我有几个字段要添加到项目中的大多数模型中。例如,这些字段是“跟踪字段”,例如创建日期、更新日期和“活动”标志。我正在尝试创建一个 Mixin,我可以将它添加到每个模型类中,这样我就可以通过多重继承添加这些额外的字段。但是,当创建对象实例时,通过 Mixin 添加的模型字段似乎显示为对象的方法而不是数据库字段。
In [18]: Blog.objects.all()[0].created
Out[18]: <django.db.models.fields.DateTimeField object at 0x10190efd0>
这是我的模型的样子:
from django.db import models
class Blog(models.Model, TrackingFieldMixin):
name = models.CharField(max_length=64)
type = models....
class TrackingFieldsMixin():
active = models.BooleanField(default=True,
help_text=_('Indicates whether or not this object has been deleted.'))
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
所以这似乎不起作用。有谁知道我如何能够为类似于上面的常见模型字段创建可重用的 mixin?这种方法有缺陷吗?
谢谢你的帮助,乔
更新:请注意,我计划使用 mixin 的一些模型使用 MPTT 模型,因此我不能简单地将 TrackingFieldMixin 混合在基类中并仅从它继承。
class Post(MPTTModel, TrackingFieldMixin):
post_name = models....
post_type = models...