Commits

Anonymous committed 3db10d8

Started a 'Cheat sheet' section in aggregation docs because I desperately need this

Comments (0)

Files changed (1)

docs/topics/db/aggregation.txt

        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
 =====================================
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.