gpt4 book ai didi

Django 自动从抽象元类继承 "abstract = true"

转载 作者:行者123 更新时间:2023-12-05 08:35:14 24 4
gpt4 key购买 nike

我正在使用以下代码。

class CommonFunctions(object):

def get_absolute_url(self):
return "/{0}/list/".format(self.__class__.__name__).lower()

def get_fields(self):
return [(field, field.value_to_string(self)) for field in (self.__class__)._meta.fields]

class Meta:
abstract = True

类是

class Book(models.Model, CommonFunctions):
book_name = models.CharField(max_length=30)
book_area = models.CharField(max_length=30)

现在,如果我使用它,我会得到一个错误,

ForeignKey cannot define a relation with abstract class

但是如果我用

 class Meta:
abstract = False

然后在 Book 类中它就可以工作了。

如果它们的 documentation 为什么要继承 true说它应该继承false

Django does make one adjustment to the Meta class of an abstract base class: before installing the Meta attribute, it sets abstract=False. This means that children of abstract base classes don't automatically become abstract classes themselves.

最佳答案

您的CommonFunctions 应该基于models.Model,而不是object。这样,您将获得 Django 文档中所述的行为。

class CommonFunctions(models.Model):

def get_absolute_url(self):
return "/{0}/list/".format(self.__class__.__name__).lower()

def get_fields(self):
return [(field, field.value_to_string(self)) for field in (self.__class__)._meta.fields]

class Meta:
abstract = True

然后您的 Book 类应该仅基于 CommonFunctions

class Book(CommonFunctions):
book_name = models.CharField(max_length=30)
book_area = models.CharField(max_length=30)

关于Django 自动从抽象元类继承 "abstract = true",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6518655/

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