本文介绍了从数据库重新加载 django 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以从数据库中刷新 django 对象的状态?我的意思是行为大致相当于:
Is it possible to refresh the state of a django object from database? I mean behavior roughly equivalent to:
new_self = self.__class__.objects.get(pk=self.pk)
for each field of the record:
setattr(self, field, getattr(new_self, field))
更新:在跟踪器中发现重新打开/不会修复战争:http://code.djangoproject.com/ticket/901.还是不明白为什么维护者不喜欢这个.
UPDATE: Found a reopen/wontfix war in the tracker: http://code.djangoproject.com/ticket/901.Still don't understand why the maintainers don't like this.
推荐答案
自 Django 1.8 起,刷新对象已内置.链接到文档.
As of Django 1.8 refreshing objects is built in. Link to docs.
def test_update_result(self):
obj = MyModel.objects.create(val=1)
MyModel.objects.filter(pk=obj.pk).update(val=F('val') + 1)
# At this point obj.val is still 1, but the value in the database
# was updated to 2. The object's updated value needs to be reloaded
# from the database.
obj.refresh_from_db()
self.assertEqual(obj.val, 2)
这篇关于从数据库重新加载 django 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!