问题描述
有没有办法告诉 Django 具有 contenttypes GenericForeignKey 的模型只能指向预定义列表中的模型?例如,我有 4 个模型:A、B、C、D 和一个包含 GenericForeignKey 的模型 X.我可以告诉 X 只有 A &B 是否允许用于 GenericForeignKey?
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?
推荐答案
例如,您的应用程序是 app 和 app2,app 中有 A、B 模型,app2 中有 C、D 模型.您只想看到 app.A 和 app.B 和 app2.C
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
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')
在外键上使用 limit_choices_to.
use limit_choices_to on ForeignKey.
检查 django 文档以获取详细信息和 Q 对象,app_label.您需要编写适当的 app_label 和模型.这只是代码片段
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:我认为你写错了 app_label.这可以帮助您.
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 限制为模型列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!