有没有办法告诉django,一个拥有contenttypes GenericForeignKey的模型只能指向预定义列表中的模型?例如,我有4个模型: A、B、C、D和一个包含GenericForeignKey的模型X。我可以告诉X只允许A和B访问GenericForeignKey吗?
发布于 2011-06-14 05:20:14
例如,你的应用程序是app和app2,app中有A,B型号,app2中有C,D型号。您只希望看到app.A和app.B以及app2.C
from django.db import models
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 docs以了解详细信息和Q对象,app_label。您需要编写适当的app_label和模型。这只是代码片段
另外:我认为你写错了app_label。这可以帮助你。
from django.contrib.contenttypes.models import ContentType
for c in ContentType.objects.all():
print(c.app_label, c.model)
https://stackoverflow.com/questions/6335986
复制相似问题