본문 바로가기
개발/Python

[파이썬] 데이터베이스에서 django 객체 reload

by MinorMan 2021. 1. 12.
반응형

<질문>

데이터베이스에서 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. 관리자가 왜 이것을 좋아하지 않는지 여전히 이해하지 못합니다.


<답변1>

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)

<답변2>

나는 그것이 상대적으로 쉽다는 것을 알았습니다.reload the object from the database이렇게 :

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

<답변3>

@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

<답변4>

@Flimm이 지적했듯이 이것은 정말 멋진 솔루션입니다.

foo.refresh_from_db()

이렇게하면 데이터베이스의 모든 데이터가 개체로 다시로드됩니다.

728x90

댓글