mirror of https://github.com/django/django.git
Refactored the way save() works so that non-integer primary keys are now possible. custom_pk unit tests (from [458]) now pass. Refs #81.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@462 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
parent
63e1f3d39c
commit
4622e0ff82
|
@ -208,6 +208,14 @@ class Options:
|
||||||
if self.pk is None:
|
if self.pk is None:
|
||||||
self.fields.insert(0, AutoField('id', 'ID', primary_key=True))
|
self.fields.insert(0, AutoField('id', 'ID', primary_key=True))
|
||||||
self.pk = self.fields[0]
|
self.pk = self.fields[0]
|
||||||
|
# Cache whether this has an AutoField.
|
||||||
|
self.has_auto_field = False
|
||||||
|
for f in self.fields:
|
||||||
|
is_auto = isinstance(f, AutoField)
|
||||||
|
if is_auto and self.has_auto_field:
|
||||||
|
raise AssertionError, "A model can't have more than one AutoField."
|
||||||
|
elif is_auto:
|
||||||
|
self.has_auto_field = True
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return '<Options for %s>' % self.module_name
|
return '<Options for %s>' % self.module_name
|
||||||
|
@ -717,37 +725,27 @@ def method_save(opts, self):
|
||||||
self._pre_save()
|
self._pre_save()
|
||||||
non_pks = [f for f in opts.fields if not f.primary_key]
|
non_pks = [f for f in opts.fields if not f.primary_key]
|
||||||
cursor = db.db.cursor()
|
cursor = db.db.cursor()
|
||||||
add = not bool(getattr(self, opts.pk.name))
|
|
||||||
for f in non_pks:
|
# First, try an UPDATE. If that doesn't update anything, do an INSERT.
|
||||||
f.pre_save(self, getattr(self, f.name), add)
|
pk_set = bool(getattr(self, opts.pk.name))
|
||||||
db_values = [f.get_db_prep_save(getattr(self, f.name)) for f in non_pks]
|
if pk_set:
|
||||||
# OneToOne objects are a special case because there's no AutoField, and the
|
db_values = [f.get_db_prep_save(f.pre_save(getattr(self, f.name), False)) for f in non_pks]
|
||||||
# primary key field is set manually.
|
cursor.execute("UPDATE %s SET %s WHERE %s=%%s" % (opts.db_table,
|
||||||
if isinstance(opts.pk.rel, OneToOne):
|
','.join(['%s=%%s' % f.name for f in non_pks]), opts.pk.name),
|
||||||
cursor.execute("UPDATE %s SET %s WHERE %s=%%s" % \
|
db_values + [getattr(self, opts.pk.name)])
|
||||||
(opts.db_table, ','.join(['%s=%%s' % f.name for f in non_pks]),
|
if not pk_set or cursor.rowcount == 0:
|
||||||
opts.pk.name), db_values + [getattr(self, opts.pk.name)])
|
field_names = [f.name for f in opts.fields if not isinstance(f, AutoField)]
|
||||||
if cursor.rowcount == 0: # If nothing was updated, add the record.
|
placeholders = ['%s'] * len(field_names)
|
||||||
field_names = [f.name for f in opts.fields]
|
db_values = [f.get_db_prep_save(f.pre_save(getattr(self, f.name), True)) for f in opts.fields if not isinstance(f, AutoField)]
|
||||||
placeholders = ['%s'] * len(field_names)
|
if opts.order_with_respect_to:
|
||||||
cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % \
|
field_names.append('_order')
|
||||||
(opts.db_table, ','.join(field_names), ','.join(placeholders)),
|
# TODO: This assumes the database supports subqueries.
|
||||||
[f.get_db_prep_save(getattr(self, f.name)) for f in opts.fields])
|
placeholders.append('(SELECT COUNT(*) FROM %s WHERE %s = %%s)' % \
|
||||||
else:
|
(opts.db_table, opts.order_with_respect_to.name))
|
||||||
if not add:
|
db_values.append(getattr(self, opts.order_with_respect_to.name))
|
||||||
cursor.execute("UPDATE %s SET %s WHERE %s=%%s" % \
|
cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % (opts.db_table,
|
||||||
(opts.db_table, ','.join(['%s=%%s' % f.name for f in non_pks]),
|
','.join(field_names), ','.join(placeholders)), db_values)
|
||||||
opts.pk.name), db_values + [getattr(self, opts.pk.name)])
|
if opts.has_auto_field:
|
||||||
else:
|
|
||||||
field_names = [f.name for f in non_pks]
|
|
||||||
placeholders = ['%s'] * len(field_names)
|
|
||||||
if opts.order_with_respect_to:
|
|
||||||
field_names.append('_order')
|
|
||||||
placeholders.append('(SELECT COUNT(*) FROM %s WHERE %s = %%s)' % \
|
|
||||||
(opts.db_table, opts.order_with_respect_to.name))
|
|
||||||
db_values.append(getattr(self, opts.order_with_respect_to.name))
|
|
||||||
cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % \
|
|
||||||
(opts.db_table, ','.join(field_names), ','.join(placeholders)), db_values)
|
|
||||||
setattr(self, opts.pk.name, db.get_last_insert_id(cursor, opts.db_table, opts.pk.name))
|
setattr(self, opts.pk.name, db.get_last_insert_id(cursor, opts.db_table, opts.pk.name))
|
||||||
db.db.commit()
|
db.db.commit()
|
||||||
# Run any post-save hooks.
|
# Run any post-save hooks.
|
||||||
|
|
|
@ -82,12 +82,9 @@ class Field(object):
|
||||||
else:
|
else:
|
||||||
self.db_index = db_index
|
self.db_index = db_index
|
||||||
|
|
||||||
def pre_save(self, obj, value, add):
|
def pre_save(self, value, add):
|
||||||
"""
|
"Returns field's value just before saving."
|
||||||
Hook for altering the object obj based on the value of this field and
|
return value
|
||||||
and on the add/change status.
|
|
||||||
"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
def get_db_prep_save(self, value):
|
def get_db_prep_save(self, value):
|
||||||
"Returns field's value prepared for saving into a database."
|
"Returns field's value prepared for saving into a database."
|
||||||
|
@ -236,6 +233,10 @@ class Field(object):
|
||||||
|
|
||||||
class AutoField(Field):
|
class AutoField(Field):
|
||||||
empty_strings_allowed = False
|
empty_strings_allowed = False
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
assert kwargs.get('primary_key', False) is True, "%ss must have primary_key=True." % self.__class__.__name__
|
||||||
|
Field.__init__(self, *args, **kwargs)
|
||||||
|
|
||||||
def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False):
|
def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False):
|
||||||
if not rel:
|
if not rel:
|
||||||
return [] # Don't add a FormField unless it's in a related context.
|
return [] # Don't add a FormField unless it's in a related context.
|
||||||
|
@ -280,9 +281,10 @@ class DateField(Field):
|
||||||
value = str(value)
|
value = str(value)
|
||||||
return Field.get_db_prep_lookup(self, lookup_type, value)
|
return Field.get_db_prep_lookup(self, lookup_type, value)
|
||||||
|
|
||||||
def pre_save(self, obj, value, add):
|
def pre_save(self, value, add):
|
||||||
if self.auto_now or (self.auto_now_add and add):
|
if self.auto_now or (self.auto_now_add and add):
|
||||||
setattr(obj, self.name, datetime.datetime.now())
|
return datetime.datetime.now()
|
||||||
|
return value
|
||||||
|
|
||||||
def get_db_prep_save(self, value):
|
def get_db_prep_save(self, value):
|
||||||
# Casts dates into string format for entry into database.
|
# Casts dates into string format for entry into database.
|
||||||
|
@ -483,9 +485,10 @@ class TimeField(Field):
|
||||||
value = str(value)
|
value = str(value)
|
||||||
return Field.get_db_prep_lookup(self, lookup_type, value)
|
return Field.get_db_prep_lookup(self, lookup_type, value)
|
||||||
|
|
||||||
def pre_save(self, obj, value, add):
|
def pre_save(self, value, add):
|
||||||
if self.auto_now or (self.auto_now_add and add):
|
if self.auto_now or (self.auto_now_add and add):
|
||||||
setattr(obj, self.name, datetime.datetime.now().time())
|
return datetime.datetime.now().time()
|
||||||
|
return value
|
||||||
|
|
||||||
def get_db_prep_save(self, value):
|
def get_db_prep_save(self, value):
|
||||||
# Casts dates into string format for entry into database.
|
# Casts dates into string format for entry into database.
|
||||||
|
|
Loading…
Reference in New Issue