summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorAdrian Holovaty <adrian@holovaty.com>2012-01-13 21:57:30 +0000
committerAdrian Holovaty <adrian@holovaty.com>2012-01-13 21:57:30 +0000
commit64229eb3882be7080f73bc4559f44dc34507b140 (patch)
tree7bf84bde35c65231809c268e677458beecddf896 /docs
parent4c16e772308e525b9b35799e230a5499df80b47c (diff)
Started a 'Cheat sheet' section in aggregation docs because I desperately need this
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'docs')
-rw-r--r--docs/topics/db/aggregation.txt36
1 files changed, 36 insertions, 0 deletions
diff --git a/docs/topics/db/aggregation.txt b/docs/topics/db/aggregation.txt
index faf8fe32f0..3a4d287864 100644
--- a/docs/topics/db/aggregation.txt
+++ b/docs/topics/db/aggregation.txt
@@ -41,6 +41,42 @@ used to track the inventory for a series of online bookstores:
name = models.CharField(max_length=300)
books = models.ManyToManyField(Book)
+Cheat sheet
+===========
+
+In a hurry? Here's how to do common aggregate queries, assuming the models above::
+
+ # Total number of books.
+ >>> Book.objects.count()
+ 2452
+
+ # Total number of books with publisher=BaloneyPress
+ >>> Book.objects.filter(publisher__name='BaloneyPress').count()
+ 73
+
+ # Average price across all books.
+ >>> from django.db.models import Avg
+ >>> Book.objects.all().aggregate(Avg('price'))
+ {'price__avg': 34.35}
+
+ # Max price across all books.
+ >>> from django.db.models import Max
+ >>> Book.objects.all().aggregate(Max('price'))
+ {'price__max': Decimal('81.20')}
+
+ # Each publisher, each with a count of books as a "num_books" attribute.
+ >>> from django.db.models import Count
+ >>> pubs = Publisher.objects.annotate(num_books=Count('book'))
+ >>> pubs
+ [<Publisher BaloneyPress>, <Publisher SalamiPress>, ...]
+ >>> pubs[0].num_books
+ 73
+
+ # The top 5 publishers, in order by number of books.
+ >>> from django.db.models import Count
+ >>> pubs = Publisher.objects.annotate(num_books=Count('book')).order_by('-num_books')[:5]
+ >>> pubs[0].num_books
+ 1323
Generating aggregates over a QuerySet
=====================================