问题描述
有没有办法告诉django一个内容类型GenericForeignKey的模型只能指向来自预定义列表的模型?例如,我有4个模型:A,B,C,D和一个拥有GenericForeignKey的模型X。我可以告诉X只有A& B允许用于GenericForeignKey?例如,
您的应用程序是app和app2,应用程序中的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')| model.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在ContentType.objects中为c导入ContentType
。 all():
print(c.app_label,c.model)
Is there a way of telling django that a model having a contenttypes GenericForeignKey can only point to models from a predefined list? For example, I have 4 models: A, B, C, D and a model X that holds a GenericForeignKey. Can I tell X that only A & B are allowed for the GenericForeignKey?
For example,your apps are app and app2 and there are A, B models in app and there are C, D models in app2.you want to see only app.A and app.B and 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')
use limit_choices_to on ForeignKey.
check django docs for details and Q objects, app_label.you need to write proper app_label and model. This is just code snippet
plus: I think you write wrong app_label. This can help you.
from django.contrib.contenttypes.models import ContentType
for c in ContentType.objects.all():
print(c.app_label, c.model)
这篇关于如何将Django的GenericForeignKey限制为模型列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!