Simplified Model.save() a bit.

This commit is contained in:
葛汉斌 2019-05-28 21:40:31 +08:00 committed by Mariusz Felisiak
parent 67b6cb7723
commit fcbc502af9
2 changed files with 16 additions and 14 deletions

View File

@ -305,6 +305,7 @@ answer newbie questions, and generally made Django that much better:
Gasper Koren Gasper Koren
Gasper Zejn <zejn@kiberpipa.org> Gasper Zejn <zejn@kiberpipa.org>
Gavin Wahl <gavinwahl@gmail.com> Gavin Wahl <gavinwahl@gmail.com>
Ge Hanbin <xiaomiba0904@gmail.com>
geber@datacollect.com geber@datacollect.com
Geert Vanderkelen Geert Vanderkelen
George Karpenkov <george@metaworld.ru> George Karpenkov <george@metaworld.ru>

View File

@ -678,13 +678,14 @@ class Model(metaclass=ModelBase):
# been assigned and there's no need to worry about this check. # been assigned and there's no need to worry about this check.
if field.is_relation and field.is_cached(self): if field.is_relation and field.is_cached(self):
obj = getattr(self, field.name, None) obj = getattr(self, field.name, None)
if not obj:
continue
# A pk may have been assigned manually to a model instance not # A pk may have been assigned manually to a model instance not
# saved to the database (or auto-generated in a case like # saved to the database (or auto-generated in a case like
# UUIDField), but we allow the save to proceed and rely on the # UUIDField), but we allow the save to proceed and rely on the
# database to raise an IntegrityError if applicable. If # database to raise an IntegrityError if applicable. If
# constraints aren't supported by the database, there's the # constraints aren't supported by the database, there's the
# unavoidable risk of data corruption. # unavoidable risk of data corruption.
if obj:
if obj.pk is None: if obj.pk is None:
# Remove the object from a related instance cache. # Remove the object from a related instance cache.
if not field.remote_field.multiple: if not field.remote_field.multiple:
@ -699,7 +700,7 @@ class Model(metaclass=ModelBase):
setattr(self, field.attname, obj.pk) setattr(self, field.attname, obj.pk)
# If the relationship's pk/to_field was changed, clear the # If the relationship's pk/to_field was changed, clear the
# cached relationship. # cached relationship.
if obj and getattr(obj, field.target_field.attname) != getattr(self, field.attname): if getattr(obj, field.target_field.attname) != getattr(self, field.attname):
field.delete_cached_value(self) field.delete_cached_value(self)
using = using or router.db_for_write(self.__class__, instance=self) using = using or router.db_for_write(self.__class__, instance=self)