我如何限制Django的GenericForeignKey到模型列表?

有没有告诉Django的一种方式,有一个内容types的GenericForeignKey只能指向预定义列表中的模型? 例如,我有4个模型:A,B,C,D和一个包含GenericForeignKey的模型X. 我可以告诉X,GenericForeignKey只允许A和B吗?

例如,您的应用程序是app和app2,应用程序中有A,B模型,app2中有C,D模型。 你只想看到app.A和app.B和app2.C

class TaggedItem(models.Model): tag = models.SlugField() limit = models.Q(app_label = 'app', model = 'a') | models.Q(app_label = 'app', model = 'b') | models.Q(app_label = 'app2', model = 'c') content_type = models.ForeignKey(ContentType, limit_choices_to = limit) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') 

在ForeignKey上使用limit_choices_to。

检查django文档的细节和Q对象,app_label。 你需要编写适当的app_label和model。 这只是代码片段

加上:我认为你写错了app_label。 这可以帮助你。

  from django.contrib.contenttypes.models import ContentType for c in ContentType.objects.all(): print(c.app_label, c.model)