Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #214 -- Added get_values() and get_values_iterator() module-lev…

…el functions to DB API. Thanks, rmunn

git-svn-id: http://code.djangoproject.com/svn/django/trunk@359 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 1a8fc57bf6e4b86fe047d04fea2efe50296634d0 1 parent 3aa33ed
Adrian Holovaty authored August 01, 2005
33  django/core/meta.py
@@ -562,6 +562,12 @@ def __new__(cls, name, bases, attrs):
562 562
         new_mod.get_iterator = curry(function_get_iterator, opts, new_class)
563 563
         new_mod.get_iterator.__doc__ = "Returns an iterator of %s objects matching the given parameters." % name
564 564
 
  565
+        new_mod.get_values = curry(function_get_values, opts, new_class)
  566
+        new_mod.get_values.__doc__ = "Returns a list of dictionaries matching the given parameters."
  567
+
  568
+        new_mod.get_values_iterator = curry(function_get_values_iterator, opts, new_class)
  569
+        new_mod.get_values_iterator.__doc__ = "Returns an iterator of dictionaries matching the given parameters."
  570
+
565 571
         new_mod.get_count = curry(function_get_count, opts)
566 572
         new_mod.get_count.__doc__ = "Returns the number of %s objects matching the given parameters." % name
567 573
 
@@ -1083,6 +1089,31 @@ def function_get_count(opts, **kwargs):
1083 1089
     cursor.execute("SELECT COUNT(*)" + sql, params)
1084 1090
     return cursor.fetchone()[0]
1085 1091
 
  1092
+def function_get_values_iterator(opts, klass, **kwargs):
  1093
+    # select_related and select aren't supported in get_values().
  1094
+    kwargs['select_related'] = False
  1095
+    kwargs['select'] = {}
  1096
+
  1097
+    # 'fields' is a list of field names to fetch.
  1098
+    try:
  1099
+        fields = kwargs.pop('fields')
  1100
+    except KeyError: # Default to all fields.
  1101
+        fields = [f.name for f in opts.fields]
  1102
+
  1103
+    cursor = db.db.cursor()
  1104
+    _, sql, params = function_get_sql_clause(opts, **kwargs)
  1105
+    select = ['%s.%s' % (opts.db_table, f) for f in fields]
  1106
+    cursor.execute("SELECT " + (kwargs.get('distinct') and "DISTINCT " or "") + ",".join(select) + sql, params)
  1107
+    while 1:
  1108
+        rows = cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)
  1109
+        if not rows:
  1110
+            raise StopIteration
  1111
+        for row in rows:
  1112
+            yield dict(zip(fields, row))
  1113
+
  1114
+def function_get_values(opts, klass, **kwargs):
  1115
+    return list(function_get_values_iterator(opts, klass, **kwargs))
  1116
+
1086 1117
 def _fill_table_cache(opts, select, tables, where, old_prefix, cache_tables_seen):
1087 1118
     """
1088 1119
     Helper function that recursively populates the select, tables and where (in
@@ -1228,7 +1259,7 @@ def function_get_sql_clause(opts, **kwargs):
1228 1259
         _fill_table_cache(opts, select, tables, where, opts.db_table, [opts.db_table])
1229 1260
 
1230 1261
     # Add any additional SELECTs passed in via kwargs.
1231  
-    if kwargs.get('select', False):
  1262
+    if kwargs.get('select'):
1232 1263
         select.extend(['(%s) AS %s' % (s[1], s[0]) for s in kwargs['select']])
1233 1264
 
1234 1265
     # ORDER BY clause
20  tests/testapp/models/lookup.py
@@ -58,6 +58,26 @@ def __repr__(self):
58 58
 >>> articles.get_in_bulk([1000])
59 59
 {}
60 60
 
  61
+# get_values() is just like get_list(), except it returns a list of
  62
+# dictionaries instead of object instances -- and you can specify which fields
  63
+# you want to retrieve.
  64
+>>> articles.get_values(fields=['headline'])
  65
+[{'headline': 'Article 4'}, {'headline': 'Article 2'}, {'headline': 'Article 3'}, {'headline': 'Article 1'}]
  66
+>>> articles.get_values(pub_date__exact=datetime(2005, 7, 27), fields=['id'])
  67
+[{'id': 2}, {'id': 3}]
  68
+>>> articles.get_values(fields=['id', 'headline']) == [{'id': 4, 'headline': 'Article 4'}, {'id': 2, 'headline': 'Article 2'}, {'id': 3, 'headline': 'Article 3'}, {'id': 1, 'headline': 'Article 1'}]
  69
+True
  70
+
  71
+# get_values_iterator() is just like get_values(), but it's a generator.
  72
+>>> for d in articles.get_values_iterator(fields=['id', 'headline']):
  73
+...     i = d.items()
  74
+...     i.sort()
  75
+...     i
  76
+[('headline', 'Article 4'), ('id', 4)]
  77
+[('headline', 'Article 2'), ('id', 2)]
  78
+[('headline', 'Article 3'), ('id', 3)]
  79
+[('headline', 'Article 1'), ('id', 1)]
  80
+
61 81
 # Every DateField and DateTimeField creates get_next_by_FOO() and
62 82
 # get_previous_by_FOO() methods.
63 83
 >>> a3.get_next_by_pub_date()

0 notes on commit 1a8fc57

Please sign in to comment.
Something went wrong with that request. Please try again.