programing

데이터베이스에서 jango 개체 다시 로드

css3 2023. 7. 19. 21:32

데이터베이스에서 jango 개체 다시 로드

데이터베이스에서 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.8부터는 새로 고침 대상이 내장되어 있습니다.문서에 연결합니다.

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)

데이터베이스에서 개체를 비교적 쉽게 다시 로드할 수 있습니다.

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

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

foo.refresh_from_db()

그러면 데이터베이스의 모든 데이터가 개체로 다시 로드됩니다.

@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

언급URL : https://stackoverflow.com/questions/4377861/reload-django-object-from-database