Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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):  . . .  
like image 716
B Robster Avatar asked Jun 21 '11 15:06

B Robster


People also ask

Does Django support multiple inheritance?

Django models support multiple inheritance.

What is abstract inheritance in Django?

An abstract model is a base class in which you define fields you want to include in all child models. Django doesn't create any database table for abstract models. A database table is created for each child model, including the fields inherited from the abstract class and the ones defined in the child model.

Can a class inherit from multiple abstract classes Python?

You can only inherit the implementation of one class by directly deriving from it. You can implement multiple interfaces, but you can't inherit the implementation of multiple classes.

Why do we use abstract models in Django?

“Abstract base classes are useful when you want to put some common information into a number of other models. You write your base class and put abstract=True in the Meta class. This model will then not be used to create any database table.


1 Answers

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.

like image 134
Brutus Avatar answered Sep 21 '22 14:09

Brutus