Save the current instance. Override this in a subclass if you want to control the saving process. The 'force_insert' and 'force_update' parameters can be used to insist that the "save" must be an SQL insert or update (or equivalent for non-SQL backends), res
(
self,
*,
force_insert=False,
force_update=False,
using=None,
update_fields=None,
)
| 831 | return getattr(self, field.attname) |
| 832 | |
| 833 | def save( |
| 834 | self, |
| 835 | *, |
| 836 | force_insert=False, |
| 837 | force_update=False, |
| 838 | using=None, |
| 839 | update_fields=None, |
| 840 | ): |
| 841 | """ |
| 842 | Save the current instance. Override this in a subclass if you want to |
| 843 | control the saving process. |
| 844 | |
| 845 | The 'force_insert' and 'force_update' parameters can be used to insist |
| 846 | that the "save" must be an SQL insert or update (or equivalent for |
| 847 | non-SQL backends), respectively. Normally, they should not be set. |
| 848 | """ |
| 849 | |
| 850 | self._prepare_related_fields_for_save(operation_name="save") |
| 851 | |
| 852 | using = using or router.db_for_write(self.__class__, instance=self) |
| 853 | if force_insert and (force_update or update_fields): |
| 854 | raise ValueError("Cannot force both insert and updating in model saving.") |
| 855 | |
| 856 | deferred_non_generated_fields = { |
| 857 | f.attname |
| 858 | for f in self._meta.concrete_fields |
| 859 | if f.attname not in self.__dict__ and f.generated is False |
| 860 | } |
| 861 | if update_fields is not None: |
| 862 | # If update_fields is empty, skip the save. We do also check for |
| 863 | # no-op saves later on for inheritance cases. This bailout is |
| 864 | # still needed for skipping signal sending. |
| 865 | if not update_fields: |
| 866 | return |
| 867 | |
| 868 | update_fields = frozenset(update_fields) |
| 869 | field_names = self._meta._non_pk_concrete_field_names |
| 870 | not_updatable_fields = update_fields.difference(field_names) |
| 871 | |
| 872 | if not_updatable_fields: |
| 873 | raise ValueError( |
| 874 | "The following fields do not exist in this model, are m2m " |
| 875 | "fields, primary keys, or are non-concrete fields: %s" |
| 876 | % ", ".join(not_updatable_fields) |
| 877 | ) |
| 878 | |
| 879 | # If saving to the same database, and this model is deferred, then |
| 880 | # automatically do an "update_fields" save on the loaded fields. |
| 881 | elif ( |
| 882 | not force_insert |
| 883 | and deferred_non_generated_fields |
| 884 | and using == self._state.db |
| 885 | and self._is_pk_set() |
| 886 | ): |
| 887 | field_names = set() |
| 888 | pk_fields = self._meta.pk_fields |
| 889 | for field in self._meta.concrete_fields: |
| 890 | if field not in pk_fields and not hasattr(field, "through"): |
no test coverage detected