你能找出Django Model实例是否“脏”? [英] Can you find out if a Django Model instance is "dirty"?

查看:105
本文介绍了你能找出Django Model实例是否“脏”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常喜欢SQLAlchemy的功能,可以让你看到一个对象是否是脏的:如果它是从数据库中检索到的,或者是最后一次被保存,那么它被修改了。



是否可以从Django ORM中找到这些信息?



请注意这与 django中的几个字段,因为我不在乎以前的数据是什么,虽然S.Lott的答案可能提供了一种方法它,但我想要一种不打数据库的方式。



我也看过 django.db.transaction.is_dirty (),但这似乎不是解决方案。

解决方案

做数据库查询:

  class DirtyMixin(object):
@property
def is_dirty(self) :
db_obj = self .__ class __。objects.get(self.pk)
for f in self._meta。 local_fields:
如果self .__ getattribute __(f.name)!= db_obj .__ getattribute __(f.name):
return True
return False
/ pre>

然后,您可以将其作为祖先类添加到模型中。或者,猴子修补form.Model类,如果你喜欢。

 从django.db导入模型
模型。模型.__ bases__ =(DirtyMixin,)+ models.Model .__ bases__


I really like the feature of SQLAlchemy that allows you to see if an object is dirty: if it has been modified since it was retrieved from the database, or the last time it was saved.

Is it possible to find this information from the Django ORM?

Note this is not the same as Dirty fields in django, as I don't care about what the previous data was, although S.Lott's answer may provide a way to do it, but I would like a way that doesn't hit the database.

I have also looked at the django.db.transaction.is_dirty(), but this doesn't seem to be the solution.

解决方案

A solution that does do a database query:

class DirtyMixin(object):
    @property
    def is_dirty(self):
        db_obj = self.__class__.objects.get(self.pk)
        for f in self._meta.local_fields:
            if self.__getattribute__(f.name) != db_obj.__getattribute__(f.name):
                return True
        return False

You can then add this as an ancestor class to a model. Or, monkey-patch the forms.Model class, if you like.

from django.db import models
models.Model.__bases__ = (DirtyMixin,) + models.Model.__bases__

这篇关于你能找出Django Model实例是否“脏”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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