Search code examples
djangodjango-modelsdjango-southdjango-orm

Mixin inhheritance for models in django


Is there a way to build django models hierarchy like this?

class LikableObjectMixin(models.Model):
    # mixin for all likable objects: posts, photos, etc
    likers = models.ManyToManyField(Account)

    class Meta:
        abstract = True

    def save():
        super(LikableObjectMixin, self).save()


class Post(LikableObjectMixin, models.Model):
    message = models.TextField(_('Post'))
    author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='posts', blank=True, null=True)
    created = models.DateTimeField(auto_now_add=True)

Can south work with this kind of inheritance? Is this an appropriate way to build model hierarchy?

Django=1.5.1


Solution

  • Yes, it's perfectly fine. South will create proper m2m relations for all your models that inherit from your mixin. You don't even have to write save method explicitly. So:

    class LikableObjectMixin(models.Model):
        likers = models.ManyToManyField(Account)
    
        class Meta:
            abstract = True
    
    
    class Post(LikableObjectMixin):
        message = models.TextField(_('Post'))