开发者

Is it OK to use multiple inheritance with Django abstract models? [closed]

开发者 https://www.devze.com 2023-03-14 21:36 出处:网络
Closed. This question is opinion-based. It is not currently accepting answers. Want to improve this question? Update the question so it can be answered with facts and citations by editing th
Closed. This question is opinion-based. It is not currently accepting answers.

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 question

I 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?

0

精彩评论

暂无评论...
验证码 换一张
取 消