Reload django object from database

前端 未结 4 846
囚心锁ツ
囚心锁ツ 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条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-13 17:23

    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
    

提交回复
热议问题