Django 模型混合: 从模型继承。模型还是从对象继承?

这是一个关于 PythonMixins 的问题,通常可能会很有用。我只是使用 Django 模型,因为这是我最熟悉的用例。

混合函数应该继承被设计用来混合“对象”的类还是从“对象”继承?

通过代码示例,根据您想要实现的目标,什么更正确、更好或更好?

这个

class TaggingMixin(models.Model):
tag = models.ForeignKey(Tag)


class Meta:
abstract = True


class MyModel(models.Model, TaggingMixin):
title = models.CharField(max_length=100)

或者这样:

class TaggingMixin(object):
tag = models.ForeignKey(Tag)


class Meta:
abstract = True


class MyModel(models.Model, TaggingMixin):
title = models.CharField(max_length=100)

我认为从对象继承是正确的方法。但我在网上看到了第一个案例。

编辑: 我已经将我的后续问题转移到另一个问题: < a href = “ https://stackoverflow.com/questions/3263417/Django 抽象模型 vs-simple-Python-Mixins-vs-Python-ABCs”> Django 抽象模型 vs

34190 次浏览

This looks like a job for an abstract model.

EDIT:

Those are not mixins per se. Or rather, they do not need to be. You can derive from an abstract model directly.

I would recommend that it inherits from object. That way you can ensure that it only provides those methods and attributes you actually define explicitly.

Also, you should always ensure that you put the mixin class first when defining your concrete class. Python's resolution rules mean that the superclasses are searched in order of their definition in the class declaration, and resolution stops when a matching attribute is found. So if your mixin defines a method that is also defined by the main superclass, your mixin method won't be found.

When you inherits from plain Python object South doesn't create a migration so you can't use this approach

Django does a lot of meta magic when it comes to its model classes, so unfortunately the usual approach to mixins as suggested in Daniel Roseman's answer -- where they inherit from object -- does not work well in the Django universe.

The correct way to structure your mixins, using the example provided, would be:

class TaggingMixin(models.Model):
tag = models.ForeignKey(Tag)


class Meta:
abstract = True


class MyModel(TaggingMixin):
title = models.CharField(max_length=100)

Important points here being:

  • Mixins inherit from model.Model but are configured as an abstract class.
  • Because mixins inherit from model.Model, your actual model should not inherit from it. If you do, this might trigger a consistent method resolution order exception.