(self, operation_name, fields=None)
| 1258 | self.__dict__.pop(field.attname, None) |
| 1259 | |
| 1260 | def _prepare_related_fields_for_save(self, operation_name, fields=None): |
| 1261 | # Ensure that a model instance without a PK hasn't been assigned to |
| 1262 | # a ForeignKey, GenericForeignKey or OneToOneField on this model. If |
| 1263 | # the field is nullable, allowing the save would result in silent data |
| 1264 | # loss. |
| 1265 | for field in self._meta.concrete_fields: |
| 1266 | if fields and field not in fields: |
| 1267 | continue |
| 1268 | # If the related field isn't cached, then an instance hasn't been |
| 1269 | # assigned and there's no need to worry about this check. |
| 1270 | if field.is_relation and field.is_cached(self): |
| 1271 | obj = getattr(self, field.name, None) |
| 1272 | if not obj: |
| 1273 | continue |
| 1274 | # A pk may have been assigned manually to a model instance not |
| 1275 | # saved to the database (or auto-generated in a case like |
| 1276 | # UUIDField), but we allow the save to proceed and rely on the |
| 1277 | # database to raise an IntegrityError if applicable. If |
| 1278 | # constraints aren't supported by the database, there's the |
| 1279 | # unavoidable risk of data corruption. |
| 1280 | if not obj._is_pk_set(): |
| 1281 | # Remove the object from a related instance cache. |
| 1282 | if not field.remote_field.multiple: |
| 1283 | field.remote_field.delete_cached_value(obj) |
| 1284 | raise ValueError( |
| 1285 | "%s() prohibited to prevent data loss due to unsaved " |
| 1286 | "related object '%s'." % (operation_name, field.name) |
| 1287 | ) |
| 1288 | elif getattr(self, field.attname) in field.empty_values: |
| 1289 | # Set related object if it has been saved after an |
| 1290 | # assignment. |
| 1291 | setattr(self, field.name, obj) |
| 1292 | # If the relationship's pk/to_field was changed, clear the |
| 1293 | # cached relationship. |
| 1294 | if getattr(obj, field.target_field.attname) != getattr( |
| 1295 | self, field.attname |
| 1296 | ): |
| 1297 | field.delete_cached_value(self) |
| 1298 | # GenericForeignKeys are private. |
| 1299 | for field in self._meta.private_fields: |
| 1300 | if fields and field not in fields: |
| 1301 | continue |
| 1302 | if ( |
| 1303 | field.is_relation |
| 1304 | and field.is_cached(self) |
| 1305 | and hasattr(field, "fk_field") |
| 1306 | ): |
| 1307 | obj = field.get_cached_value(self, default=None) |
| 1308 | if obj and not obj._is_pk_set(): |
| 1309 | raise ValueError( |
| 1310 | f"{operation_name}() prohibited to prevent data loss due to " |
| 1311 | f"unsaved related object '{field.name}'." |
| 1312 | ) |
| 1313 | |
| 1314 | def delete(self, using=None, keep_parents=False): |
| 1315 | if not self._is_pk_set(): |
no test coverage detected