我有许多继承自 PolymorphicModel (来自 django-polymorphic)的 Django 模型。我想为特定模型类型及其子模型创建 GenericForeignKey 关系。
类似于:
# application_one/models.py
from django.db import models
from polymorphic import PolymorphicModel
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class ModelA(PolymorphicModel):
name = models.CharField(max_length=100)
class ModelB(ModelA):
new_property = models.CharField(max_length=100)
class ModelC(ModelA):
other_property = models.CharField(max_length=100)
class OtherModel(models.Model):
pass
class ModelWithRelation(models.Model):
# We want to limit the related_model to ModelA, or it's children
related_model = models.ForeignKey(ContentType)
object_id = models.IntegerField()
content_object = GenericForeignKey('related_model', 'object_id')
--- 和 ---
# application_two/models.py
from application_one.models import ModelA
class ModelD(ModelA):
pass
您可以通过在 limit_choices_to
中显式指定模型名称来限制 ContentType 的选择,但我实际上希望这是对 ModelA 子级的动态查询,因为在我们的应用程序中,我们期待子级ModelA 存在于其他应用程序中,并且不想在 application_one 中定义它们。
我将如何定义一个 Q 对象(或我需要做的任何事情)以便能够在相关对象上设置 limit_choices_to (即 lated_model = models.ForeignKey(ContentType)
)。
TIA!
最佳答案
这是Django Polymorphic的内置功能,您不需要创建GenericForeignKey
,只需为ModelA创建一个常规的
code> 和 Django Polymorphic 将处理剩下的事情。ForeinKey
即可
关于python - 使用过滤器通过 django-polymorphic 限制 GenericForeignKey 模型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29668549/