是否可以从数据库中刷新 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。仍然不明白为什么维护者不喜欢这个。
commmit
之后 才能更改数据库对象。完成此操作后,您必须等待下一个 SQL 事务提交。为什么要这样做?你要等多久才能完成下一笔交易?
从 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)
我发现像这样reload the object from the database相对容易:
x = X.objects.get(id=x.id)
refresh_from_db
解决了所有这些问题。
正如@Flimm 指出的那样,这是一个非常棒的解决方案:
foo.refresh_from_db()
这会将数据库中的所有数据重新加载到对象中。
参考@grep的评论,不应该这样做:
# Put this on your base model (or monkey patch it onto django's Model if that's your thing)
def reload(self):
new_self = self.__class__.objects.get(pk=self.pk)
# You may want to clear out the old dict first or perform a selective merge
self.__dict__.update(new_self.__dict__)
# Use it like this
bar.foo = foo
assert bar.foo.pk is None
foo.save()
foo.reload()
assert bar.foo is foo and bar.foo.pk is not None
refresh_from_db
方法。
不定期副业成功案例分享
refresh_from_db
只会更新此类已填充的字段。refresh_from_db
时删除了基础对象,它会正确引发DoesNotExist
异常。供参考。