【问题标题】:Using a filter to limit a GenericForeignKey model list with django-polymorphic使用过滤器来限制具有 django-polymorphic 的 GenericForeignKey 模型列表
【发布时间】:2015-04-16 07:51:30
【问题描述】:

我有许多继承自 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 对象(或我需要做的任何事情)以便能够在相关对象(即 related_model = models.ForeignKey(ContentType))上设置 limit_choices_to。

TIA!

【问题讨论】:

    标签: python django polymorphism django-contenttypes


    【解决方案1】:

    这是 Django Polymorphic 的内置功能,您无需创建 GenericForeignKey,只需创建一个常规的 ForeinKeyModelA,其余的由 Django Polymorphic 处理。

    更多信息请见Django Polymorphic's documentation on ForeignKeys

    【讨论】:

    • 太棒了!我早该知道的!
    猜你喜欢
    • 2011-09-14
    • 2014-05-05
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多