我想在抽象模型类上创建以便将来继承,如下所示:
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
orrelated_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/