468
495
# Determine whether a record with the primary key already exists.
469
496
if (force_update or (not force_insert and
470
manager.filter(pk=pk_val).extra(select={'a': 1}).values('a').order_by())):
497
manager.using(using).filter(pk=pk_val).exists())):
471
498
# It does already exist, so do an UPDATE.
472
499
if force_update or non_pks:
473
500
values = [(f, None, (raw and getattr(self, f.attname) or f.pre_save(self, False))) for f in non_pks]
474
rows = manager.filter(pk=pk_val)._update(values)
501
rows = manager.using(using).filter(pk=pk_val)._update(values)
475
502
if force_update and not rows:
476
503
raise DatabaseError("Forced update did not affect any rows.")
478
505
record_exists = False
479
506
if not pk_set or not record_exists:
507
if meta.order_with_respect_to:
508
# If this is a model with an order_with_respect_to
509
# autopopulate the _order field
510
field = meta.order_with_respect_to
511
order_value = manager.using(using).filter(**{field.name: getattr(self, field.attname)}).count()
512
setattr(self, '_order', order_value)
482
516
raise ValueError("Cannot force an update in save() with no primary key.")
483
values = [(f, f.get_db_prep_save(raw and getattr(self, f.attname) or f.pre_save(self, True))) for f in meta.local_fields if not isinstance(f, AutoField)]
517
values = [(f, f.get_db_prep_save(raw and getattr(self, f.attname) or f.pre_save(self, True), connection=connection))
518
for f in meta.local_fields if not isinstance(f, AutoField)]
485
values = [(f, f.get_db_prep_save(raw and getattr(self, f.attname) or f.pre_save(self, True))) for f in meta.local_fields]
520
values = [(f, f.get_db_prep_save(raw and getattr(self, f.attname) or f.pre_save(self, True), connection=connection))
521
for f in meta.local_fields]
487
if meta.order_with_respect_to:
488
field = meta.order_with_respect_to
489
values.append((meta.get_field_by_name('_order')[0], manager.filter(**{field.name: getattr(self, field.attname)}).count()))
490
523
record_exists = False
492
525
update_pk = bool(meta.has_auto_field and not pk_set)
494
527
# Create a new record.
495
result = manager._insert(values, return_id=update_pk)
528
result = manager._insert(values, return_id=update_pk, using=using)
497
530
# Create a new record with defaults for everything.
498
result = manager._insert([(meta.pk, connection.ops.pk_default_value())], return_id=update_pk, raw_values=True)
531
result = manager._insert([(meta.pk, connection.ops.pk_default_value())], return_id=update_pk, raw_values=True, using=using)
501
534
setattr(self, meta.pk.attname, result)
502
transaction.commit_unless_managed()
535
transaction.commit_unless_managed(using=using)
537
# Store the database on which the object was saved
538
self._state.db = using
540
# Signal that the save is complete
541
if origin and not meta.auto_created:
505
542
signals.post_save.send(sender=origin, instance=self,
506
543
created=(not record_exists), raw=raw)
538
576
rel_descriptor = cls.__dict__[rel_opts_name]
541
raise AssertionError("Should never get here.")
579
# in the case of a hidden fkey just skip it, it'll get
580
# processed as an m2m
581
if not related.field.rel.is_hidden():
582
raise AssertionError("Should never get here.")
542
585
delete_qs = rel_descriptor.delete_manager(self).all()
543
586
for sub_obj in delete_qs:
544
sub_obj._collect_sub_objects(seen_objs, self.__class__, related.field.null)
587
sub_obj._collect_sub_objects(seen_objs, self, related.field.null)
589
for related in self._meta.get_all_related_many_to_many_objects():
590
if related.field.rel.through:
591
db = router.db_for_write(related.field.rel.through.__class__, instance=self)
592
opts = related.field.rel.through._meta
593
reverse_field_name = related.field.m2m_reverse_field_name()
594
nullable = opts.get_field(reverse_field_name).null
595
filters = {reverse_field_name: self}
596
for sub_obj in related.field.rel.through._base_manager.using(db).filter(**filters):
597
sub_obj._collect_sub_objects(seen_objs, self, nullable)
599
for f in self._meta.many_to_many:
601
db = router.db_for_write(f.rel.through.__class__, instance=self)
602
opts = f.rel.through._meta
603
field_name = f.m2m_field_name()
604
nullable = opts.get_field(field_name).null
605
filters = {field_name: self}
606
for sub_obj in f.rel.through._base_manager.using(db).filter(**filters):
607
sub_obj._collect_sub_objects(seen_objs, self, nullable)
609
# m2m-ish but with no through table? GenericRelation: cascade delete
610
for sub_obj in f.value_from_object(self).all():
611
# Generic relations not enforced by db constraints, thus we can set
612
# nullable=True, order does not matter
613
sub_obj._collect_sub_objects(seen_objs, self, True)
546
615
# Handle any ancestors (for the model-inheritance case). We do this by
547
616
# traversing to the most remote parent classes -- those with no parents
580
650
param = smart_str(getattr(self, field.attname))
581
651
q = Q(**{'%s__%s' % (field.name, op): param})
582
652
q = q|Q(**{field.name: param, 'pk__%s' % op: self.pk})
583
qs = self.__class__._default_manager.filter(**kwargs).filter(q).order_by('%s%s' % (order, field.name), '%spk' % order)
653
qs = self.__class__._default_manager.using(self._state.db).filter(**kwargs).filter(q).order_by('%s%s' % (order, field.name), '%spk' % order)
586
656
except IndexError:
587
raise self.DoesNotExist, "%s matching query does not exist." % self.__class__._meta.object_name
657
raise self.DoesNotExist("%s matching query does not exist." % self.__class__._meta.object_name)
589
659
def _get_next_or_previous_in_order(self, is_next):
590
660
cachename = "__%s_order_cache" % is_next
591
661
if not hasattr(self, cachename):
592
qn = connection.ops.quote_name
593
op = is_next and '>' or '<'
662
op = is_next and 'gt' or 'lt'
594
663
order = not is_next and '-_order' or '_order'
595
664
order_field = self._meta.order_with_respect_to
596
# FIXME: When querysets support nested queries, this can be turned
597
# into a pure queryset operation.
598
where = ['%s %s (SELECT %s FROM %s WHERE %s=%%s)' % \
599
(qn('_order'), op, qn('_order'),
600
qn(self._meta.db_table), qn(self._meta.pk.column))]
602
obj = self._default_manager.filter(**{order_field.name: getattr(self, order_field.attname)}).extra(where=where, params=params).order_by(order)[:1].get()
665
obj = self._default_manager.filter(**{
666
order_field.name: getattr(self, order_field.attname)
668
'_order__%s' % op: self._default_manager.values('_order').filter(**{
669
self._meta.pk.name: self.pk
671
}).order_by(order)[:1].get()
603
672
setattr(self, cachename, obj)
604
673
return getattr(self, cachename)
606
675
def prepare_database_save(self, unused):
680
Hook for doing any extra model-wide validation after clean() has been
681
called on every field by self.clean_fields. Any ValidationError raised
682
by this method will not be associated with a particular field; it will
683
have a special-case association with the field defined by NON_FIELD_ERRORS.
687
def validate_unique(self, exclude=None):
689
Checks unique constraints on the model and raises ``ValidationError``
692
unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
694
errors = self._perform_unique_checks(unique_checks)
695
date_errors = self._perform_date_checks(date_checks)
697
for k, v in date_errors.items():
698
errors.setdefault(k, []).extend(v)
701
raise ValidationError(errors)
703
def _get_unique_checks(self, exclude=None):
705
Gather a list of checks to perform. Since validate_unique could be
706
called from a ModelForm, some fields may have been excluded; we can't
707
perform a unique check on a model that is missing fields involved
709
Fields that did not validate should also be exluded, but they need
710
to be passed in via the exclude argument.
716
unique_togethers = [(self.__class__, self._meta.unique_together)]
717
for parent_class in self._meta.parents.keys():
718
if parent_class._meta.unique_together:
719
unique_togethers.append((parent_class, parent_class._meta.unique_together))
721
for model_class, unique_together in unique_togethers:
722
for check in unique_together:
724
# If this is an excluded field, don't add this check.
728
unique_checks.append((model_class, tuple(check)))
730
# These are checks for the unique_for_<date/year/month>.
733
# Gather a list of checks for fields declared as unique and add them to
734
# the list of checks.
736
fields_with_class = [(self.__class__, self._meta.local_fields)]
737
for parent_class in self._meta.parents.keys():
738
fields_with_class.append((parent_class, parent_class._meta.local_fields))
740
for model_class, fields in fields_with_class:
746
unique_checks.append((model_class, (name,)))
747
if f.unique_for_date:
748
date_checks.append((model_class, 'date', name, f.unique_for_date))
749
if f.unique_for_year:
750
date_checks.append((model_class, 'year', name, f.unique_for_year))
751
if f.unique_for_month:
752
date_checks.append((model_class, 'month', name, f.unique_for_month))
753
return unique_checks, date_checks
755
def _perform_unique_checks(self, unique_checks):
758
for model_class, unique_check in unique_checks:
759
# Try to look up an existing object with the same values as this
760
# object's values for all the unique field.
763
for field_name in unique_check:
764
f = self._meta.get_field(field_name)
765
lookup_value = getattr(self, f.attname)
766
if lookup_value is None:
767
# no value, skip the lookup
769
if f.primary_key and not getattr(self, '_adding', False):
770
# no need to check for unique primary key when editing
772
lookup_kwargs[str(field_name)] = lookup_value
774
# some fields were skipped, no reason to do the check
775
if len(unique_check) != len(lookup_kwargs.keys()):
778
qs = model_class._default_manager.filter(**lookup_kwargs)
780
# Exclude the current object from the query if we are editing an
781
# instance (as opposed to creating a new one)
782
if not getattr(self, '_adding', False) and self.pk is not None:
783
qs = qs.exclude(pk=self.pk)
786
if len(unique_check) == 1:
787
key = unique_check[0]
789
key = NON_FIELD_ERRORS
790
errors.setdefault(key, []).append(self.unique_error_message(model_class, unique_check))
794
def _perform_date_checks(self, date_checks):
796
for model_class, lookup_type, field, unique_for in date_checks:
798
# there's a ticket to add a date lookup, we can remove this special
799
# case if that makes it's way in
800
date = getattr(self, unique_for)
801
if lookup_type == 'date':
802
lookup_kwargs['%s__day' % unique_for] = date.day
803
lookup_kwargs['%s__month' % unique_for] = date.month
804
lookup_kwargs['%s__year' % unique_for] = date.year
806
lookup_kwargs['%s__%s' % (unique_for, lookup_type)] = getattr(date, lookup_type)
807
lookup_kwargs[field] = getattr(self, field)
809
qs = model_class._default_manager.filter(**lookup_kwargs)
810
# Exclude the current object from the query if we are editing an
811
# instance (as opposed to creating a new one)
812
if not getattr(self, '_adding', False) and self.pk is not None:
813
qs = qs.exclude(pk=self.pk)
816
errors.setdefault(field, []).append(
817
self.date_error_message(lookup_type, field, unique_for)
821
def date_error_message(self, lookup_type, field, unique_for):
823
return _(u"%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
824
'field_name': unicode(capfirst(opts.get_field(field).verbose_name)),
825
'date_field': unicode(capfirst(opts.get_field(unique_for).verbose_name)),
826
'lookup': lookup_type,
829
def unique_error_message(self, model_class, unique_check):
830
opts = model_class._meta
831
model_name = capfirst(opts.verbose_name)
834
if len(unique_check) == 1:
835
field_name = unique_check[0]
836
field_label = capfirst(opts.get_field(field_name).verbose_name)
837
# Insert the error into the error dict, very sneaky
838
return _(u"%(model_name)s with this %(field_label)s already exists.") % {
839
'model_name': unicode(model_name),
840
'field_label': unicode(field_label)
844
field_labels = map(lambda f: capfirst(opts.get_field(f).verbose_name), unique_check)
845
field_labels = get_text_list(field_labels, _('and'))
846
return _(u"%(model_name)s with this %(field_label)s already exists.") % {
847
'model_name': unicode(model_name),
848
'field_label': unicode(field_labels)
851
def full_clean(self, exclude=None):
853
Calls clean_fields, clean, and validate_unique, on the model,
854
and raises a ``ValidationError`` for any errors that occured.
861
self.clean_fields(exclude=exclude)
862
except ValidationError, e:
863
errors = e.update_error_dict(errors)
865
# Form.clean() is run even if other validation fails, so do the
866
# same with Model.clean() for consistency.
869
except ValidationError, e:
870
errors = e.update_error_dict(errors)
872
# Run unique checks, but only for fields that passed validation.
873
for name in errors.keys():
874
if name != NON_FIELD_ERRORS and name not in exclude:
877
self.validate_unique(exclude=exclude)
878
except ValidationError, e:
879
errors = e.update_error_dict(errors)
882
raise ValidationError(errors)
884
def clean_fields(self, exclude=None):
886
Cleans all fields and raises a ValidationError containing message_dict
887
of all validation errors if any occur.
893
for f in self._meta.fields:
894
if f.name in exclude:
896
# Skip validation for empty fields with blank=True. The developer
897
# is responsible for making sure they have a valid value.
898
raw_value = getattr(self, f.attname)
899
if f.blank and raw_value in validators.EMPTY_VALUES:
902
setattr(self, f.attname, f.clean(raw_value, self))
903
except ValidationError, e:
904
errors[f.name] = e.messages
907
raise ValidationError(errors)
610
910
############################################
611
911
# HELPER FUNCTIONS (CURRIED MODEL METHODS) #