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

« back to all changes in this revision

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

  • Committer: Bazaar Package Importer
  • Author(s): Chris Lamb
  • Date: 2009-07-29 11:26:28 UTC
  • mfrom: (1.1.8 upstream) (4.1.5 sid)
  • Revision ID: james.westby@ubuntu.com-20090729112628-pg09ino8sz0sj21t
Tags: 1.1-1
* New upstream release.
* Merge from experimental:
  - Ship FastCGI initscript and /etc/default file in python-django's examples
    directory (Closes: #538863)
  - Drop "05_10539-sphinx06-compatibility.diff"; it has been applied
    upstream.
  - Bump Standards-Version to 3.8.2.

Show diffs side-by-side

added added

removed removed

Lines of Context:
10
10
 
11
11
import django.db.models.manager     # Imported to register signal handler.
12
12
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned, FieldError
13
 
from django.db.models.fields import AutoField
 
13
from django.db.models.fields import AutoField, FieldDoesNotExist
14
14
from django.db.models.fields.related import OneToOneRel, ManyToOneRel, OneToOneField
15
 
from django.db.models.query import delete_objects, Q, CollectedObjects
 
15
from django.db.models.query import delete_objects, Q
 
16
from django.db.models.query_utils import CollectedObjects, DeferredAttribute
16
17
from django.db.models.options import Options
17
18
from django.db import connection, transaction, DatabaseError
18
19
from django.db.models import signals
67
68
                if not hasattr(meta, 'get_latest_by'):
68
69
                    new_class._meta.get_latest_by = base_meta.get_latest_by
69
70
 
 
71
        is_proxy = new_class._meta.proxy
 
72
 
70
73
        if getattr(new_class, '_default_manager', None):
71
 
            new_class._default_manager = None
 
74
            if not is_proxy:
 
75
                # Multi-table inheritance doesn't inherit default manager from
 
76
                # parents.
 
77
                new_class._default_manager = None
 
78
                new_class._base_manager = None
 
79
            else:
 
80
                # Proxy classes do inherit parent's default manager, if none is
 
81
                # set explicitly.
 
82
                new_class._default_manager = new_class._default_manager._copy_to_model(new_class)
 
83
                new_class._base_manager = new_class._base_manager._copy_to_model(new_class)
72
84
 
73
85
        # Bail out early if we have already created this class.
74
86
        m = get_model(new_class._meta.app_label, name, False)
79
91
        for obj_name, obj in attrs.items():
80
92
            new_class.add_to_class(obj_name, obj)
81
93
 
 
94
        # All the fields of any type declared on this model
 
95
        new_fields = new_class._meta.local_fields + \
 
96
                     new_class._meta.local_many_to_many + \
 
97
                     new_class._meta.virtual_fields
 
98
        field_names = set([f.name for f in new_fields])
 
99
 
 
100
        # Basic setup for proxy models.
 
101
        if is_proxy:
 
102
            base = None
 
103
            for parent in [cls for cls in parents if hasattr(cls, '_meta')]:
 
104
                if parent._meta.abstract:
 
105
                    if parent._meta.fields:
 
106
                        raise TypeError("Abstract base class containing model fields not permitted for proxy model '%s'." % name)
 
107
                    else:
 
108
                        continue
 
109
                if base is not None:
 
110
                    raise TypeError("Proxy model '%s' has more than one non-abstract model base class." % name)
 
111
                else:
 
112
                    base = parent
 
113
            if base is None:
 
114
                    raise TypeError("Proxy model '%s' has no non-abstract model base class." % name)
 
115
            if (new_class._meta.local_fields or
 
116
                    new_class._meta.local_many_to_many):
 
117
                raise FieldError("Proxy model '%s' contains model fields."
 
118
                        % name)
 
119
            while base._meta.proxy:
 
120
                base = base._meta.proxy_for_model
 
121
            new_class._meta.setup_proxy(base)
 
122
 
82
123
        # Do the appropriate setup for any model parents.
83
124
        o2o_map = dict([(f.rel.to, f) for f in new_class._meta.local_fields
84
125
                if isinstance(f, OneToOneField)])
 
126
 
85
127
        for base in parents:
 
128
            original_base = base
86
129
            if not hasattr(base, '_meta'):
87
130
                # Things without _meta aren't functional models, so they're
88
131
                # uninteresting parents.
89
132
                continue
90
133
 
91
 
            # All the fields of any type declared on this model
92
 
            new_fields = new_class._meta.local_fields + \
93
 
                         new_class._meta.local_many_to_many + \
94
 
                         new_class._meta.virtual_fields
95
 
            field_names = set([f.name for f in new_fields])
96
 
 
 
134
            parent_fields = base._meta.local_fields + base._meta.local_many_to_many
 
135
            # Check for clashes between locally declared fields and those
 
136
            # on the base classes (we cannot handle shadowed fields at the
 
137
            # moment).
 
138
            for field in parent_fields:
 
139
                if field.name in field_names:
 
140
                    raise FieldError('Local field %r in class %r clashes '
 
141
                                     'with field of similar name from '
 
142
                                     'base class %r' %
 
143
                                        (field.name, name, base.__name__))
97
144
            if not base._meta.abstract:
98
145
                # Concrete classes...
 
146
                while base._meta.proxy:
 
147
                    # Skip over a proxy class to the "real" base it proxies.
 
148
                    base = base._meta.proxy_for_model
99
149
                if base in o2o_map:
100
150
                    field = o2o_map[base]
101
 
                    field.primary_key = True
102
 
                    new_class._meta.setup_pk(field)
103
 
                else:
 
151
                elif not is_proxy:
104
152
                    attr_name = '%s_ptr' % base._meta.module_name
105
153
                    field = OneToOneField(base, name=attr_name,
106
154
                            auto_created=True, parent_link=True)
107
155
                    new_class.add_to_class(attr_name, field)
 
156
                else:
 
157
                    field = None
108
158
                new_class._meta.parents[base] = field
109
 
 
110
159
            else:
111
160
                # .. and abstract ones.
112
 
 
113
 
                # Check for clashes between locally declared fields and those
114
 
                # on the ABC.
115
 
                parent_fields = base._meta.local_fields + base._meta.local_many_to_many
116
161
                for field in parent_fields:
117
 
                    if field.name in field_names:
118
 
                        raise FieldError('Local field %r in class %r clashes '\
119
 
                                         'with field of similar name from '\
120
 
                                         'abstract base class %r' % \
121
 
                                            (field.name, name, base.__name__))
122
162
                    new_class.add_to_class(field.name, copy.deepcopy(field))
123
163
 
124
164
                # Pass any non-abstract parent classes onto child.
125
165
                new_class._meta.parents.update(base._meta.parents)
126
166
 
127
167
            # Inherit managers from the abstract base classes.
128
 
            base_managers = base._meta.abstract_managers
129
 
            base_managers.sort()
130
 
            for _, mgr_name, manager in base_managers:
131
 
                val = getattr(new_class, mgr_name, None)
132
 
                if not val or val is manager:
133
 
                    new_manager = manager._copy_to_model(new_class)
134
 
                    new_class.add_to_class(mgr_name, new_manager)
135
 
 
136
 
            # Inherit virtual fields (like GenericForeignKey) from the parent class
 
168
            new_class.copy_managers(base._meta.abstract_managers)
 
169
 
 
170
            # Proxy models inherit the non-abstract managers from their base,
 
171
            # unless they have redefined any of them.
 
172
            if is_proxy:
 
173
                new_class.copy_managers(original_base._meta.concrete_managers)
 
174
 
 
175
            # Inherit virtual fields (like GenericForeignKey) from the parent
 
176
            # class
137
177
            for field in base._meta.virtual_fields:
138
178
                if base._meta.abstract and field.name in field_names:
139
179
                    raise FieldError('Local field %r in class %r clashes '\
159
199
        # registered version.
160
200
        return get_model(new_class._meta.app_label, name, False)
161
201
 
 
202
    def copy_managers(cls, base_managers):
 
203
        # This is in-place sorting of an Options attribute, but that's fine.
 
204
        base_managers.sort()
 
205
        for _, mgr_name, manager in base_managers:
 
206
            val = getattr(cls, mgr_name, None)
 
207
            if not val or val is manager:
 
208
                new_manager = manager._copy_to_model(cls)
 
209
                cls.add_to_class(mgr_name, new_manager)
 
210
 
162
211
    def add_to_class(cls, name, value):
163
212
        if hasattr(value, 'contribute_to_class'):
164
213
            value.contribute_to_class(cls, name)
190
239
 
191
240
class Model(object):
192
241
    __metaclass__ = ModelBase
 
242
    _deferred = False
193
243
 
194
244
    def __init__(self, *args, **kwargs):
195
245
        signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs)
224
274
        # keywords, or default.
225
275
 
226
276
        for field in fields_iter:
227
 
            rel_obj = None
 
277
            is_related_object = False
 
278
            # This slightly odd construct is so that we can access any
 
279
            # data-descriptor object (DeferredAttribute) without triggering its
 
280
            # __get__ method.
 
281
            if (field.attname not in kwargs and
 
282
                    isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute)):
 
283
                # This field will be populated on request.
 
284
                continue
228
285
            if kwargs:
229
286
                if isinstance(field.rel, ManyToOneRel):
230
287
                    try:
231
288
                        # Assume object instance was passed in.
232
289
                        rel_obj = kwargs.pop(field.name)
 
290
                        is_related_object = True
233
291
                    except KeyError:
234
292
                        try:
235
293
                            # Object instance wasn't passed in -- must be an ID.
245
303
                    val = kwargs.pop(field.attname, field.get_default())
246
304
            else:
247
305
                val = field.get_default()
248
 
            # If we got passed a related instance, set it using the field.name
249
 
            # instead of field.attname (e.g. "user" instead of "user_id") so
250
 
            # that the object gets properly cached (and type checked) by the
251
 
            # RelatedObjectDescriptor.
252
 
            if rel_obj:
 
306
            if is_related_object:
 
307
                # If we are passed a related instance, set it using the
 
308
                # field.name instead of field.attname (e.g. "user" instead of
 
309
                # "user_id") so that the object gets properly cached (and type
 
310
                # checked) by the RelatedObjectDescriptor.
253
311
                setattr(self, field.name, rel_obj)
254
312
            else:
255
313
                setattr(self, field.attname, val)
286
344
    def __hash__(self):
287
345
        return hash(self._get_pk_val())
288
346
 
 
347
    def __reduce__(self):
 
348
        """
 
349
        Provide pickling support. Normally, this just dispatches to Python's
 
350
        standard handling. However, for models with deferred field loading, we
 
351
        need to do things manually, as they're dynamically created classes and
 
352
        only module-level classes can be pickled by the default path.
 
353
        """
 
354
        data = self.__dict__
 
355
        if not self._deferred:
 
356
            return (self.__class__, (), data)
 
357
        defers = []
 
358
        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)
 
370
 
289
371
    def _get_pk_val(self, meta=None):
290
372
        if not meta:
291
373
            meta = self._meta
296
378
 
297
379
    pk = property(_get_pk_val, _set_pk_val)
298
380
 
 
381
    def serializable_value(self, field_name):
 
382
        """
 
383
        Returns the value of the field name for this instance. If the field is
 
384
        a foreign key, returns the id value, instead of the object. If there's
 
385
        no Field object with this name on the model, the model attribute's
 
386
        value is returned directly.
 
387
 
 
388
        Used to serialize a field's value (in the serializer, or form output,
 
389
        for example). Normally, you would just access the attribute directly
 
390
        and not use this method.
 
391
        """
 
392
        try:
 
393
            field = self._meta.get_field_by_name(field_name)[0]
 
394
        except FieldDoesNotExist:
 
395
            return getattr(self, field_name)
 
396
        return getattr(self, field.attname)
 
397
 
299
398
    def save(self, force_insert=False, force_update=False):
300
399
        """
301
400
        Saves the current instance. Override this in a subclass if you want to
312
411
 
313
412
    save.alters_data = True
314
413
 
315
 
    def save_base(self, raw=False, cls=None, force_insert=False,
316
 
            force_update=False):
 
414
    def save_base(self, raw=False, cls=None, origin=None,
 
415
            force_insert=False, force_update=False):
317
416
        """
318
417
        Does the heavy-lifting involved in saving. Subclasses shouldn't need to
319
418
        override this method. It's separate from save() in order to hide the
320
419
        need for overrides of save() to pass around internal-only parameters
321
 
        ('raw' and 'cls').
 
420
        ('raw', 'cls', and 'origin').
322
421
        """
323
422
        assert not (force_insert and force_update)
324
 
        if not cls:
 
423
        if cls is None:
325
424
            cls = self.__class__
326
 
            meta = self._meta
327
 
            signal = True
328
 
            signals.pre_save.send(sender=self.__class__, instance=self, raw=raw)
 
425
            meta = cls._meta
 
426
            if not meta.proxy:
 
427
                origin = cls
329
428
        else:
330
429
            meta = cls._meta
331
 
            signal = False
 
430
 
 
431
        if origin:
 
432
            signals.pre_save.send(sender=origin, instance=self, raw=raw)
332
433
 
333
434
        # If we are in a raw save, save the object exactly as presented.
334
435
        # That means that we don't try to be smart about saving attributes
335
436
        # that might have come from the parent class - we just save the
336
437
        # attributes we have been given to the class we have been given.
337
 
        if not raw:
 
438
        # We also go through this process to defer the save of proxy objects
 
439
        # to their actual underlying model.
 
440
        if not raw or meta.proxy:
 
441
            if meta.proxy:
 
442
                org = cls
 
443
            else:
 
444
                org = None
338
445
            for parent, field in meta.parents.items():
339
446
                # At this point, parent's primary key field may be unknown
340
447
                # (for example, from administration form which doesn't fill
341
448
                # this field). If so, fill it.
342
 
                if getattr(self, parent._meta.pk.attname) is None and getattr(self, field.attname) is not None:
 
449
                if field and getattr(self, parent._meta.pk.attname) is None and getattr(self, field.attname) is not None:
343
450
                    setattr(self, parent._meta.pk.attname, getattr(self, field.attname))
344
451
 
345
 
                self.save_base(raw, parent)
346
 
                setattr(self, field.attname, self._get_pk_val(parent._meta))
347
 
 
348
 
        non_pks = [f for f in meta.local_fields if not f.primary_key]
349
 
 
350
 
        # First, try an UPDATE. If that doesn't update anything, do an INSERT.
351
 
        pk_val = self._get_pk_val(meta)
352
 
        pk_set = pk_val is not None
353
 
        record_exists = True
354
 
        manager = cls._default_manager
355
 
        if pk_set:
356
 
            # Determine whether a record with the primary key already exists.
357
 
            if (force_update or (not force_insert and
358
 
                    manager.filter(pk=pk_val).extra(select={'a': 1}).values('a').order_by())):
359
 
                # It does already exist, so do an UPDATE.
360
 
                if force_update or non_pks:
361
 
                    values = [(f, None, f.get_db_prep_save(raw and getattr(self, f.attname) or f.pre_save(self, False))) for f in non_pks]
362
 
                    rows = manager.filter(pk=pk_val)._update(values)
363
 
                    if force_update and not rows:
364
 
                        raise DatabaseError("Forced update did not affect any rows.")
365
 
            else:
 
452
                self.save_base(cls=parent, origin=org)
 
453
 
 
454
                if field:
 
455
                    setattr(self, field.attname, self._get_pk_val(parent._meta))
 
456
            if meta.proxy:
 
457
                return
 
458
 
 
459
        if not meta.proxy:
 
460
            non_pks = [f for f in meta.local_fields if not f.primary_key]
 
461
 
 
462
            # First, try an UPDATE. If that doesn't update anything, do an INSERT.
 
463
            pk_val = self._get_pk_val(meta)
 
464
            pk_set = pk_val is not None
 
465
            record_exists = True
 
466
            manager = cls._base_manager
 
467
            if pk_set:
 
468
                # Determine whether a record with the primary key already exists.
 
469
                if (force_update or (not force_insert and
 
470
                        manager.filter(pk=pk_val).extra(select={'a': 1}).values('a').order_by())):
 
471
                    # It does already exist, so do an UPDATE.
 
472
                    if force_update or non_pks:
 
473
                        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)
 
475
                        if force_update and not rows:
 
476
                            raise DatabaseError("Forced update did not affect any rows.")
 
477
                else:
 
478
                    record_exists = False
 
479
            if not pk_set or not record_exists:
 
480
                if not pk_set:
 
481
                    if force_update:
 
482
                        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)]
 
484
                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]
 
486
 
 
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()))
366
490
                record_exists = False
367
 
        if not pk_set or not record_exists:
368
 
            if not pk_set:
369
 
                if force_update:
370
 
                    raise ValueError("Cannot force an update in save() with no primary key.")
371
 
                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)]
372
 
            else:
373
 
                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]
374
 
 
375
 
            if meta.order_with_respect_to:
376
 
                field = meta.order_with_respect_to
377
 
                values.append((meta.get_field_by_name('_order')[0], manager.filter(**{field.name: getattr(self, field.attname)}).count()))
378
 
            record_exists = False
379
 
 
380
 
            update_pk = bool(meta.has_auto_field and not pk_set)
381
 
            if values:
382
 
                # Create a new record.
383
 
                result = manager._insert(values, return_id=update_pk)
384
 
            else:
385
 
                # Create a new record with defaults for everything.
386
 
                result = manager._insert([(meta.pk, connection.ops.pk_default_value())], return_id=update_pk, raw_values=True)
387
 
 
388
 
            if update_pk:
389
 
                setattr(self, meta.pk.attname, result)
390
 
        transaction.commit_unless_managed()
391
 
 
392
 
        if signal:
393
 
            signals.post_save.send(sender=self.__class__, instance=self,
 
491
 
 
492
                update_pk = bool(meta.has_auto_field and not pk_set)
 
493
                if values:
 
494
                    # Create a new record.
 
495
                    result = manager._insert(values, return_id=update_pk)
 
496
                else:
 
497
                    # 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)
 
499
 
 
500
                if update_pk:
 
501
                    setattr(self, meta.pk.attname, result)
 
502
            transaction.commit_unless_managed()
 
503
 
 
504
        if origin:
 
505
            signals.post_save.send(sender=origin, instance=self,
394
506
                created=(not record_exists), raw=raw)
395
507
 
396
508
    save_base.alters_data = True
418
530
                else:
419
531
                    sub_obj._collect_sub_objects(seen_objs, self.__class__, related.field.null)
420
532
            else:
421
 
                for sub_obj in getattr(self, rel_opts_name).all():
 
533
                # To make sure we can access all elements, we can't use the
 
534
                # normal manager on the related object. So we work directly
 
535
                # with the descriptor object.
 
536
                for cls in self.__class__.mro():
 
537
                    if rel_opts_name in cls.__dict__:
 
538
                        rel_descriptor = cls.__dict__[rel_opts_name]
 
539
                        break
 
540
                else:
 
541
                    raise AssertionError("Should never get here.")
 
542
                delete_qs = rel_descriptor.delete_manager(self).all()
 
543
                for sub_obj in delete_qs:
422
544
                    sub_obj._collect_sub_objects(seen_objs, self.__class__, related.field.null)
423
545
 
424
546
        # Handle any ancestors (for the model-inheritance case). We do this by
425
547
        # traversing to the most remote parent classes -- those with no parents
426
548
        # themselves -- and then adding those instances to the collection. That
427
549
        # will include all the child instances down to "self".
428
 
        parent_stack = self._meta.parents.values()
 
550
        parent_stack = [p for p in self._meta.parents.values() if p is not None]
429
551
        while parent_stack:
430
552
            link = parent_stack.pop()
431
553
            parent_obj = getattr(self, link.name)
481
603
            setattr(self, cachename, obj)
482
604
        return getattr(self, cachename)
483
605
 
 
606
    def prepare_database_save(self, unused):
 
607
        return self.pk
484
608
 
485
609
 
486
610
############################################
522
646
class Empty(object):
523
647
    pass
524
648
 
 
649
def model_unpickle(model, attrs):
 
650
    """
 
651
    Used to unpickle Model subclasses with deferred fields.
 
652
    """
 
653
    from django.db.models.query_utils import deferred_class_factory
 
654
    cls = deferred_class_factory(model, attrs)
 
655
    return cls.__new__(cls)
 
656
model_unpickle.__safe_for_unpickle__ = True
 
657
 
525
658
if sys.version_info < (2, 5):
526
659
    # Prior to Python 2.5, Exception was an old-style class
527
660
    def subclass_exception(name, parent, unused):