是否可以从数据库中刷新 django 对象的状态?我的意思是行为大致相当于:
new_self = self.__class__.objects.get(pk=self.pk)
for each field of the record:
setattr(self, field, getattr(new_self, field))
更新:在跟踪器中发现了重新打开/不会修复 war :http://code.djangoproject.com/ticket/901 . 还是不明白为什么维护者不喜欢这个。
最佳答案
从 Django 1.8 开始,内置刷新对象。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)
关于python - 从数据库重新加载 django 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4377861/