使用过滤器限制带有 django-polymorphic 的 GenericForeignKey 模型列表

Using a filter to limit a GenericForeignKey model list with django-polymorphic

我有许多 Django 模型继承自 PolymorphicModel(来自 django-polymorphic)。我想为特定模型类型及其子模型创建 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 对象(或我需要做的任何事情)以便能够在相关对象(即 related_model = models.ForeignKey(ContentType))上设置 limit_choices_to。

TIA!

这是Django Polymorphic的内置特性,你不需要创建一个GenericForeignKey,只需要创建一个正则的ForeinKeyModelA,Django Polymorphic会带剩下的就交给你吧。

有关详细信息,请参阅 Django Polymorphic's documentation on ForeignKeys