~ubuntu-branches/ubuntu/quantal/python-django/quantal-security

« back to all changes in this revision

Viewing changes to django/db/models/base.py

  • Committer: Bazaar Package Importer
  • Author(s): Chris Lamb
  • Date: 2010-05-21 07:52:55 UTC
  • mfrom: (1.3.6 upstream)
  • mto: This revision was merged to the branch mainline in revision 28.
  • Revision ID: james.westby@ubuntu.com-20100521075255-ii78v1dyfmyu3uzx
Tags: upstream-1.2
ImportĀ upstreamĀ versionĀ 1.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
import copy
2
1
import types
3
2
import sys
4
3
import os
5
4
from itertools import izip
6
 
try:
7
 
    set
8
 
except NameError:
9
 
    from sets import Set as set     # Python 2.3 fallback.
10
 
 
11
5
import django.db.models.manager     # Imported to register signal handler.
12
 
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned, FieldError
 
6
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned, FieldError, ValidationError, NON_FIELD_ERRORS
 
7
from django.core import validators
13
8
from django.db.models.fields import AutoField, FieldDoesNotExist
14
9
from django.db.models.fields.related import OneToOneRel, ManyToOneRel, OneToOneField
15
10
from django.db.models.query import delete_objects, Q
16
11
from django.db.models.query_utils import CollectedObjects, DeferredAttribute
17
12
from django.db.models.options import Options
18
 
from django.db import connection, transaction, DatabaseError
 
13
from django.db import connections, router, transaction, DatabaseError, DEFAULT_DB_ALIAS
19
14
from django.db.models import signals
20
15
from django.db.models.loading import register_models, get_model
21
 
from django.utils.functional import curry
 
16
from django.utils.translation import ugettext_lazy as _
 
17
import django.utils.copycompat as copy
 
18
from django.utils.functional import curry, update_wrapper
22
19
from django.utils.encoding import smart_str, force_unicode, smart_unicode
 
20
from django.utils.text import get_text_list, capfirst
23
21
from django.conf import settings
24
22
 
25
 
 
26
23
class ModelBase(type):
27
24
    """
28
25
    Metaclass for all models.
55
52
 
56
53
        new_class.add_to_class('_meta', Options(meta, **kwargs))
57
54
        if not abstract:
58
 
            new_class.add_to_class('DoesNotExist',
59
 
                    subclass_exception('DoesNotExist', ObjectDoesNotExist, module))
60
 
            new_class.add_to_class('MultipleObjectsReturned',
61
 
                    subclass_exception('MultipleObjectsReturned', MultipleObjectsReturned, module))
 
55
            new_class.add_to_class('DoesNotExist', subclass_exception('DoesNotExist',
 
56
                    tuple(x.DoesNotExist
 
57
                            for x in parents if hasattr(x, '_meta') and not x._meta.abstract)
 
58
                                    or (ObjectDoesNotExist,), module))
 
59
            new_class.add_to_class('MultipleObjectsReturned', subclass_exception('MultipleObjectsReturned',
 
60
                    tuple(x.MultipleObjectsReturned
 
61
                            for x in parents if hasattr(x, '_meta') and not x._meta.abstract)
 
62
                                    or (MultipleObjectsReturned,), module))
62
63
            if base_meta and not base_meta.abstract:
63
64
                # Non-abstract child classes inherit some attributes from their
64
65
                # non-abstract parent (unless an ABC comes before it in the
114
115
                    raise TypeError("Proxy model '%s' has no non-abstract model base class." % name)
115
116
            if (new_class._meta.local_fields or
116
117
                    new_class._meta.local_many_to_many):
117
 
                raise FieldError("Proxy model '%s' contains model fields."
118
 
                        % name)
 
118
                raise FieldError("Proxy model '%s' contains model fields." % name)
119
119
            while base._meta.proxy:
120
120
                base = base._meta.proxy_for_model
121
121
            new_class._meta.setup_proxy(base)
232
232
            cls.__doc__ = "%s(%s)" % (cls.__name__, ", ".join([f.attname for f in opts.fields]))
233
233
 
234
234
        if hasattr(cls, 'get_absolute_url'):
235
 
            cls.get_absolute_url = curry(get_absolute_url, opts, cls.get_absolute_url)
 
235
            cls.get_absolute_url = update_wrapper(curry(get_absolute_url, opts, cls.get_absolute_url),
 
236
                                                  cls.get_absolute_url)
236
237
 
237
238
        signals.class_prepared.send(sender=cls)
238
239
 
 
240
class ModelState(object):
 
241
    """
 
242
    A class for storing instance state
 
243
    """
 
244
    def __init__(self, db=None):
 
245
        self.db = db
239
246
 
240
247
class Model(object):
241
248
    __metaclass__ = ModelBase
244
251
    def __init__(self, *args, **kwargs):
245
252
        signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
246
253
 
 
254
        # Set up the storage for instance state
 
255
        self._state = ModelState()
 
256
 
247
257
        # There is a rather weird disparity here; if kwargs, it's set, then args
248
258
        # overrides it. It should be one or the other; don't duplicate the work
249
259
        # The reason for the kwargs check is that standard iterator passes in by
300
310
                        if rel_obj is None and field.null:
301
311
                            val = None
302
312
                else:
303
 
                    val = kwargs.pop(field.attname, field.get_default())
 
313
                    try:
 
314
                        val = kwargs.pop(field.attname)
 
315
                    except KeyError:
 
316
                        # This is done with an exception rather than the
 
317
                        # default argument on pop because we don't want
 
318
                        # get_default() to be evaluated, and then not used.
 
319
                        # Refs #12057.
 
320
                        val = field.get_default()
304
321
            else:
305
322
                val = field.get_default()
306
323
            if is_related_object:
320
337
                except AttributeError:
321
338
                    pass
322
339
            if kwargs:
323
 
                raise TypeError, "'%s' is an invalid keyword argument for this function" % kwargs.keys()[0]
 
340
                raise TypeError("'%s' is an invalid keyword argument for this function" % kwargs.keys()[0])
324
341
        signals.post_init.send(sender=self.__class__, instance=self)
325
342
 
326
343
    def __repr__(self):
352
369
        only module-level classes can be pickled by the default path.
353
370
        """
354
371
        data = self.__dict__
355
 
        if not self._deferred:
356
 
            return (self.__class__, (), data)
 
372
        model = self.__class__
 
373
        # The obvious thing to do here is to invoke super().__reduce__()
 
374
        # for the non-deferred case. Don't do that.
 
375
        # On Python 2.4, there is something wierd with __reduce__,
 
376
        # and as a result, the super call will cause an infinite recursion.
 
377
        # See #10547 and #12121.
357
378
        defers = []
358
379
        pk_val = None
359
 
        for field in self._meta.fields:
360
 
            if isinstance(self.__class__.__dict__.get(field.attname),
361
 
                    DeferredAttribute):
362
 
                defers.append(field.attname)
363
 
                if pk_val is None:
364
 
                    # The pk_val and model values are the same for all
365
 
                    # DeferredAttribute classes, so we only need to do this
366
 
                    # once.
367
 
                    obj = self.__class__.__dict__[field.attname]
368
 
                    model = obj.model_ref()
369
 
        return (model_unpickle, (model, defers), data)
 
380
        if self._deferred:
 
381
            from django.db.models.query_utils import deferred_class_factory
 
382
            factory = deferred_class_factory
 
383
            for field in self._meta.fields:
 
384
                if isinstance(self.__class__.__dict__.get(field.attname),
 
385
                        DeferredAttribute):
 
386
                    defers.append(field.attname)
 
387
                    if pk_val is None:
 
388
                        # The pk_val and model values are the same for all
 
389
                        # DeferredAttribute classes, so we only need to do this
 
390
                        # once.
 
391
                        obj = self.__class__.__dict__[field.attname]
 
392
                        model = obj.model_ref()
 
393
        else:
 
394
            factory = simple_class_factory
 
395
        return (model_unpickle, (model, defers, factory), data)
370
396
 
371
397
    def _get_pk_val(self, meta=None):
372
398
        if not meta:
395
421
            return getattr(self, field_name)
396
422
        return getattr(self, field.attname)
397
423
 
398
 
    def save(self, force_insert=False, force_update=False):
 
424
    def save(self, force_insert=False, force_update=False, using=None):
399
425
        """
400
426
        Saves the current instance. Override this in a subclass if you want to
401
427
        control the saving process.
405
431
        non-SQL backends), respectively. Normally, they should not be set.
406
432
        """
407
433
        if force_insert and force_update:
408
 
            raise ValueError("Cannot force both insert and updating in "
409
 
                    "model saving.")
410
 
        self.save_base(force_insert=force_insert, force_update=force_update)
 
434
            raise ValueError("Cannot force both insert and updating in model saving.")
 
435
        self.save_base(using=using, force_insert=force_insert, force_update=force_update)
411
436
 
412
437
    save.alters_data = True
413
438
 
414
 
    def save_base(self, raw=False, cls=None, origin=None,
415
 
            force_insert=False, force_update=False):
 
439
    def save_base(self, raw=False, cls=None, origin=None, force_insert=False,
 
440
            force_update=False, using=None):
416
441
        """
417
442
        Does the heavy-lifting involved in saving. Subclasses shouldn't need to
418
443
        override this method. It's separate from save() in order to hide the
419
444
        need for overrides of save() to pass around internal-only parameters
420
445
        ('raw', 'cls', and 'origin').
421
446
        """
 
447
        using = using or router.db_for_write(self.__class__, instance=self)
 
448
        connection = connections[using]
422
449
        assert not (force_insert and force_update)
423
450
        if cls is None:
424
451
            cls = self.__class__
428
455
        else:
429
456
            meta = cls._meta
430
457
 
431
 
        if origin:
 
458
        if origin and not meta.auto_created:
432
459
            signals.pre_save.send(sender=origin, instance=self, raw=raw)
433
460
 
434
461
        # If we are in a raw save, save the object exactly as presented.
449
476
                if field and getattr(self, parent._meta.pk.attname) is None and getattr(self, field.attname) is not None:
450
477
                    setattr(self, parent._meta.pk.attname, getattr(self, field.attname))
451
478
 
452
 
                self.save_base(cls=parent, origin=org)
 
479
                self.save_base(cls=parent, origin=org, using=using)
453
480
 
454
481
                if field:
455
482
                    setattr(self, field.attname, self._get_pk_val(parent._meta))
467
494
            if pk_set:
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.")
477
504
                else:
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)
 
513
 
480
514
                if not pk_set:
481
515
                    if force_update:
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)]
484
519
                else:
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]
486
522
 
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
491
524
 
492
525
                update_pk = bool(meta.has_auto_field and not pk_set)
493
526
                if values:
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)
496
529
                else:
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)
499
532
 
500
533
                if update_pk:
501
534
                    setattr(self, meta.pk.attname, result)
502
 
            transaction.commit_unless_managed()
503
 
 
504
 
        if origin:
 
535
            transaction.commit_unless_managed(using=using)
 
536
 
 
537
        # Store the database on which the object was saved
 
538
        self._state.db = using
 
539
 
 
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)
507
544
 
517
554
             (model_class, {pk_val: obj, pk_val: obj, ...}), ...]
518
555
        """
519
556
        pk_val = self._get_pk_val()
520
 
        if seen_objs.add(self.__class__, pk_val, self, parent, nullable):
 
557
        if seen_objs.add(self.__class__, pk_val, self,
 
558
                         type(parent), parent, nullable):
521
559
            return
522
560
 
523
561
        for related in self._meta.get_all_related_objects():
524
562
            rel_opts_name = related.get_accessor_name()
525
 
            if isinstance(related.field.rel, OneToOneRel):
 
563
            if not related.field.rel.multiple:
526
564
                try:
527
565
                    sub_obj = getattr(self, rel_opts_name)
528
566
                except ObjectDoesNotExist:
529
567
                    pass
530
568
                else:
531
 
                    sub_obj._collect_sub_objects(seen_objs, self.__class__, related.field.null)
 
569
                    sub_obj._collect_sub_objects(seen_objs, self, related.field.null)
532
570
            else:
533
571
                # To make sure we can access all elements, we can't use the
534
572
                # normal manager on the related object. So we work directly
538
576
                        rel_descriptor = cls.__dict__[rel_opts_name]
539
577
                        break
540
578
                else:
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.")
 
583
                    else:
 
584
                        continue
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)
 
588
 
 
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)
 
598
 
 
599
        for f in self._meta.many_to_many:
 
600
            if f.rel.through:
 
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)
 
608
            else:
 
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)
545
614
 
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
558
627
            # delete it and all its descendents.
559
628
            parent_obj._collect_sub_objects(seen_objs)
560
629
 
561
 
    def delete(self):
 
630
    def delete(self, using=None):
 
631
        using = using or router.db_for_write(self.__class__, instance=self)
562
632
        assert self._get_pk_val() is not None, "%s object can't be deleted because its %s attribute is set to None." % (self._meta.object_name, self._meta.pk.attname)
563
633
 
564
634
        # Find all the objects than need to be deleted.
566
636
        self._collect_sub_objects(seen_objs)
567
637
 
568
638
        # Actually delete the objects.
569
 
        delete_objects(seen_objs)
 
639
        delete_objects(seen_objs, using)
570
640
 
571
641
    delete.alters_data = True
572
642
 
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)
584
654
        try:
585
655
            return qs[0]
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)
588
658
 
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))]
601
 
            params = [self.pk]
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)
 
667
            }).filter(**{
 
668
                '_order__%s' % op: self._default_manager.values('_order').filter(**{
 
669
                    self._meta.pk.name: self.pk
 
670
                })
 
671
            }).order_by(order)[:1].get()
603
672
            setattr(self, cachename, obj)
604
673
        return getattr(self, cachename)
605
674
 
606
675
    def prepare_database_save(self, unused):
607
676
        return self.pk
608
677
 
 
678
    def clean(self):
 
679
        """
 
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.
 
684
        """
 
685
        pass
 
686
 
 
687
    def validate_unique(self, exclude=None):
 
688
        """
 
689
        Checks unique constraints on the model and raises ``ValidationError``
 
690
        if any failed.
 
691
        """
 
692
        unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
 
693
 
 
694
        errors = self._perform_unique_checks(unique_checks)
 
695
        date_errors = self._perform_date_checks(date_checks)
 
696
 
 
697
        for k, v in date_errors.items():
 
698
            errors.setdefault(k, []).extend(v)
 
699
 
 
700
        if errors:
 
701
            raise ValidationError(errors)
 
702
 
 
703
    def _get_unique_checks(self, exclude=None):
 
704
        """
 
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
 
708
        in that check.
 
709
        Fields that did not validate should also be exluded, but they need
 
710
        to be passed in via the exclude argument.
 
711
        """
 
712
        if exclude is None:
 
713
            exclude = []
 
714
        unique_checks = []
 
715
 
 
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))
 
720
 
 
721
        for model_class, unique_together in unique_togethers:
 
722
            for check in unique_together:
 
723
                for name in check:
 
724
                    # If this is an excluded field, don't add this check.
 
725
                    if name in exclude:
 
726
                        break
 
727
                else:
 
728
                    unique_checks.append((model_class, tuple(check)))
 
729
 
 
730
        # These are checks for the unique_for_<date/year/month>.
 
731
        date_checks = []
 
732
 
 
733
        # Gather a list of checks for fields declared as unique and add them to
 
734
        # the list of checks.
 
735
 
 
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))
 
739
 
 
740
        for model_class, fields in fields_with_class:
 
741
            for f in fields:
 
742
                name = f.name
 
743
                if name in exclude:
 
744
                    continue
 
745
                if f.unique:
 
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
 
754
 
 
755
    def _perform_unique_checks(self, unique_checks):
 
756
        errors = {}
 
757
 
 
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.
 
761
 
 
762
            lookup_kwargs = {}
 
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
 
768
                    continue
 
769
                if f.primary_key and not getattr(self, '_adding', False):
 
770
                    # no need to check for unique primary key when editing
 
771
                    continue
 
772
                lookup_kwargs[str(field_name)] = lookup_value
 
773
 
 
774
            # some fields were skipped, no reason to do the check
 
775
            if len(unique_check) != len(lookup_kwargs.keys()):
 
776
                continue
 
777
 
 
778
            qs = model_class._default_manager.filter(**lookup_kwargs)
 
779
 
 
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)
 
784
 
 
785
            if qs.exists():
 
786
                if len(unique_check) == 1:
 
787
                    key = unique_check[0]
 
788
                else:
 
789
                    key = NON_FIELD_ERRORS
 
790
                errors.setdefault(key, []).append(self.unique_error_message(model_class, unique_check))
 
791
 
 
792
        return errors
 
793
 
 
794
    def _perform_date_checks(self, date_checks):
 
795
        errors = {}
 
796
        for model_class, lookup_type, field, unique_for in date_checks:
 
797
            lookup_kwargs = {}
 
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
 
805
            else:
 
806
                lookup_kwargs['%s__%s' % (unique_for, lookup_type)] = getattr(date, lookup_type)
 
807
            lookup_kwargs[field] = getattr(self, field)
 
808
 
 
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)
 
814
 
 
815
            if qs.exists():
 
816
                errors.setdefault(field, []).append(
 
817
                    self.date_error_message(lookup_type, field, unique_for)
 
818
                )
 
819
        return errors
 
820
 
 
821
    def date_error_message(self, lookup_type, field, unique_for):
 
822
        opts = self._meta
 
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,
 
827
        }
 
828
 
 
829
    def unique_error_message(self, model_class, unique_check):
 
830
        opts = model_class._meta
 
831
        model_name = capfirst(opts.verbose_name)
 
832
 
 
833
        # A unique field
 
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)
 
841
            }
 
842
        # unique_together
 
843
        else:
 
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)
 
849
            }
 
850
 
 
851
    def full_clean(self, exclude=None):
 
852
        """
 
853
        Calls clean_fields, clean, and validate_unique, on the model,
 
854
        and raises a ``ValidationError`` for any errors that occured.
 
855
        """
 
856
        errors = {}
 
857
        if exclude is None:
 
858
            exclude = []
 
859
 
 
860
        try:
 
861
            self.clean_fields(exclude=exclude)
 
862
        except ValidationError, e:
 
863
            errors = e.update_error_dict(errors)
 
864
 
 
865
        # Form.clean() is run even if other validation fails, so do the
 
866
        # same with Model.clean() for consistency.
 
867
        try:
 
868
            self.clean()
 
869
        except ValidationError, e:
 
870
            errors = e.update_error_dict(errors)
 
871
 
 
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:
 
875
                exclude.append(name)
 
876
        try:
 
877
            self.validate_unique(exclude=exclude)
 
878
        except ValidationError, e:
 
879
            errors = e.update_error_dict(errors)
 
880
 
 
881
        if errors:
 
882
            raise ValidationError(errors)
 
883
 
 
884
    def clean_fields(self, exclude=None):
 
885
        """
 
886
        Cleans all fields and raises a ValidationError containing message_dict
 
887
        of all validation errors if any occur.
 
888
        """
 
889
        if exclude is None:
 
890
            exclude = []
 
891
 
 
892
        errors = {}
 
893
        for f in self._meta.fields:
 
894
            if f.name in exclude:
 
895
                continue
 
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:
 
900
                continue
 
901
            try:
 
902
                setattr(self, f.attname, f.clean(raw_value, self))
 
903
            except ValidationError, e:
 
904
                errors[f.name] = e.messages
 
905
 
 
906
        if errors:
 
907
            raise ValidationError(errors)
 
908
 
609
909
 
610
910
############################################
611
911
# HELPER FUNCTIONS (CURRIED MODEL METHODS) #
613
913
 
614
914
# ORDERING METHODS #########################
615
915
 
616
 
def method_set_order(ordered_obj, self, id_list):
 
916
def method_set_order(ordered_obj, self, id_list, using=None):
 
917
    if using is None:
 
918
        using = DEFAULT_DB_ALIAS
617
919
    rel_val = getattr(self, ordered_obj._meta.order_with_respect_to.rel.field_name)
618
920
    order_name = ordered_obj._meta.order_with_respect_to.name
619
921
    # FIXME: It would be nice if there was an "update many" version of update
620
922
    # for situations like this.
621
923
    for i, j in enumerate(id_list):
622
924
        ordered_obj.objects.filter(**{'pk': j, order_name: rel_val}).update(_order=i)
623
 
    transaction.commit_unless_managed()
 
925
    transaction.commit_unless_managed(using=using)
624
926
 
625
927
 
626
928
def method_get_order(ordered_obj, self):
646
948
class Empty(object):
647
949
    pass
648
950
 
649
 
def model_unpickle(model, attrs):
 
951
def simple_class_factory(model, attrs):
 
952
    """Used to unpickle Models without deferred fields.
 
953
 
 
954
    We need to do this the hard way, rather than just using
 
955
    the default __reduce__ implementation, because of a
 
956
    __deepcopy__ problem in Python 2.4
 
957
    """
 
958
    return model
 
959
 
 
960
def model_unpickle(model, attrs, factory):
650
961
    """
651
962
    Used to unpickle Model subclasses with deferred fields.
652
963
    """
653
 
    from django.db.models.query_utils import deferred_class_factory
654
 
    cls = deferred_class_factory(model, attrs)
 
964
    cls = factory(model, attrs)
655
965
    return cls.__new__(cls)
656
966
model_unpickle.__safe_for_unpickle__ = True
657
967
 
658
968
if sys.version_info < (2, 5):
659
969
    # Prior to Python 2.5, Exception was an old-style class
660
 
    def subclass_exception(name, parent, unused):
661
 
        return types.ClassType(name, (parent,), {})
 
970
    def subclass_exception(name, parents, unused):
 
971
        return types.ClassType(name, parents, {})
662
972
else:
663
 
    def subclass_exception(name, parent, module):
664
 
        return type(name, (parent,), {'__module__': module})
 
973
    def subclass_exception(name, parents, module):
 
974
        return type(name, parents, {'__module__': module})