Python 从数据库重新加载 django 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4377861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:29:32  来源:igfitidea点击:

Reload django object from database

pythondjangodjango-models

提问by grep

Is it possible to refresh the state of a django object from database? I mean behavior roughly equivalent to:

是否可以从数据库刷新 django 对象的状态?我的意思是行为大致相当于:

new_self = self.__class__.objects.get(pk=self.pk)
for each field of the record:
    setattr(self, field, getattr(new_self, field))

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.

更新:在跟踪器中发现了重新打开/不会修复的War:http://code.djangoproject.com/ticket/901 。仍然不明白为什么维护者不喜欢这个。

采纳答案by Tim Fletcher

As of Django 1.8 refreshing objects is built in. Link to docs.

从 Django 1.8 开始,刷新对象是内置的。链接到 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)

回答by Rory

I've found it relatively easy to reload the object from the databaselike so:

我发现像这样从数据库重新加载对象相对容易:

x = X.objects.get(id=x.id)

回答by Eloff

In reference to @grep's comment, shouldn't it be possible to do:

关于@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

回答by Ron

As @Flimm pointed out, this is a really awesome solution:

正如@Flimm 指出的,这是一个非常棒的解决方案:

foo.refresh_from_db()

This reloads all data from the database into the object.

这会将数据库中的所有数据重新加载到对象中。