Django:为可重用模型字段创建 Mixin

问题描述 投票:0回答:1

我想将一些字段添加到项目中的大多数模型中。 例如,这些字段是“跟踪字段”,例如创建日期、更新日期和“活动”标志。 我正在尝试创建一个 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

所以这似乎不起作用。 有谁知道我如何为类似于上面的常见模型字段创建可重用的混合? 这种方法有缺陷吗?

感谢您的帮助, 乔

更新:请注意,我计划在 MPTT 模型中使用 mixin 的一些模型,因此我不能简单地将 TrackingFieldMixin mixin 基类并仅从它继承。

class Post(MPTTModel, TrackingFieldMixin):
    post_name = models....
    post_type = models...
django inheritance model mixins
1个回答
35
投票

抽象模型仍然需要继承

model.Model
才能正常工作:

class TrackingFieldsMixin(models.Model):

另外,我会添加一个

active
BooleanField
,而不是您的
deleted_on
DateTimeField
,这样您就可以记录删除记录的时间。 然后,您可以在实例上添加属性来查看它是否处于活动状态:

@property
def active(self):
    return self.deleted_on is None

以及在查询和/或自定义管理器中:

Blog.objects.filter(deleted_on__isnull=True)
© www.soinside.com 2019 - 2024. All rights reserved.