Sunday, January 6, 2013

Re: Multiple model inheritance

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
 

On Monday, December 31, 2012 8:12:03 AM UTC-5, Mattias Linnap wrote:
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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/9luopcnKn1MJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment