gpt4 book ai didi

python - 如何在抽象模型的 ManyToMany 字段中设置 related_name?

转载 作者:行者123 更新时间:2023-12-05 02:15:18 26 4
gpt4 key购买 nike

我有这个抽象模型:

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

messages = models.ManyToManyField(SystemMessage, related_name=?)

我打算在至少三个其他模型中使用这个抽象模型,比方说 A、B 和 C。如何为这些类动态设置 related_name?例如,对于 B 类,我希望 related_name 为 Bs。有可能吗?

为了进一步澄清问题,类将如下所示:

class B(HasSystemMessage):
# Some model fields
class A(HasSystemMessage):
# Some model fields

HasSystemMessage.objects.filter(a__contains=[some elements])

最佳答案

您可以使用 %(class)s%(app_label)s

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

messages = models.ManyToManyField(SystemMessage, related_name=%(app_label)s_%(class)s_related)

来自 Django 文档

Be careful with related_name and related_query_name¶ If you are using related_name or related_query_name on a ForeignKey or ManyToManyField, you must always specify a unique reverse name and query name for the field. This would normally cause a problem in abstract base classes, since the fields on this class are included into each of the child classes, with exactly the same values for the attributes (including related_name and related_query_name) each time.

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 lower-cased name of the child class that the field is used in. '%(app_label)s' is replaced by the lower-cased 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.

引用:https://docs.djangoproject.com/en/2.0/topics/db/models/#be-careful-with-related-name-and-related-query-name

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com