python - Django:如何在抽象模型类中设置ForeignKey related_name?

标签 python django django-models django-rest-framework

我想在抽象模型类上创建以便将来继承,如下所示:

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 section of the documentation说,你可以:

To work around this problem, when you are using related_name or related_query_name in an abstract base class (only), part of the value should contain '%(app_label)s' and '%(class)s'.

  • '%(class)s' is replaced by the lowercased name of the child class that the field is used in.

  • '%(app_label)s' is replaced by the lowercased name of the app the child class is contained within. Each installed application name must be unique and the model class names within each app must also be unique, therefore the resulting name will end up being different.

因此您可以使用:

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

    class Meta:
        abstract = True

然后是related_name将是<i>foo</i>_created_by如果继承的模型的名称名为 foo

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

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

    class Meta:
        abstract = True

然后是related_name将是<i>bar</i>_<i>foo</i>_created_by如果继承的模型的名称名为 foo 在名为 bar 的应用程序中

关于python - Django:如何在抽象模型类中设置ForeignKey related_name?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72588287/

相关文章:

python - 网络浏览器何时发送 If-Modified-Since?

python - 模块未定义属性/类

django - 转换有关 AlterField django 迁移的数据

python - 基于文件的缓存在 python 中过期

python - 从 Python 下载/安装 Windows 更新

python - 找不到 msguniq。确保安装了 GNU gettext 工具 0.15 或更新版本。 (Django 1.8 和 OSX ElCapitan)

python - 在 Django 的 admin change_form 中创建自定义按钮

Django 动态 OR 查询

python - 如何在 Django 中更改上传文件的文件名?

Python:两个变量什么时候指向内存中的同一个对象?