1
0
mirror of https://github.com/django/django.git synced 2025-06-05 03:29:12 +00:00

magic-removal: Removed unnecessary legacy 'import copy' and restored some spacing that had been changed (for easier understanding of diffs)

git-svn-id: http://code.djangoproject.com/svn/django/branches/magic-removal@2156 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Adrian Holovaty 2006-01-29 02:02:58 +00:00
parent 5bac096399
commit 83f8870489
2 changed files with 37 additions and 43 deletions

View File

@ -7,7 +7,6 @@ from django.db.models.query import handle_legacy_orderlist, orderlist2sql, order
from django.dispatch import dispatcher from django.dispatch import dispatcher
from django.db.models import signals from django.db.models import signals
from django.utils.datastructures import SortedDict from django.utils.datastructures import SortedDict
import copy
# Size of each "chunk" for get_iterator calls. # Size of each "chunk" for get_iterator calls.
# Larger values are slightly faster at the expense of more storage space. # Larger values are slightly faster at the expense of more storage space.
@ -19,7 +18,6 @@ def ensure_default_manager(sender):
# Create the default manager, if needed. # Create the default manager, if needed.
if hasattr(cls, 'objects'): if hasattr(cls, 'objects'):
raise ValueError, "Model %s must specify a custom Manager, because it has a field named 'objects'" % name raise ValueError, "Model %s must specify a custom Manager, because it has a field named 'objects'" % name
cls.add_to_class('objects', Manager()) cls.add_to_class('objects', Manager())
cls.objects._prepare() cls.objects._prepare()
@ -35,7 +33,7 @@ class Manager(QuerySet):
self.creation_counter = Manager.creation_counter self.creation_counter = Manager.creation_counter
Manager.creation_counter += 1 Manager.creation_counter += 1
self.klass = None self.klass = None
def _prepare(self): def _prepare(self):
pass pass
# TODO # TODO
@ -60,7 +58,7 @@ class Manager(QuerySet):
raise self.klass.DoesNotExist, "%s does not exist for %s" % (self.klass._meta.object_name, kwargs) raise self.klass.DoesNotExist, "%s does not exist for %s" % (self.klass._meta.object_name, kwargs)
assert len(obj_list) == 1, "get_object() returned more than one %s -- it returned %s! Lookup parameters were %s" % (self.klass._meta.object_name, len(obj_list), kwargs) assert len(obj_list) == 1, "get_object() returned more than one %s -- it returned %s! Lookup parameters were %s" % (self.klass._meta.object_name, len(obj_list), kwargs)
return obj_list[0] return obj_list[0]
def in_bulk(self, id_list, **kwargs): def in_bulk(self, id_list, **kwargs):
assert isinstance(id_list, list), "in_bulk() must be provided with a list of IDs." assert isinstance(id_list, list), "in_bulk() must be provided with a list of IDs."
assert id_list != [], "in_bulk() cannot be passed an empty ID list." assert id_list != [], "in_bulk() cannot be passed an empty ID list."
@ -68,8 +66,8 @@ class Manager(QuerySet):
if kwargs: if kwargs:
new_query = self.filter(**kwargs) new_query = self.filter(**kwargs)
new_query = new_query.extras(where= new_query = new_query.extras(where=
["%s.%s IN (%s)" % (backend.quote_name(self.klass._meta.db_table), ["%s.%s IN (%s)" % (backend.quote_name(self.klass._meta.db_table),
backend.quote_name(self.klass._meta.pk.column), backend.quote_name(self.klass._meta.pk.column),
",".join(['%s'] * len(id_list)))], ",".join(['%s'] * len(id_list)))],
params=id_list) params=id_list)
obj_list = list(new_query) obj_list = list(new_query)
@ -82,7 +80,7 @@ class Manager(QuerySet):
# Check for at least one query argument. # Check for at least one query argument.
if not kwargs and not delete_all: if not kwargs and not delete_all:
raise TypeError, "SAFETY MECHANISM: Specify DELETE_ALL=True if you actually want to delete all data." raise TypeError, "SAFETY MECHANISM: Specify DELETE_ALL=True if you actually want to delete all data."
if kwargs: if kwargs:
del_query = self.filter(**kwargs) del_query = self.filter(**kwargs)
else: else:
@ -99,8 +97,8 @@ class Manager(QuerySet):
# Perform the SQL delete # Perform the SQL delete
cursor = connection.cursor() cursor = connection.cursor()
_, sql, params = del_query._get_sql_clause(False) _, sql, params = del_query._get_sql_clause(False)
cursor.execute("DELETE " + sql, params) cursor.execute("DELETE " + sql, params)
class OldManager(object): class OldManager(object):
# Tracks each time a Manager instance is created. Used to retain order. # Tracks each time a Manager instance is created. Used to retain order.
@ -369,5 +367,4 @@ class ManagerDescriptor(object):
def __get__(self, instance, type=None): def __get__(self, instance, type=None):
if instance != None: if instance != None:
raise AttributeError, "Manager isn't accessible via %s instances" % type.__name__ raise AttributeError, "Manager isn't accessible via %s instances" % type.__name__
return self.manager return self.manager

View File

@ -68,7 +68,7 @@ class QuerySet(object):
self._offset = None self._offset = None
self._limit = None self._limit = None
self._use_cache = False self._use_cache = False
def filter(self, **kwargs): def filter(self, **kwargs):
"""Returns a new query instance with the query arguments """Returns a new query instance with the query arguments
ANDed to the existing set""" ANDed to the existing set"""
@ -83,31 +83,30 @@ class QuerySet(object):
def order_by(self, *field_names): def order_by(self, *field_names):
"""Returns a new query instance with the ordering changed.""" """Returns a new query instance with the ordering changed."""
return self._clone(_order_by=field_names) return self._clone(_order_by=field_names)
def select_related(self, true_or_false): def select_related(self, true_or_false):
"""Returns a new query instance with the 'related' qualifier modified""" """Returns a new query instance with the 'related' qualifier modified"""
return self._clone(_related=true_or_false) return self._clone(_related=true_or_false)
def count(self): def count(self):
counter = self._clone() counter = self._clone()
counter._order_by = [] counter._order_by = []
# TODO - do we change these or not? # TODO - do we change these or not?
# e.g. if someone does objects[0:10].count() # e.g. if someone does objects[0:10].count()
# (which # (which
#counter._offset = None #counter._offset = None
#counter._limit = None #counter._limit = None
counter._select_related = False counter._select_related = False
_, sql, params = counter._get_sql_clause(True) _, sql, params = counter._get_sql_clause(True)
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("SELECT COUNT(*)" + sql, params) cursor.execute("SELECT COUNT(*)" + sql, params)
return cursor.fetchone()[0] return cursor.fetchone()[0]
# Convenience function for subclasses # Convenience function for subclasses
def _set_core_filter(self, **kwargs): def _set_core_filter(self, **kwargs):
"""Sets the filters that should always be applied to queries""" """Sets the filters that should always be applied to queries"""
self._filter = Q(**kwargs) self._filter = Q(**kwargs)
def _clone(self, **kwargs): def _clone(self, **kwargs):
"""Gets a clone of the object, with optional kwargs to alter the clone""" """Gets a clone of the object, with optional kwargs to alter the clone"""
@ -121,26 +120,26 @@ class QuerySet(object):
# restore cache # restore cache
self._result_cache = _result_cache_save self._result_cache = _result_cache_save
return clone return clone
def _ensure_compatible(self, other): def _ensure_compatible(self, other):
if self._distinct != other._distinct: if self._distinct != other._distinct:
raise ValueException, "Can't combine a unique query with a non-unique query" raise ValueException, "Can't combine a unique query with a non-unique query"
def _combine(self, other): def _combine(self, other):
self._ensure_compatible(other) self._ensure_compatible(other)
# get a deepcopy of 'other's order by # get a deepcopy of 'other's order by
# (so that A.filter(args1) & A.filter(args2) does the same as # (so that A.filter(args1) & A.filter(args2) does the same as
# A.filter(args1).filter(args2) # A.filter(args1).filter(args2)
combined = other._clone() combined = other._clone()
# If 'self' is ordered and 'other' isn't, propagate 'self's ordering # If 'self' is ordered and 'other' isn't, propagate 'self's ordering
if len(self._order_by) > 0 and len(combined._order_by == 0): if len(self._order_by) > 0 and len(combined._order_by == 0):
combined._order_by = copy.deepcopy(self._order_by) combined._order_by = copy.deepcopy(self._order_by)
return combined return combined
def extras(self, params=None, select=None, where=None, tables=None): def extras(self, params=None, select=None, where=None, tables=None):
return self._clone(_params=params, _select=select, _where=where, _tables=tables) return self._clone(_params=params, _select=select, _where=where, _tables=tables)
def __and__(self, other): def __and__(self, other):
combined = self._combine(other) combined = self._combine(other)
combined._filter = self._filter & other._filter combined._filter = self._filter & other._filter
return combined return combined
@ -149,7 +148,7 @@ class QuerySet(object):
combined = self._combine(other) combined = self._combine(other)
combined._filter = self._filter | other._filter combined._filter = self._filter | other._filter
return combined return combined
# TODO - allow_joins - do we need it? # TODO - allow_joins - do we need it?
def _get_sql_clause(self, allow_joins): def _get_sql_clause(self, allow_joins):
def quote_only_if_word(word): def quote_only_if_word(word):
@ -166,13 +165,13 @@ class QuerySet(object):
select = ["%s.%s" % (backend.quote_name(opts.db_table), backend.quote_name(f.column)) for f in opts.fields] select = ["%s.%s" % (backend.quote_name(opts.db_table), backend.quote_name(f.column)) for f in opts.fields]
tables = [quote_only_if_word(t) for t in (self._tables or [])] tables = [quote_only_if_word(t) for t in (self._tables or [])]
joins = SortedDict() joins = SortedDict()
where = self._where or [] where = self._where or []
params = self._params or [] params = self._params or []
# Convert the Q object into SQL. # Convert the Q object into SQL.
tables2, joins2, where2, params2 = self._filter.get_sql(opts) tables2, joins2, where2, params2 = self._filter.get_sql(opts)
tables.extend(tables2) tables.extend(tables2)
joins.update(joins2) joins.update(joins2)
where.extend(where2) where.extend(where2)
@ -238,8 +237,8 @@ class QuerySet(object):
else: else:
assert self._offset is None, "'offset' is not allowed without 'limit'" assert self._offset is None, "'offset' is not allowed without 'limit'"
return select, " ".join(sql), params return select, " ".join(sql), params
def _fetch_data(self): def _fetch_data(self):
if self._use_cache: if self._use_cache:
if self._result_cache is None: if self._result_cache is None:
@ -247,8 +246,7 @@ class QuerySet(object):
return self._result_cache return self._result_cache
else: else:
return list(self.get_iterator()) return list(self.get_iterator())
def __iter__(self): def __iter__(self):
"""Gets an iterator for the data""" """Gets an iterator for the data"""
# Fetch the data or use get_iterator? If not, we can't # Fetch the data or use get_iterator? If not, we can't
@ -256,13 +254,13 @@ class QuerySet(object):
# Also, lots of things in current template system break if we # Also, lots of things in current template system break if we
# don't get it all. # don't get it all.
return iter(self._fetch_data()) return iter(self._fetch_data())
def __len__(self): def __len__(self):
return len(self._fetch_data()) return len(self._fetch_data())
def __getitem__(self, k): def __getitem__(self, k):
"""Retrieve an item or slice from the set of results""" """Retrieve an item or slice from the set of results"""
# getitem can't return query instances, because .filter() # getitem can't return query instances, because .filter()
# and .order_by() methods on the result would break badly. # and .order_by() methods on the result would break badly.
# This means we don't have to worry about arithmetic with # This means we don't have to worry about arithmetic with
# self._limit or self._offset - they will both be None # self._limit or self._offset - they will both be None
@ -270,7 +268,7 @@ class QuerySet(object):
if isinstance(k, slice): if isinstance(k, slice):
# Get a new query if we haven't already got data from db # Get a new query if we haven't already got data from db
if self._result_cache is None: if self._result_cache is None:
# slice.stop and slice.start # slice.stop and slice.start
clone = self._clone(_offset=k.start, _limit=k.stop) clone = self._clone(_offset=k.start, _limit=k.stop)
return list(clone)[::k.step] return list(clone)[::k.step]
# TODO - we are throwing away this retrieved data. # TODO - we are throwing away this retrieved data.
@ -278,17 +276,17 @@ class QuerySet(object):
# list structure we could put it in. # list structure we could put it in.
else: else:
return self._result_cache[k] return self._result_cache[k]
else: else:
# TODO: possibly use a new query which just gets one item # TODO: possibly use a new query which just gets one item
# if we haven't already got them all? # if we haven't already got them all?
return self._fetch_data()[k] return self._fetch_data()[k]
def get_iterator(self): def get_iterator(self):
# self._select is a dictionary, and dictionaries' key order is # self._select is a dictionary, and dictionaries' key order is
# undefined, so we convert it to a list of tuples. # undefined, so we convert it to a list of tuples.
_extra_select = (self._select or {}).items() _extra_select = (self._select or {}).items()
cursor = connection.cursor() cursor = connection.cursor()
select, sql, params = self._get_sql_clause(True) select, sql, params = self._get_sql_clause(True)
cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params) cursor.execute("SELECT " + (self._distinct and "DISTINCT " or "") + ",".join(select) + sql, params)
@ -306,7 +304,7 @@ class QuerySet(object):
for i, k in enumerate(_extra_select): for i, k in enumerate(_extra_select):
setattr(obj, k[0], row[index_end+i]) setattr(obj, k[0], row[index_end+i])
yield obj yield obj
class QOperator: class QOperator:
"Base class for QAnd and QOr" "Base class for QAnd and QOr"
def __init__(self, *args): def __init__(self, *args):
@ -382,7 +380,6 @@ class Q:
def get_sql(self, opts): def get_sql(self, opts):
return parse_lookup(self.kwargs.items(), opts) return parse_lookup(self.kwargs.items(), opts)
def get_where_clause(lookup_type, table_prefix, field_name, value): def get_where_clause(lookup_type, table_prefix, field_name, value):
if table_prefix.endswith('.'): if table_prefix.endswith('.'):
table_prefix = backend.quote_name(table_prefix[:-1])+'.' table_prefix = backend.quote_name(table_prefix[:-1])+'.'
@ -453,19 +450,19 @@ def parse_lookup(kwarg_items, opts):
# there for others to implement custom Q()s, etc that return other join # there for others to implement custom Q()s, etc that return other join
# types. # types.
tables, joins, where, params = [], SortedDict(), [], [] tables, joins, where, params = [], SortedDict(), [], []
for kwarg, value in kwarg_items: for kwarg, value in kwarg_items:
if value is None: if value is None:
pass pass
else: else:
path = kwarg.split(LOOKUP_SEPARATOR) path = kwarg.split(LOOKUP_SEPARATOR)
# Extract the last elements of the kwarg. # Extract the last elements of the kwarg.
# The very-last is the clause (equals, like, etc). # The very-last is the clause (equals, like, etc).
# The second-last is the table column on which the clause is # The second-last is the table column on which the clause is
# to be performed. # to be performed.
# The exceptions to this are: # The exceptions to this are:
# 1) "pk", which is an implicit id__exact; # 1) "pk", which is an implicit id__exact;
# if we find "pk", make the clause "exact', and insert # if we find "pk", make the clause "exact', and insert
# a dummy name of None, which we will replace when # a dummy name of None, which we will replace when
# we know which table column to grab as the primary key. # we know which table column to grab as the primary key.
# 2) If there is only one part, assume it to be an __exact # 2) If there is only one part, assume it to be an __exact
@ -476,7 +473,7 @@ def parse_lookup(kwarg_items, opts):
elif len(path) == 0: elif len(path) == 0:
path.append(clause) path.append(clause)
clause = 'exact' clause = 'exact'
if len(path) < 1: if len(path) < 1:
raise TypeError, "Cannot parse keyword query %r" % kwarg raise TypeError, "Cannot parse keyword query %r" % kwarg