我有以下字段target_contenttype = models.ForeignKey(ContentType,
blank=True,
null=True,
related_name="target_object",
on_delete=models.PROTECT,
limit_choices_to={'model__in':( ''
)})在 limit_choices_to 上,我找不到有关如何限制位于不同应用程序上的相关模型的文档。有人可以帮忙吗。
1 回答

呼啦一阵风
TA贡献1802条经验 获得超6个赞
您可以使用get_for_model()(如果您已导入相关模型)或get_by_natural_key(),将应用程序名称和模型名称传递给它,两者均为小写:
from relatedapp.models import RelatedModel
limit_choices_to={'model__in':(
ContentType.objects.get_for_model(RelatedModel),
ContentType.objects.get_by_natural_key('relatedapp', 'relatedmodel'),
)}
另一种方法是创建一个 Q 对象来过滤应用程序标签 + 模型,两者都是小写的:
limit_choices_to=(
Q(app_label='app1', model='model1') |
Q(app_label='app2', model='model2')
)
添加回答
举报
0/150
提交
取消