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

查看:149
本文介绍了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>

这是我的模型看起来像:

Here is what my models look like:

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?

感谢您的帮助,
Joe

Thanks for you help, Joe

更新:请注意,我打算使用mixin的一些我的模型使用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):

而不是您的活动 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天全站免登陆