如何在模型混合中引用字段定义中的模型名称?即,这里将替换 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()
%(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,
)