Django automatically inheriting "abstract = true" from an abstract meta class
I am using the following code.
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
The class is
class Book(models.Model, CommonFunctions):
book_name = models.CharField(max_length=30)
book_area = models.CharField(max_length=30)
Now if I use this I get an error,
ForeignKey
cannot define a relation with abstract class
But if I use
class Meta:
abstract = False
in the Book
class then it works.
Why is it inheriting true
if their documentati开发者_Python百科on says it should inherit 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.
Your CommonFunctions
should be based on models.Model
, not object
. This way, you will get the behavior stated in the Django documentation.
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
And then your Book
class should be based only on CommonFunctions
.
class Book(CommonFunctions):
book_name = models.CharField(max_length=30)
book_area = models.CharField(max_length=30)
精彩评论