Django:为可重用的模型字段创建 Mixin [英] Django: Creating a Mixin for Reusable Model Fields

查看:33
本文介绍了Django:为可重用的模型字段创建 Mixin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个字段要添加到项目中的大多数模型中.例如,这些字段是跟踪字段",例如创建日期、更新日期和活动"标志.我正在尝试创建一个 Mixin,我可以将它添加到每个模型类中,这将允许我通过多重继承添加这些额外的字段.但是,当创建对象实例时,我通过 Mixin 添加的模型字段似乎显示为对象的方法而不是数据库字段.

I've got a few fields that I want to add to most every model in my project. For example, these fields are "tracking fields" such as a created date, an update date, and an "active" flag. I'm attempting to create a Mixin that I could add to each model class that would allow me to add these extra fields via multiple inheritance. However, when an object instance is created, it appears that my model fields that were added via the Mixin show up as methods of the object rather than database fields.

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?这种方法有缺陷吗?

So this doesn't appear to work. Does anyone know how I am able to create a reusable mixin for common model fields similar to above? Is there a flaw in this approach?

谢谢你的帮助,乔

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

Update: Note that some of my models that I plan to use the mixin in use the MPTT model, so I can't simply make my TrackingFieldMixin mixin the base class and inherit only from it.

class Post(MPTTModel, TrackingFieldMixin):
    post_name = models....
    post_type = models...

推荐答案

抽象模型仍然需要继承 model.Model 才能正常工作:

Abstract models still need to inherit from model.Model to work correctly:

class TrackingFieldsMixin(models.Model):

也不是你的 active BooleanField 我会添加一个 deleted_on DateTimeField 这样你就可以记录何时记录被删除了.然后,您可以在实例上添加属性以查看它是否处于活动状态:

Also instead of your active BooleanField I would add a deleted_on DateTimeField so you can record when the record was deleted. You can then just add properties on the instance to see if it's active:

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

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

Blog.objects.filter(deleted_on__isnull=True)

这篇关于Django:为可重用的模型字段创建 Mixin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆