[英]Limit model choices on foreign key Django
我有以下字段
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 上,我找不到有关如何限制位于不同应用程序上的相关模型的文档。 有人可以帮忙吗。
您可以使用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')
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.