1 | """
|
---|
2 | XXX. Adding .sum( field ) to models
|
---|
3 |
|
---|
4 | Creates a SELECT SUM( fieldname ) ... query
|
---|
5 | """
|
---|
6 |
|
---|
7 | from django.db import models
|
---|
8 |
|
---|
9 | class Article(models.Model):
|
---|
10 | headline = models.CharField(maxlength=100)
|
---|
11 | pub_date = models.DateTimeField()
|
---|
12 | views = models.IntegerField()
|
---|
13 |
|
---|
14 | def __str__(self):
|
---|
15 | return self.headline
|
---|
16 |
|
---|
17 | API_TESTS = """
|
---|
18 | # Create a few articles.
|
---|
19 | >>> from datetime import datetime
|
---|
20 | >>> a = Article(headline='Area man programs in Python', pub_date=datetime(2005, 7, 28), views=77)
|
---|
21 | >>> a.save()
|
---|
22 |
|
---|
23 | >>> a = Article(headline='Django 0.95 Released', pub_date=datetime(2006, 8, 04), views=223)
|
---|
24 | >>> a.save()
|
---|
25 |
|
---|
26 | >>> a = Article(headline='Django accepted as framework of choice', pub_date=datetime(2006, 8, 04), views=700)
|
---|
27 | >>> a.save()
|
---|
28 |
|
---|
29 | >>> sum = Article.objects.all().sum( 'views' )
|
---|
30 | >>> sum == 1000
|
---|
31 | True
|
---|
32 |
|
---|
33 | >>> sum = Article.objects.all().filter( pk=1 ).sum( 'views' )
|
---|
34 | >>> sum == 77
|
---|
35 | True
|
---|
36 |
|
---|
37 | >> sum = Article.objects.all().filter( pub_date__year=2006 ).sum( 'views' )
|
---|
38 | >> sum == 923
|
---|
39 | True
|
---|
40 |
|
---|
41 | >> sum = Article.objects.all().filter( pub_date__year=2006 ).sum( 'views' )
|
---|
42 | >> sum == 1123923
|
---|
43 | False
|
---|
44 | """
|
---|