gpt4 book ai didi

django - 如何将 Django 的 GenericForeignKey 限制为模型列表?

转载 作者:行者123 更新时间:2023-11-28 19:33:33 29 4
gpt4 key购买 nike

有没有办法告诉 django 具有 contenttypes GenericForeignKey 的模型只能指向预定义列表中的模型?例如,我有 4 个模型:A、B、C、D 和一个包含 GenericForeignKey 的模型 X。我可以告诉 X GenericForeignKey 只允许使用 A 和 B 吗?

最佳答案

例如,您的应用程序是 app 和 app2,app 中有 A、B 模型,app2 中有 C、D 模型。你只想看到 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')

在 ForeignKey 上使用 limit_choices_to。

查看 django 文档以获取详细信息和 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)

关于django - 如何将 Django 的 GenericForeignKey 限制为模型列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6335986/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com