79
91
for obj_name, obj in attrs.items():
80
92
new_class.add_to_class(obj_name, obj)
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])
100
# Basic setup for proxy models.
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)
110
raise TypeError("Proxy model '%s' has more than one non-abstract model base class." % name)
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."
119
while base._meta.proxy:
120
base = base._meta.proxy_for_model
121
new_class._meta.setup_proxy(base)
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)])
85
127
for base in parents:
86
129
if not hasattr(base, '_meta'):
87
130
# Things without _meta aren't functional models, so they're
88
131
# uninteresting parents.
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])
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
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 '
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)
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)
108
158
new_class._meta.parents[base] = field
111
160
# .. and abstract ones.
113
# Check for clashes between locally declared fields and those
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))
124
164
# Pass any non-abstract parent classes onto child.
125
165
new_class._meta.parents.update(base._meta.parents)
127
167
# Inherit managers from the abstract base classes.
128
base_managers = base._meta.abstract_managers
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)
136
# Inherit virtual fields (like GenericForeignKey) from the parent class
168
new_class.copy_managers(base._meta.abstract_managers)
170
# Proxy models inherit the non-abstract managers from their base,
171
# unless they have redefined any of them.
173
new_class.copy_managers(original_base._meta.concrete_managers)
175
# Inherit virtual fields (like GenericForeignKey) from the parent
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 '\
313
412
save.alters_data = True
315
def save_base(self, raw=False, cls=None, force_insert=False,
414
def save_base(self, raw=False, cls=None, origin=None,
415
force_insert=False, force_update=False):
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
420
('raw', 'cls', and 'origin').
323
422
assert not (force_insert and force_update)
325
424
cls = self.__class__
328
signals.pre_save.send(sender=self.__class__, instance=self, raw=raw)
432
signals.pre_save.send(sender=origin, instance=self, raw=raw)
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.
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:
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))
345
self.save_base(raw, parent)
346
setattr(self, field.attname, self._get_pk_val(parent._meta))
348
non_pks = [f for f in meta.local_fields if not f.primary_key]
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
354
manager = cls._default_manager
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.")
452
self.save_base(cls=parent, origin=org)
455
setattr(self, field.attname, self._get_pk_val(parent._meta))
460
non_pks = [f for f in meta.local_fields if not f.primary_key]
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
466
manager = cls._base_manager
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.")
478
record_exists = False
479
if not pk_set or not record_exists:
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)]
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]
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:
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)]
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]
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
380
update_pk = bool(meta.has_auto_field and not pk_set)
382
# Create a new record.
383
result = manager._insert(values, return_id=update_pk)
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)
389
setattr(self, meta.pk.attname, result)
390
transaction.commit_unless_managed()
393
signals.post_save.send(sender=self.__class__, instance=self,
492
update_pk = bool(meta.has_auto_field and not pk_set)
494
# Create a new record.
495
result = manager._insert(values, return_id=update_pk)
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)
501
setattr(self, meta.pk.attname, result)
502
transaction.commit_unless_managed()
505
signals.post_save.send(sender=origin, instance=self,
394
506
created=(not record_exists), raw=raw)
396
508
save_base.alters_data = True
419
531
sub_obj._collect_sub_objects(seen_objs, self.__class__, related.field.null)
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]
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)
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)