Multiple model inheritance

39 views
Skip to first unread message

Mattias Linnap

unread,
Dec 31, 2012, 8:12:03 AM12/31/12
to django...@googlegroups.com
Hi all,

I would like to define multiple abstract base models with small set of
fields each. The "real" models inherit from multiple mixins to add the
fields.

For example:
class Taggable(?):
tag = models.CharField()
class Visible(?):
visible = models.BooleanField()
class SomeFullModel(?, Taggable, Visible):
otherfield = models.CharField()

With this use case:
* should the abstract models inherit from models.Model, or be a plain
Python class inheriting from object?
* should all or any of the abstract models have a class Meta with
abstract=True?
* should the final real model inherit from models.Model (probably
required if all the mixins are plain classes), or inherit from the
first mixin that is an abstract model?
* does the order of the base classes in SomeFullModel matter?

Thanks,

Mattias

Peter of the Norse

unread,
Jan 6, 2013, 2:33:08 AM1/6/13
to django...@googlegroups.com
I’m not sure that’s possible. Even abstract Models do magic in the background. Specifically there's the _meta class attribute that gets inherited. If you were to try it, only one of the _metas would be included.
> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To post to this group, send email to django...@googlegroups.com.
> To unsubscribe from this group, send email to django-users...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
>

Peter of the Norse
Rahm...@Radio1190.org



nkryptic

unread,
Jan 6, 2013, 9:30:59 AM1/6/13
to django...@googlegroups.com
yes, yes, no and yes. Abstract models should inherit form models.Model.  Abstract models should always have a Meta class with abstract=True.  The order matters when it comes to shared functionality.  Here's how I would code those models you had:

class Taggable(models.Model):
    tag = models.CharField()
    class Meta:
        abstract = True

class Visible(models.Model):
    visible = models.BooleanField()
    class Meta:
        abstract = True

class SomeFullModel(Taggable, Visible):
    otherfield = models.CharField()


If you override a method on all three of those classes (e.g. the save method) and in each of them, call super(...).save(), then the order be:
SomeFullModel.save() => Taggable.save() => Visible.save() => models.Model.save()

As to how the Meta class is inherited, I'll point you to https://docs.djangoproject.com/en/1.4/topics/db/models/#meta-inheritance
Reply all
Reply to author
Forward
0 new messages