반응형
데이터베이스에서 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 추적기에서 재 개설 / 원터치 전쟁이 발견되었습니다 . 여전히 관리자가 왜 이것을 좋아하지 않는지 이해하지 못합니다.
Django 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)
@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
@Flimm이 지적했듯이 이것은 정말 멋진 솔루션입니다.
foo.refresh_from_db()
데이터베이스의 모든 데이터가 개체로 다시로드됩니다.
참고 URL : https://stackoverflow.com/questions/4377861/reload-django-object-from-database
반응형
'Programing' 카테고리의 다른 글
SQL Server 2012 Express 버전의 차이점은 무엇입니까? (0) | 2020.06.25 |
---|---|
constexpr에서 std :: string을 사용할 수 있습니까? (0) | 2020.06.25 |
지정된 문자열로 시작하는 파일 이름을 가진 모든 파일을 찾으십니까? (0) | 2020.06.24 |
TypeScript에서 숫자를 문자열로 캐스팅 (0) | 2020.06.24 |
C # 스위치 명령문 제한-왜? (0) | 2020.06.24 |