从数据库重新加载Django对象
有没有办法从数据库中刷新一个django对象的状态?我的意思是,想要的效果大概是这样的:
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。我还是不明白为什么维护者不喜欢这个。
4 个回答
26
正如@Flimm提到的,这真是一个很棒的解决方案:
foo.refresh_from_db()
这个方法会把数据库里的所有数据重新加载到对象里。
31
我发现从数据库中重新加载对象其实挺简单的,像这样:
x = X.objects.get(id=x.id)
357
从Django 1.8开始,刷新对象的功能已经内置了。你可以查看这段文档了解更多信息:文档链接。
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)