如何在 Django 模型混合字段定义中引用模型名称?

问题描述 投票:0回答:1

如何在模型混合中引用字段定义中的模型名称?即,这里将替换 model_name:

class CreatedByMixin(models.Model):

    class Meta:
        abstract = True

    created_by = ForeignKey(
        User,
        verbose_name="Created by",
        help_text="User that created the record",
        related_name=f"{model_name}_created",
        editable=False,
    )

该模型的相关名称是“MyModel_created”?

class MyModel(UserAuditMixin, TimeStampedModel):
    class Meta:
        db_table_comment = "Participants are the users that are involved in the transcript"

    field1 = models.TextField()
django orm
1个回答
0
投票

您正在寻找

%(class)s
 [Django-doc]。您不会在
ForeignKey
中格式化字符串:Django 自动(重新)格式化字符串,因此您使用:

class CreatedByMixin(models.Model):
    class Meta:
        abstract = True

    created_by = ForeignKey(
        User,
        verbose_name='Created by',
        help_text='User that created the record',
        related_name='%(class)s_created',
        editable=False,
    )
© www.soinside.com 2019 - 2024. All rights reserved.