在Django管理器中,添加泛型关系的内联

2024-04-23 07:15:41 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我的简化模型:

from django.contrib.contenttypes.fields import (
    GenericForeignKey, GenericRelation)
from django.db import models
from django.utils.translation import ugettext_lazy as _


class Thing(models.Model):
    '''
    Our 'Thing' class
    with a link (generic relationship) to an abstract config
    '''

    name = models.CharField(
        max_length=128, blank=True,
        verbose_name=_(u'Name of my thing'))

    # Link to our configs
    config_content_type = models.ForeignKey(
        ContentType,
        null=True,
        blank=True)
    config_object_id = models.PositiveIntegerField(
        null=True,
        blank=True)
    config_object = GenericForeignKey(
        'config_content_type',
        'config_object_id')


class Config(models.Model):
    '''
    Base class for custom Configs
    '''
    class Meta:
        abstract = True

    name = models.CharField(
        max_length=128, blank=True,
        verbose_name=_(u'Config Name'))

    thing = GenericRelation(
        Thing,
        related_query_name='config')


class FirstConfig(Config):
    pass


class SecondConfig(Config):
    pass

这里是管理员:

^{pr2}$

到目前为止,我有一个Thing对象和一个FirstConfig对象链接在一起。 代码被简化了:在一个无关紧要的部分,我设法在创建一个东西时创建我的抽象配置,并设置了正确的内容类型/对象标识

现在我希望在ThingAdmin中将这个FirstConfig实例看作一个inline(FirstConfigInline)。在

我试过用django.contrib.contenttypes.admin.GenericsTackedLine,但它不适用于我当前的型号设置。
我尝试使用FirstConfigInline的fk_name参数。
同样,正如您所见,我试图在配置模型上使用'thing'genericrationation属性,但没有成功。。在

你知道如何正确设置管理员吗?在


Tags: 对象djangonamefromimportconfigtrueobject
1条回答
网友
1楼 · 发布于 2024-04-23 07:15:41

根据Django Docs你必须定义ct_fk_字段和ct_字段(如果它们从默认值更改)。因此,将ct_字段设置为config_content_type就足够了。在

希望它能起作用!在

编辑:必须在内联中声明这些值:

class SecondConfigInline(admin.StackedInline):
    model = SecondConfig
    ct_fk_field = "config_object_id"
    ct_field = "config_content_type"

编辑2:

我刚刚意识到我的假设有一个错误。通常您应该在内联模型上声明Foreignkey。根据代码的其余部分,您可以删除Thing上的generic Foreignkey+Config上的genericrational,然后在Config Basemodel上声明一个普通的Foreignkey。在

相关问题 更多 >