Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
开发者_开发技巧Closed 2 years ago.
Improve this questionI have three different abstract model base classes . . . I'd like to use them in multiple inheritance, sort of like Mixins. Any problems with this?
E.g.,
class TaggableBase(models.Model):
. . .
class Meta:
abstract = True
class TimeStampedBase(models.Model):
. . .
class Meta:
abstract = True
class OrganizationalBase(models.Model):
. . .
class Meta:
abstract = True
class MyTimeStampedTaggableOrganizationalModel(OrganizationalBase, TimeStampedBase, TaggableBase):
. . .
If you use any fields at all in your class, inherit from models.Model
.
Otherwise Django will ignore those fields (the attributes will still be there in Python, but no fields will be created in the DB). Set abstract = True
to get "mixin" like behavior (i.e. no DB tables will be created for the mixins but for the models using those mixins).
If you don't use any fields, you can just inherit from object
, to keep things plain and simple.
I do this all the time with my classes and model classes. It's one of the best things in Python, in my opinion.
Sounds like for what you're trying to do, mixins really are the best fit. A simple google search will find lots of articles on implementing mixins in python, such as this one. I'm not sure multiple inheritance is the best way to go about doing it, so you might want to explore all the other options. What else have you thought about?
精彩评论