Mixin inhheritance用于django中的模型

时间:2013-07-09 10:45:15

标签: django django-models django-south django-orm

有没有办法像这样构建django模型层次结构?

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)

南方可以使用这种继承吗?这是构建模型层次结构的合适方法吗?

的Django = 1.5.1

1 个答案:

答案 0 :(得分:1)

是的,完全没问题。 South将为您继承mixin的所有模型创建适当的m2m关系。您甚至不必明确地编写save方法。所以:

class LikableObjectMixin(models.Model):
    likers = models.ManyToManyField(Account)

    class Meta:
        abstract = True


class Post(LikableObjectMixin):
    message = models.TextField(_('Post'))