我有以下字段
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')
)
关于python - 限制外键 Django 的模型选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55062567/