diff options
Diffstat (limited to 'django')
| -rw-r--r-- | django/db/models/base.py | 13 | ||||
| -rw-r--r-- | django/forms/models.py | 4 |
2 files changed, 12 insertions, 5 deletions
diff --git a/django/db/models/base.py b/django/db/models/base.py index 05a6c1aa93..f29d7db629 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -260,6 +260,10 @@ class ModelState(object): """ def __init__(self, db=None): self.db = db + # If true, uniqueness validation checks will consider this a new, as-yet-unsaved object. + # Necessary for correct validation of new instances of objects with explicit (non-auto) PKs. + # This impacts validation only; it has no effect on the actual save. + self.adding = False class Model(object): __metaclass__ = ModelBase @@ -553,12 +557,15 @@ class Model(object): # Store the database on which the object was saved self._state.db = using + # Once saved, this is no longer a to-be-added instance. + self._state.adding = False # Signal that the save is complete if origin and not meta.auto_created: signals.post_save.send(sender=origin, instance=self, created=(not record_exists), raw=raw) + save_base.alters_data = True def _collect_sub_objects(self, seen_objs, parent=None, nullable=False): @@ -783,7 +790,7 @@ class Model(object): if lookup_value is None: # no value, skip the lookup continue - if f.primary_key and not getattr(self, '_adding', False): + if f.primary_key and not self._state.adding: # no need to check for unique primary key when editing continue lookup_kwargs[str(field_name)] = lookup_value @@ -796,7 +803,7 @@ class Model(object): # Exclude the current object from the query if we are editing an # instance (as opposed to creating a new one) - if not getattr(self, '_adding', False) and self.pk is not None: + if not self._state.adding and self.pk is not None: qs = qs.exclude(pk=self.pk) if qs.exists(): @@ -826,7 +833,7 @@ class Model(object): qs = model_class._default_manager.filter(**lookup_kwargs) # Exclude the current object from the query if we are editing an # instance (as opposed to creating a new one) - if not getattr(self, '_adding', False) and self.pk is not None: + if not self._state.adding and self.pk is not None: qs = qs.exclude(pk=self.pk) if qs.exists(): diff --git a/django/forms/models.py b/django/forms/models.py index d4046a7f70..c5be8aa1e3 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -244,10 +244,10 @@ class BaseModelForm(BaseForm): # if we didn't get an instance, instantiate a new one self.instance = opts.model() object_data = {} - self.instance._adding = True + self.instance._state.adding = True else: self.instance = instance - self.instance._adding = False + self.instance._state.adding = False object_data = model_to_dict(instance, opts.fields, opts.exclude) # if initial was provided, it should override the values from instance if initial is not None: |
