~ubuntu-branches/ubuntu/quantal/python-django/quantal-security

« back to all changes in this revision

Viewing changes to tests/regressiontests/aggregation_regress/models.py

  • Committer: Bazaar Package Importer
  • Author(s): Chris Lamb
  • Date: 2010-05-21 07:52:55 UTC
  • mfrom: (1.3.6 upstream)
  • mto: This revision was merged to the branch mainline in revision 28.
  • Revision ID: james.westby@ubuntu.com-20100521075255-ii78v1dyfmyu3uzx
Tags: upstream-1.2
ImportĀ upstreamĀ versionĀ 1.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# coding: utf-8
2
2
import pickle
3
3
 
4
 
from django.db import connection, models
 
4
from django.db import connection, models, DEFAULT_DB_ALIAS
5
5
from django.conf import settings
6
6
 
7
 
try:
8
 
    sorted
9
 
except NameError:
10
 
    from django.utils.itercompat import sorted      # For Python 2.3
11
 
 
12
7
class Author(models.Model):
13
8
    name = models.CharField(max_length=100)
14
9
    age = models.IntegerField()
97
92
{'pages__sum': 3703}
98
93
 
99
94
# Annotations get combined with extra select clauses
100
 
>>> sorted(Book.objects.all().annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost' : 'price * .5'}).get(pk=2).__dict__.items())
 
95
>>> sorted((k,v) for k,v in Book.objects.all().annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost' : 'price * .5'}).get(pk=2).__dict__.items() if k != '_state')
101
96
[('contact_id', 3), ('id', 2), ('isbn', u'067232959'), ('manufacture_cost', ...11.545...), ('mean_auth_age', 45.0), ('name', u'Sams Teach Yourself Django in 24 Hours'), ('pages', 528), ('price', Decimal("23.09")), ('pubdate', datetime.date(2008, 3, 3)), ('publisher_id', 2), ('rating', 3.0)]
102
97
 
103
98
# Order of the annotate/extra in the query doesn't matter
104
 
>>> sorted(Book.objects.all().extra(select={'manufacture_cost' : 'price * .5'}).annotate(mean_auth_age=Avg('authors__age')).get(pk=2).__dict__.items())
 
99
>>> sorted((k,v) for k,v in Book.objects.all().extra(select={'manufacture_cost' : 'price * .5'}).annotate(mean_auth_age=Avg('authors__age')).get(pk=2).__dict__.items()if k != '_state')
105
100
[('contact_id', 3), ('id', 2), ('isbn', u'067232959'), ('manufacture_cost', ...11.545...), ('mean_auth_age', 45.0), ('name', u'Sams Teach Yourself Django in 24 Hours'), ('pages', 528), ('price', Decimal("23.09")), ('pubdate', datetime.date(2008, 3, 3)), ('publisher_id', 2), ('rating', 3.0)]
106
101
 
107
102
# Values queries can be combined with annotate and extra
108
 
>>> sorted(Book.objects.all().annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost' : 'price * .5'}).values().get(pk=2).items())
 
103
>>> sorted((k,v) for k,v in Book.objects.all().annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost' : 'price * .5'}).values().get(pk=2).items()if k != '_state')
109
104
[('contact_id', 3), ('id', 2), ('isbn', u'067232959'), ('manufacture_cost', ...11.545...), ('mean_auth_age', 45.0), ('name', u'Sams Teach Yourself Django in 24 Hours'), ('pages', 528), ('price', Decimal("23.09")), ('pubdate', datetime.date(2008, 3, 3)), ('publisher_id', 2), ('rating', 3.0)]
110
105
 
111
106
# The order of the (empty) values, annotate and extra clauses doesn't matter
112
 
>>> sorted(Book.objects.all().values().annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost' : 'price * .5'}).get(pk=2).items())
 
107
>>> sorted((k,v) for k,v in Book.objects.all().values().annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost' : 'price * .5'}).get(pk=2).items()if k != '_state')
113
108
[('contact_id', 3), ('id', 2), ('isbn', u'067232959'), ('manufacture_cost', ...11.545...), ('mean_auth_age', 45.0), ('name', u'Sams Teach Yourself Django in 24 Hours'), ('pages', 528), ('price', Decimal("23.09")), ('pubdate', datetime.date(2008, 3, 3)), ('publisher_id', 2), ('rating', 3.0)]
114
109
 
115
110
# If the annotation precedes the values clause, it won't be included
174
169
{'number': 1132, 'select': 1132}
175
170
 
176
171
# Regression for #10064: select_related() plays nice with aggregates
177
 
>>> Book.objects.select_related('publisher').annotate(num_authors=Count('authors')).values()[0]
178
 
{'rating': 4.0, 'isbn': u'013790395', 'name': u'Artificial Intelligence: A Modern Approach', 'pubdate': datetime.date(1995, 1, 15), 'price': Decimal("82.8..."), 'contact_id': 8, 'id': 5, 'num_authors': 2, 'publisher_id': 3, 'pages': 1132}
 
172
>>> sorted(Book.objects.select_related('publisher').annotate(num_authors=Count('authors')).values()[0].iteritems())
 
173
[('contact_id', 8), ('id', 5), ('isbn', u'013790395'), ('name', u'Artificial Intelligence: A Modern Approach'), ('num_authors', 2), ('pages', 1132), ('price', Decimal("82.8...")), ('pubdate', datetime.date(1995, 1, 15)), ('publisher_id', 3), ('rating', 4.0)]
179
174
 
180
175
# Regression for #10010: exclude on an aggregate field is correctly negated
181
176
>>> len(Book.objects.annotate(num_authors=Count('authors')))
219
214
>>> Book.objects.filter(id__in=[]).aggregate(num_authors=Count('authors'), avg_authors=Avg('authors'), max_authors=Max('authors'), max_price=Max('price'), max_rating=Max('rating'))
220
215
{'max_authors': None, 'max_rating': None, 'num_authors': 0, 'avg_authors': None, 'max_price': None}
221
216
 
222
 
>>> Publisher.objects.filter(pk=5).annotate(num_authors=Count('book__authors'), avg_authors=Avg('book__authors'), max_authors=Max('book__authors'), max_price=Max('book__price'), max_rating=Max('book__rating')).values()
223
 
[{'max_authors': None, 'name': u"Jonno's House of Books", 'num_awards': 0, 'max_price': None, 'num_authors': 0, 'max_rating': None, 'id': 5, 'avg_authors': None}]
 
217
>>> list(Publisher.objects.filter(pk=5).annotate(num_authors=Count('book__authors'), avg_authors=Avg('book__authors'), max_authors=Max('book__authors'), max_price=Max('book__price'), max_rating=Max('book__rating')).values()) == [{'max_authors': None, 'name': u"Jonno's House of Books", 'num_awards': 0, 'max_price': None, 'num_authors': 0, 'max_rating': None, 'id': 5, 'avg_authors': None}]
 
218
True
224
219
 
225
220
# Regression for #10113 - Fields mentioned in order_by() must be included in the GROUP BY.
226
221
# This only becomes a problem when the order_by introduces a new join.
250
245
>>> out = pickle.dumps(qs)
251
246
 
252
247
# Then check that the round trip works.
253
 
>>> query = qs.query.as_sql()[0]
 
248
>>> query = qs.query.get_compiler(qs.db).as_sql()[0]
254
249
>>> select_fields = qs.query.select_fields
255
250
>>> query2 = pickle.loads(pickle.dumps(qs))
256
 
>>> query2.query.as_sql()[0] == query
 
251
>>> query2.query.get_compiler(query2.db).as_sql()[0] == query
257
252
True
258
253
>>> query2.query.select_fields = select_fields
259
254
 
327
322
    Stddev and Variance are not guaranteed to be available for SQLite, and
328
323
    are not available for PostgreSQL before 8.2.
329
324
    """
330
 
    if settings.DATABASE_ENGINE == 'sqlite3':
 
325
    if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.sqlite3':
331
326
        return False
332
327
 
333
328
    class StdDevPop(object):
380
375
>>> Book.objects.aggregate(Variance('price', sample=True))
381
376
{'price__variance': 700.53...}
382
377
 
383
 
 
384
378
"""