Reload django object from database

前端 未结 4 839
囚心锁ツ
囚心锁ツ 2020-12-13 16:30

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         


        
4条回答
  •  Happy的楠姐
    2020-12-13 17:08

    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)
    

提交回复
热议问题