从数据库重新加载Django对象

问题:从数据库重新加载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 。仍然不明白为什么维护者不喜欢这个。

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))

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.


回答 0

从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)

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)

回答 1

我发现从数据库中重新加载对象相对容易,如下所示:

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

I’ve found it relatively easy to reload the object from the database like so:

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

回答 2

在引用@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

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

# 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

回答 3

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

foo.refresh_from_db()

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

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

foo.refresh_from_db()

This reloads all data from the database into the object.