繁体   English   中英

Django:如何在Abstract Model class中设置ForeignKey related_name?

[英]Django: how to set ForeignKey related_name in Abstract Model class?

我想在 Abstract Model class 上创建这样的未来继承:

class AbstractModel(models.Model):

    created_at = models.DateTimeField(
        auto_now_add=True,
        blank=True,
        null=True,
    )

    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        related_name='XXX_created_by',
        blank=True,
        null=True,
    )

    class Meta:
        abstract = True

字段“created_at”工作正常,但如何为我的子类在“created_by”中生成 related_name 以防止冲突?

正如文档的Be careful with related_name and related_query_name部分所说,您可以:

要解决此问题,当您在抽象基related_query_name (仅)中使用related_name或 related_query_name 时,部分值应包含'%(app_label)s''%(class)s'

  • '%(class)s'替换为使用该字段的子项 class 的小写名称

  • '%(app_label)s'替换为包含子 class的应用程序的小写名称 每个安装的应用程序名称必须是唯一的,并且每个应用程序中的 model class 名称也必须是唯一的,因此最终的名称将是不同的。

因此,您可以使用:

class AbstractModel(models.Model):
    # …
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        related_name='%(class)s_created_by',
        blank=True,
        null=True,
    )

    class Meta:
        abstract = True

_created_by if the name of the model that inherits is named foo .如果继承的related_name的名称名为foo ,则 related_name 将为 _created_by

或者,如果相同的 model 名称可以出现在不同的应用程序中:

class AbstractModel(models.Model):
    # …
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        related_name='%(app_label)s_%(class)s_created_by',
        blank=True,
        null=True,
    )

    class Meta:
        abstract = True

_ _created_by if the name of the model that inherits is named foo in an app named bar .如果继承的related_name的名称在名为bar的应用程序中名为foo ,则 related_name 将为 _ _created_by

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM