magic-removal: Refactored database-access code to use Model._get_pk_val() for simplicity
git-svn-id: http://code.djangoproject.com/svn/django/branches/magic-removal@2039 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
parent
6e8d06572a
commit
5c970704fe
|
@ -63,11 +63,14 @@ def cmp_cls(x, y):
|
|||
class Model(object):
|
||||
__metaclass__ = ModelBase
|
||||
|
||||
def _get_pk_val(self):
|
||||
return getattr(self, self._meta.pk.attname)
|
||||
|
||||
def __repr__(self):
|
||||
return '<%s object>' % self.__class__.__name__
|
||||
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, self.__class__) and getattr(self, self._meta.pk.attname) == getattr(other, self._meta.pk.attname)
|
||||
return isinstance(other, self.__class__) and self._get_pk_val() == other._get_pk_val()
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self.__eq__(other)
|
||||
|
@ -143,7 +146,7 @@ class Model(object):
|
|||
cursor = connection.cursor()
|
||||
|
||||
# First, try an UPDATE. If that doesn't update anything, do an INSERT.
|
||||
pk_val = getattr(self, self._meta.pk.attname)
|
||||
pk_val = self._get_pk_val()
|
||||
pk_set = bool(pk_val)
|
||||
record_exists = True
|
||||
if pk_set:
|
||||
|
@ -186,11 +189,8 @@ class Model(object):
|
|||
|
||||
save.alters_data = True
|
||||
|
||||
def __get_pk_val(self):
|
||||
return str(getattr(self, self._meta.pk.attname))
|
||||
|
||||
def __collect_sub_objects(self, seen_objs):
|
||||
pk_val = self.__get_pk_val()
|
||||
pk_val = self._get_pk_val()
|
||||
|
||||
if pk_val in seen_objs.setdefault(self.__class__, {}):
|
||||
return
|
||||
|
@ -210,11 +210,11 @@ class Model(object):
|
|||
sub_obj.__collect_sub_objects(seen_objs)
|
||||
|
||||
def delete(self, ignore_objects=None):
|
||||
assert getattr(self, self._meta.pk.attname) is not None, "%r can't be deleted because it doesn't have an ID."
|
||||
assert self._get_pk_val() is not None, "%r can't be deleted because it doesn't have an ID."
|
||||
seen_objs = {}
|
||||
if ignore_objects:
|
||||
for obj in ignore_objects:
|
||||
ignore_objs.setdefault(self.__class__,{})[obj.__get_pk_val()] = (obj, False)
|
||||
ignore_objs.setdefault(self.__class__,{})[obj._get_pk_val()] = (obj, False)
|
||||
|
||||
seen_objs = {}
|
||||
self.__collect_sub_objects(seen_objs)
|
||||
|
@ -230,7 +230,7 @@ class Model(object):
|
|||
for cls in cls_order:
|
||||
seen_objs[cls] = seen_objs[cls].items()
|
||||
seen_objs[cls].sort()
|
||||
for pk_val,(instance, do_delete) in seen_objs[cls]:
|
||||
for pk_val, (instance, do_delete) in seen_objs[cls]:
|
||||
|
||||
# Run any pre-delete hooks.
|
||||
if do_delete:
|
||||
|
@ -297,7 +297,7 @@ class Model(object):
|
|||
backend.quote_name(opts.db_table), backend.quote_name(opts.pk.column)),
|
||||
'%s=%%s' % backend.quote_name(order_field.column)],
|
||||
limit=1,
|
||||
params=[getattr(self, opts.pk.attname), getattr(self, order_field.attname)])
|
||||
params=[self._get_pk_val(), getattr(self, order_field.attname)])
|
||||
setattr(self, cachename, obj)
|
||||
return getattr(self, cachename)
|
||||
|
||||
|
@ -394,12 +394,12 @@ class Model(object):
|
|||
backend.quote_name(rel_opts.object_name.lower() + '_id'),
|
||||
backend.quote_name(self._meta.object_name.lower() + '_id'), rel_opts.get_order_sql('a'))
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(sql, [getattr(self, self._meta.pk.attname)])
|
||||
cursor.execute(sql, [self._get_pk_val()])
|
||||
setattr(self, cache_var, [field_with_rel.rel.to(*row) for row in cursor.fetchall()])
|
||||
return getattr(self, cache_var)
|
||||
|
||||
def _set_many_to_many_objects(self, id_list, field_with_rel):
|
||||
current_ids = [getattr(obj, obj._meta.pk.attname) for obj in self._get_many_to_many_objects(field_with_rel)]
|
||||
current_ids = [obj._get_pk_val() for obj in self._get_many_to_many_objects(field_with_rel)]
|
||||
ids_to_add, ids_to_delete = dict([(i, 1) for i in id_list]), []
|
||||
for current_id in current_ids:
|
||||
if current_id in id_list:
|
||||
|
@ -413,7 +413,7 @@ class Model(object):
|
|||
rel = field_with_rel.rel.to._meta
|
||||
m2m_table = field_with_rel.get_m2m_db_table(self._meta)
|
||||
cursor = connection.cursor()
|
||||
this_id = getattr(self, self._meta.pk.attname)
|
||||
this_id = self._get_pk_val()
|
||||
if ids_to_delete:
|
||||
sql = "DELETE FROM %s WHERE %s = %%s AND %s IN (%s)" % \
|
||||
(backend.quote_name(m2m_table),
|
||||
|
@ -456,7 +456,7 @@ class Model(object):
|
|||
# Handles related many-to-many object retrieval.
|
||||
# Examples: Album.get_song(), Album.get_song_list(), Album.get_song_count()
|
||||
def _get_related_many_to_many(self, method_name, rel_class, rel_field, **kwargs):
|
||||
kwargs['%s__%s__exact' % (rel_field.name, self._meta.pk.name)] = getattr(self, self._meta.pk.attname)
|
||||
kwargs['%s__%s__exact' % (rel_field.name, self._meta.pk.name)] = self._get_pk_val()
|
||||
return getattr(rel_class._default_manager, method_name)(**kwargs)
|
||||
|
||||
# Handles setting many-to-many related objects.
|
||||
|
@ -465,7 +465,7 @@ class Model(object):
|
|||
id_list = map(int, id_list) # normalize to integers
|
||||
rel = rel_field.rel.to
|
||||
m2m_table = rel_field.get_m2m_db_table(rel_opts)
|
||||
this_id = getattr(self, self._meta.pk.attname)
|
||||
this_id = self._get_pk_val()
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("DELETE FROM %s WHERE %s = %%s" % \
|
||||
(backend.quote_name(m2m_table),
|
||||
|
|
|
@ -32,7 +32,7 @@ def manipulator_validator_unique(f, opts, self, field_data, all_data):
|
|||
old_obj = self.manager.get_object(**{lookup_type: field_data})
|
||||
except ObjectDoesNotExist:
|
||||
return
|
||||
if hasattr(self, 'original_object') and getattr(self.original_object, opts.pk.attname) == getattr(old_obj, opts.pk.attname):
|
||||
if hasattr(self, 'original_object') and self.original_object._get_pk_val() == old_obj._get_pk_val():
|
||||
return
|
||||
raise validators.ValidationError, _("%(optname)s with this %(fieldname)s already exists.") % {'optname': capfirst(opts.verbose_name), 'fieldname': f.verbose_name}
|
||||
|
||||
|
@ -290,7 +290,7 @@ class Field(object):
|
|||
if self.choices:
|
||||
return first_choice + list(self.choices)
|
||||
rel_model = self.rel.to
|
||||
return first_choice + [(getattr(x, rel_model._meta.pk.attname), str(x))
|
||||
return first_choice + [(x._get_pk_val(), str(x))
|
||||
for x in rel_model._default_manager.get_list(**rel_model._meta.limit_choices_to)]
|
||||
|
||||
def get_choices_default(self):
|
||||
|
|
|
@ -261,7 +261,7 @@ class ManyToManyField(RelatedField, Field):
|
|||
new_data = {}
|
||||
if obj:
|
||||
get_list_func = getattr(obj, 'get_%s_list' % self.rel.singular)
|
||||
instance_ids = [getattr(instance, self.rel.to._meta.pk.attname) for instance in get_list_func()]
|
||||
instance_ids = [instance._get_pk_val() for instance in get_list_func()]
|
||||
if self.rel.raw_id_admin:
|
||||
new_data[self.name] = ",".join([str(id) for id in instance_ids])
|
||||
else:
|
||||
|
|
|
@ -63,7 +63,7 @@ class Manager(object):
|
|||
joins = SortedDict()
|
||||
where = kwargs.get('where') and kwargs['where'][:] or []
|
||||
params = kwargs.get('params') and kwargs['params'][:] or []
|
||||
|
||||
|
||||
# Convert all the args into SQL.
|
||||
table_count = 0
|
||||
for arg in args:
|
||||
|
@ -156,14 +156,14 @@ class Manager(object):
|
|||
kwargs['order_by'] = []
|
||||
kwargs['offset'] = None
|
||||
kwargs['limit'] = None
|
||||
|
||||
|
||||
opts = self.klass._meta
|
||||
|
||||
# Perform the SQL delete
|
||||
cursor = connection.cursor()
|
||||
_, sql, params = self._get_sql_clause(False, *args, **kwargs)
|
||||
cursor.execute("DELETE " + sql, params)
|
||||
|
||||
|
||||
def get_iterator(self, *args, **kwargs):
|
||||
# kwargs['select'] is a dictionary, and dictionaries' key order is
|
||||
# undefined, so we convert it to a list of tuples internally.
|
||||
|
@ -213,7 +213,7 @@ class Manager(object):
|
|||
kwargs['where'] = ["%s.%s IN (%s)" % (backend.quote_name(self.klass._meta.db_table), backend.quote_name(self.klass._meta.pk.column), ",".join(['%s'] * len(id_list)))]
|
||||
kwargs['params'] = id_list
|
||||
obj_list = self.get_list(*args, **kwargs)
|
||||
return dict([(getattr(o, self.klass._meta.pk.attname), o) for o in obj_list])
|
||||
return dict([(obj._get_pk_val(), obj) for obj in obj_list])
|
||||
|
||||
def get_values_iterator(self, *args, **kwargs):
|
||||
# select_related and select aren't supported in get_values().
|
||||
|
|
|
@ -170,7 +170,7 @@ class AutomaticManipulator(Manipulator, Naming):
|
|||
# TODO: many to many
|
||||
self.original_object.save()
|
||||
if not hasattr(self, 'obj_key'):
|
||||
self.obj_key = getattr(self.original_object, self.opts.pk.attname)
|
||||
self.obj_key = self.original_object._get_pk_val()
|
||||
|
||||
for related, manips in self.children.items():
|
||||
manips.save_from_update(self.obj_key)
|
||||
|
@ -292,7 +292,7 @@ class ModelChangeManipulator(AutomaticManipulator):
|
|||
opts = self.model._meta
|
||||
if isinstance(obj_key, self.model):
|
||||
original_object = obj_key
|
||||
self.obj_key = getattr(original_object, self.model._meta.pk.attname)
|
||||
self.obj_key = original_object._get_pk_val()
|
||||
else:
|
||||
self.obj_key = obj_key
|
||||
try:
|
||||
|
@ -317,7 +317,7 @@ class ModelChangeManipulator(AutomaticManipulator):
|
|||
else:
|
||||
# Save the obj_key even though we already have it, in case it's
|
||||
# currently a string and needs to be an integer.
|
||||
self.obj_key = getattr(original_object, self.model._meta.pk.attname)
|
||||
self.obj_key = original_object._get_pk_val()
|
||||
|
||||
super(ModelChangeManipulator, self).__init__(original_object=original_object, follow=follow, name_parts=name_parts)
|
||||
#self.original_object = original_object
|
||||
|
@ -488,7 +488,7 @@ def manipulator_validator_unique_together(field_name_list, opts, self, field_dat
|
|||
old_obj = mod.get_object(**kwargs)
|
||||
except ObjectDoesNotExist:
|
||||
return
|
||||
if hasattr(self, 'original_object') and getattr(self.original_object, opts.pk.attname) == getattr(old_obj, opts.pk.attname):
|
||||
if hasattr(self, 'original_object') and self.original_object._get_pk_val() == old_obj._get_pk_val():
|
||||
pass
|
||||
else:
|
||||
raise validators.ValidationError, _("%(object)s with this %(type)s already exists for the given %(field)s.") % \
|
||||
|
@ -514,7 +514,7 @@ def manipulator_validator_unique_for_date(from_field, date_field, opts, lookup_t
|
|||
except ObjectDoesNotExist:
|
||||
return
|
||||
else:
|
||||
if hasattr(self, 'original_object') and getattr(self.original_object, opts.pk.attname) == getattr(old_obj, opts.pk.attname):
|
||||
if hasattr(self, 'original_object') and self.original_object._get_pk_val() == old_obj._get_pk_val():
|
||||
pass
|
||||
else:
|
||||
format_string = (lookup_type == 'date') and '%B %d, %Y' or '%B %Y'
|
||||
|
|
Loading…
Reference in New Issue