models.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. # coding: utf-8
  2. from django.db import models
  3. try:
  4. sorted
  5. except NameError:
  6. from django.utils.itercompat import sorted # For Python 2.3
  7. class Author(models.Model):
  8. name = models.CharField(max_length=100)
  9. age = models.IntegerField()
  10. friends = models.ManyToManyField('self', blank=True)
  11. def __unicode__(self):
  12. return self.name
  13. class Publisher(models.Model):
  14. name = models.CharField(max_length=300)
  15. num_awards = models.IntegerField()
  16. def __unicode__(self):
  17. return self.name
  18. class Book(models.Model):
  19. isbn = models.CharField(max_length=9)
  20. name = models.CharField(max_length=300)
  21. pages = models.IntegerField()
  22. rating = models.FloatField()
  23. price = models.DecimalField(decimal_places=2, max_digits=6)
  24. authors = models.ManyToManyField(Author)
  25. contact = models.ForeignKey(Author, related_name='book_contact_set')
  26. publisher = models.ForeignKey(Publisher)
  27. pubdate = models.DateField()
  28. def __unicode__(self):
  29. return self.name
  30. class Store(models.Model):
  31. name = models.CharField(max_length=300)
  32. books = models.ManyToManyField(Book)
  33. original_opening = models.DateTimeField()
  34. friday_night_closing = models.TimeField()
  35. def __unicode__(self):
  36. return self.name
  37. class Entries(models.Model):
  38. EntryID = models.AutoField(primary_key=True, db_column='Entry ID')
  39. Entry = models.CharField(unique=True, max_length=50)
  40. Exclude = models.BooleanField()
  41. class Clues(models.Model):
  42. ID = models.AutoField(primary_key=True)
  43. EntryID = models.ForeignKey(Entries, verbose_name='Entry', db_column = 'Entry ID')
  44. Clue = models.CharField(max_length=150)
  45. # Tests on 'aggergate'
  46. # Different backends and numbers.
  47. __test__ = {'API_TESTS': """
  48. >>> from django.core import management
  49. >>> try:
  50. ... from decimal import Decimal
  51. ... except:
  52. ... from django.utils._decimal import Decimal
  53. >>> from datetime import date
  54. # Reset the database representation of this app.
  55. # This will return the database to a clean initial state.
  56. >>> management.call_command('flush', verbosity=0, interactive=False)
  57. # Empty Call - request nothing, get nothing.
  58. >>> Author.objects.all().aggregate()
  59. {}
  60. >>> from django.db.models import Avg, Sum, Count, Max, Min
  61. # Single model aggregation
  62. #
  63. # Single aggregate
  64. # Average age of Authors
  65. >>> Author.objects.all().aggregate(Avg('age'))
  66. {'age__avg': 37.4...}
  67. # Multiple aggregates
  68. # Average and Sum of Author ages
  69. >>> Author.objects.all().aggregate(Sum('age'), Avg('age'))
  70. {'age__sum': 337, 'age__avg': 37.4...}
  71. # Aggreates interact with filters, and only
  72. # generate aggregate values for the filtered values
  73. # Sum of the age of those older than 29 years old
  74. >>> Author.objects.all().filter(age__gt=29).aggregate(Sum('age'))
  75. {'age__sum': 254}
  76. # Depth-1 Joins
  77. #
  78. # On Relationships with self
  79. # Average age of the friends of each author
  80. >>> Author.objects.all().aggregate(Avg('friends__age'))
  81. {'friends__age__avg': 34.07...}
  82. # On ManyToMany Relationships
  83. #
  84. # Forward
  85. # Average age of the Authors of Books with a rating of less than 4.5
  86. >>> Book.objects.all().filter(rating__lt=4.5).aggregate(Avg('authors__age'))
  87. {'authors__age__avg': 38.2...}
  88. # Backward
  89. # Average rating of the Books whose Author's name contains the letter 'a'
  90. >>> Author.objects.all().filter(name__contains='a').aggregate(Avg('book__rating'))
  91. {'book__rating__avg': 4.0}
  92. # On OneToMany Relationships
  93. #
  94. # Forward
  95. # Sum of the number of awards of each Book's Publisher
  96. >>> Book.objects.all().aggregate(Sum('publisher__num_awards'))
  97. {'publisher__num_awards__sum': 30}
  98. # Backward
  99. # Sum of the price of every Book that has a Publisher
  100. >>> Publisher.objects.all().aggregate(Sum('book__price'))
  101. {'book__price__sum': Decimal("270.27")}
  102. # Multiple Joins
  103. #
  104. # Forward
  105. >>> Store.objects.all().aggregate(Max('books__authors__age'))
  106. {'books__authors__age__max': 57}
  107. # Backward
  108. # Note that the very long default alias may be truncated
  109. >>> Author.objects.all().aggregate(Min('book__publisher__num_awards'))
  110. {'book__publisher__num_award...': 1}
  111. # Aggregate outputs can also be aliased.
  112. # Average amazon.com Book rating
  113. >>> Store.objects.filter(name='Amazon.com').aggregate(amazon_mean=Avg('books__rating'))
  114. {'amazon_mean': 4.08...}
  115. # Tests on annotate()
  116. # An empty annotate call does nothing but return the same QuerySet
  117. >>> Book.objects.all().annotate().order_by('pk')
  118. [<Book: The Definitive Guide to Django: Web Development Done Right>, <Book: Sams Teach Yourself Django in 24 Hours>, <Book: Practical Django Projects>, <Book: Python Web Development with Django>, <Book: Artificial Intelligence: A Modern Approach>, <Book: Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp>]
  119. # Annotate inserts the alias into the model object with the aggregated result
  120. >>> books = Book.objects.all().annotate(mean_age=Avg('authors__age'))
  121. >>> books.get(pk=1).name
  122. u'The Definitive Guide to Django: Web Development Done Right'
  123. >>> books.get(pk=1).mean_age
  124. 34.5
  125. # On ManyToMany Relationships
  126. # Forward
  127. # Average age of the Authors of each book with a rating less than 4.5
  128. >>> books = Book.objects.all().filter(rating__lt=4.5).annotate(Avg('authors__age'))
  129. >>> sorted([(b.name, b.authors__age__avg) for b in books])
  130. [(u'Artificial Intelligence: A Modern Approach', 51.5), (u'Practical Django Projects', 29.0), (u'Python Web Development with Django', 30.3...), (u'Sams Teach Yourself Django in 24 Hours', 45.0)]
  131. # Count the number of authors of each book
  132. >>> books = Book.objects.annotate(num_authors=Count('authors'))
  133. >>> sorted([(b.name, b.num_authors) for b in books])
  134. [(u'Artificial Intelligence: A Modern Approach', 2), (u'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp', 1), (u'Practical Django Projects', 1), (u'Python Web Development with Django', 3), (u'Sams Teach Yourself Django in 24 Hours', 1), (u'The Definitive Guide to Django: Web Development Done Right', 2)]
  135. # Backward
  136. # Average rating of the Books whose Author's names contains the letter 'a'
  137. >>> authors = Author.objects.all().filter(name__contains='a').annotate(Avg('book__rating'))
  138. >>> sorted([(a.name, a.book__rating__avg) for a in authors])
  139. [(u'Adrian Holovaty', 4.5), (u'Brad Dayley', 3.0), (u'Jacob Kaplan-Moss', 4.5), (u'James Bennett', 4.0), (u'Paul Bissex', 4.0), (u'Stuart Russell', 4.0)]
  140. # Count the number of books written by each author
  141. >>> authors = Author.objects.annotate(num_books=Count('book'))
  142. >>> sorted([(a.name, a.num_books) for a in authors])
  143. [(u'Adrian Holovaty', 1), (u'Brad Dayley', 1), (u'Jacob Kaplan-Moss', 1), (u'James Bennett', 1), (u'Jeffrey Forcier', 1), (u'Paul Bissex', 1), (u'Peter Norvig', 2), (u'Stuart Russell', 1), (u'Wesley J. Chun', 1)]
  144. # On OneToMany Relationships
  145. # Forward
  146. # Annotate each book with the number of awards of each Book's Publisher
  147. >>> books = Book.objects.all().annotate(Sum('publisher__num_awards'))
  148. >>> sorted([(b.name, b.publisher__num_awards__sum) for b in books])
  149. [(u'Artificial Intelligence: A Modern Approach', 7), (u'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp', 9), (u'Practical Django Projects', 3), (u'Python Web Development with Django', 7), (u'Sams Teach Yourself Django in 24 Hours', 1), (u'The Definitive Guide to Django: Web Development Done Right', 3)]
  150. # Backward
  151. # Annotate each publisher with the sum of the price of all books sold
  152. >>> publishers = Publisher.objects.all().annotate(Sum('book__price'))
  153. >>> sorted([(p.name, p.book__price__sum) for p in publishers])
  154. [(u'Apress', Decimal("59.69")), (u"Jonno's House of Books", None), (u'Morgan Kaufmann', Decimal("75.00")), (u'Prentice Hall', Decimal("112.49")), (u'Sams', Decimal("23.09"))]
  155. # Calls to values() are not commutative over annotate().
  156. # Calling values on a queryset that has annotations returns the output
  157. # as a dictionary
  158. >>> Book.objects.filter(pk=1).annotate(mean_age=Avg('authors__age')).values()
  159. [{'rating': 4.5, 'isbn': u'159059725', 'name': u'The Definitive Guide to Django: Web Development Done Right', 'pubdate': datetime.date(2007, 12, 6), 'price': Decimal("30..."), 'contact_id': 1, 'id': 1, 'publisher_id': 1, 'pages': 447, 'mean_age': 34.5}]
  160. >>> Book.objects.filter(pk=1).annotate(mean_age=Avg('authors__age')).values('pk', 'isbn', 'mean_age')
  161. [{'pk': 1, 'isbn': u'159059725', 'mean_age': 34.5}]
  162. # Calling values() with parameters reduces the output
  163. >>> Book.objects.filter(pk=1).annotate(mean_age=Avg('authors__age')).values('name')
  164. [{'name': u'The Definitive Guide to Django: Web Development Done Right'}]
  165. # An empty values() call before annotating has the same effect as an
  166. # empty values() call after annotating
  167. >>> Book.objects.filter(pk=1).values().annotate(mean_age=Avg('authors__age'))
  168. [{'rating': 4.5, 'isbn': u'159059725', 'name': u'The Definitive Guide to Django: Web Development Done Right', 'pubdate': datetime.date(2007, 12, 6), 'price': Decimal("30..."), 'contact_id': 1, 'id': 1, 'publisher_id': 1, 'pages': 447, 'mean_age': 34.5}]
  169. # Calling annotate() on a ValuesQuerySet annotates over the groups of
  170. # fields to be selected by the ValuesQuerySet.
  171. # Note that an extra parameter is added to each dictionary. This
  172. # parameter is a queryset representing the objects that have been
  173. # grouped to generate the annotation
  174. >>> Book.objects.all().values('rating').annotate(n_authors=Count('authors__id'), mean_age=Avg('authors__age')).order_by('rating')
  175. [{'rating': 3.0, 'n_authors': 1, 'mean_age': 45.0}, {'rating': 4.0, 'n_authors': 6, 'mean_age': 37.1...}, {'rating': 4.5, 'n_authors': 2, 'mean_age': 34.5}, {'rating': 5.0, 'n_authors': 1, 'mean_age': 57.0}]
  176. # If a join doesn't match any objects, an aggregate returns None
  177. >>> authors = Author.objects.all().annotate(Avg('friends__age')).order_by('id')
  178. >>> len(authors)
  179. 9
  180. >>> sorted([(a.name, a.friends__age__avg) for a in authors])
  181. [(u'Adrian Holovaty', 32.0), (u'Brad Dayley', None), (u'Jacob Kaplan-Moss', 29.5), (u'James Bennett', 34.0), (u'Jeffrey Forcier', 27.0), (u'Paul Bissex', 31.0), (u'Peter Norvig', 46.0), (u'Stuart Russell', 57.0), (u'Wesley J. Chun', 33.6...)]
  182. # The Count aggregation function allows an extra parameter: distinct.
  183. # This restricts the count results to unique items
  184. >>> Book.objects.all().aggregate(Count('rating'))
  185. {'rating__count': 6}
  186. >>> Book.objects.all().aggregate(Count('rating', distinct=True))
  187. {'rating__count': 4}
  188. # Retreiving the grouped objects
  189. # When using Count you can also omit the primary key and refer only to
  190. # the related field name if you want to count all the related objects
  191. # and not a specific column
  192. >>> explicit = list(Author.objects.annotate(Count('book__id')))
  193. >>> implicit = list(Author.objects.annotate(Count('book')))
  194. >>> explicit == implicit
  195. True
  196. # Ordering is allowed on aggregates
  197. >>> Book.objects.values('rating').annotate(oldest=Max('authors__age')).order_by('oldest', 'rating')
  198. [{'rating': 4.5, 'oldest': 35}, {'rating': 3.0, 'oldest': 45}, {'rating': 4.0, 'oldest': 57}, {'rating': 5.0, 'oldest': 57}]
  199. >>> Book.objects.values('rating').annotate(oldest=Max('authors__age')).order_by('-oldest', '-rating')
  200. [{'rating': 5.0, 'oldest': 57}, {'rating': 4.0, 'oldest': 57}, {'rating': 3.0, 'oldest': 45}, {'rating': 4.5, 'oldest': 35}]
  201. # It is possible to aggregate over anotated values
  202. >>> Book.objects.all().annotate(num_authors=Count('authors__id')).aggregate(Avg('num_authors'))
  203. {'num_authors__avg': 1.66...}
  204. # You can filter the results based on the aggregation alias.
  205. # Lets add a publisher to test the different possibilities for filtering
  206. >>> p = Publisher(name='Expensive Publisher', num_awards=0)
  207. >>> p.save()
  208. >>> Book(name='ExpensiveBook1', pages=1, isbn='111', rating=3.5, price=Decimal("1000"), publisher=p, contact_id=1, pubdate=date(2008,12,1)).save()
  209. >>> Book(name='ExpensiveBook2', pages=1, isbn='222', rating=4.0, price=Decimal("1000"), publisher=p, contact_id=1, pubdate=date(2008,12,2)).save()
  210. >>> Book(name='ExpensiveBook3', pages=1, isbn='333', rating=4.5, price=Decimal("35"), publisher=p, contact_id=1, pubdate=date(2008,12,3)).save()
  211. # Publishers that have:
  212. # (i) more than one book
  213. >>> Publisher.objects.annotate(num_books=Count('book__id')).filter(num_books__gt=1).order_by('pk')
  214. [<Publisher: Apress>, <Publisher: Prentice Hall>, <Publisher: Expensive Publisher>]
  215. # (ii) a book that cost less than 40
  216. >>> Publisher.objects.filter(book__price__lt=Decimal("40.0")).order_by('pk')
  217. [<Publisher: Apress>, <Publisher: Apress>, <Publisher: Sams>, <Publisher: Prentice Hall>, <Publisher: Expensive Publisher>]
  218. # (iii) more than one book and (at least) a book that cost less than 40
  219. >>> Publisher.objects.annotate(num_books=Count('book__id')).filter(num_books__gt=1, book__price__lt=Decimal("40.0")).order_by('pk')
  220. [<Publisher: Apress>, <Publisher: Prentice Hall>, <Publisher: Expensive Publisher>]
  221. # (iv) more than one book that costs less than $40
  222. >>> Publisher.objects.filter(book__price__lt=Decimal("40.0")).annotate(num_books=Count('book__id')).filter(num_books__gt=1).order_by('pk')
  223. [<Publisher: Apress>]
  224. # Now a bit of testing on the different lookup types
  225. #
  226. >>> Publisher.objects.annotate(num_books=Count('book')).filter(num_books__range=[1, 3]).order_by('pk')
  227. [<Publisher: Apress>, <Publisher: Sams>, <Publisher: Prentice Hall>, <Publisher: Morgan Kaufmann>, <Publisher: Expensive Publisher>]
  228. >>> Publisher.objects.annotate(num_books=Count('book')).filter(num_books__range=[1, 2]).order_by('pk')
  229. [<Publisher: Apress>, <Publisher: Sams>, <Publisher: Prentice Hall>, <Publisher: Morgan Kaufmann>]
  230. >>> Publisher.objects.annotate(num_books=Count('book')).filter(num_books__in=[1, 3]).order_by('pk')
  231. [<Publisher: Sams>, <Publisher: Morgan Kaufmann>, <Publisher: Expensive Publisher>]
  232. >>> Publisher.objects.annotate(num_books=Count('book')).filter(num_books__isnull=True)
  233. []
  234. >>> p.delete()
  235. # Does Author X have any friends? (or better, how many friends does author X have)
  236. >> Author.objects.filter(pk=1).aggregate(Count('friends__id'))
  237. {'friends__id__count': 2.0}
  238. # Give me a list of all Books with more than 1 authors
  239. >>> Book.objects.all().annotate(num_authors=Count('authors__name')).filter(num_authors__ge=2).order_by('pk')
  240. [<Book: The Definitive Guide to Django: Web Development Done Right>, <Book: Artificial Intelligence: A Modern Approach>]
  241. # Give me a list of all Authors that have no friends
  242. >>> Author.objects.all().annotate(num_friends=Count('friends__id', distinct=True)).filter(num_friends=0).order_by('pk')
  243. [<Author: Brad Dayley>]
  244. # Give me a list of all publishers that have published more than 1 books
  245. >>> Publisher.objects.all().annotate(num_books=Count('book__id')).filter(num_books__gt=1).order_by('pk')
  246. [<Publisher: Apress>, <Publisher: Prentice Hall>]
  247. # Give me a list of all publishers that have published more than 1 books that cost less than 40
  248. >>> Publisher.objects.all().filter(book__price__lt=Decimal("40.0")).annotate(num_books=Count('book__id')).filter(num_books__gt=1)
  249. [<Publisher: Apress>]
  250. # Give me a list of all Books that were written by X and one other author.
  251. >>> Book.objects.all().annotate(num_authors=Count('authors__id')).filter(authors__name__contains='Norvig', num_authors__gt=1)
  252. [<Book: Artificial Intelligence: A Modern Approach>]
  253. # Give me the average rating of all Books that were written by X and one other author.
  254. #(Aggregate over objects discovered using membership of the m2m set)
  255. # Adding an existing author to another book to test it the right way
  256. >>> a = Author.objects.get(name__contains='Norvig')
  257. >>> b = Book.objects.get(name__contains='Done Right')
  258. >>> b.authors.add(a)
  259. >>> b.save()
  260. # This should do it
  261. >>> Book.objects.all().annotate(num_authors=Count('authors__id')).filter(authors__name__contains='Norvig', num_authors__gt=1).aggregate(Avg('rating'))
  262. {'rating__avg': 4.25}
  263. >>> b.authors.remove(a)
  264. # Give me a list of all Authors that have published a book with at least one other person
  265. # (Filters over a count generated on a related object)
  266. #
  267. # Cheating: [a for a in Author.objects.all().annotate(num_coleagues=Count('book__authors__id'), num_books=Count('book__id', distinct=True)) if a.num_coleagues - a.num_books > 0]
  268. # F-Syntax is required. Will be fixed after F objects are available
  269. # Tests on fields with non-default table and column names.
  270. >>> Clues.objects.values('EntryID__Entry').annotate(Appearances=Count('EntryID'), Distinct_Clues=Count('Clue', distinct=True))
  271. []
  272. # Aggregates also work on dates, times and datetimes
  273. >>> Publisher.objects.annotate(earliest_book=Min('book__pubdate')).exclude(earliest_book=None).order_by('earliest_book').values()
  274. [{'earliest_book': datetime.date(1991, 10, 15), 'num_awards': 9, 'id': 4, 'name': u'Morgan Kaufmann'}, {'earliest_book': datetime.date(1995, 1, 15), 'num_awards': 7, 'id': 3, 'name': u'Prentice Hall'}, {'earliest_book': datetime.date(2007, 12, 6), 'num_awards': 3, 'id': 1, 'name': u'Apress'}, {'earliest_book': datetime.date(2008, 3, 3), 'num_awards': 1, 'id': 2, 'name': u'Sams'}]
  275. >>> Store.objects.aggregate(Max('friday_night_closing'), Min("original_opening"))
  276. {'friday_night_closing__max': datetime.time(23, 59, 59), 'original_opening__min': datetime.datetime(1945, 4, 25, 16, 24, 14)}
  277. # values_list() can also be used
  278. >>> Book.objects.filter(pk=1).annotate(mean_age=Avg('authors__age')).values_list('pk', 'isbn', 'mean_age')
  279. [(1, u'159059725', 34.5)]
  280. >>> Book.objects.filter(pk=1).annotate(mean_age=Avg('authors__age')).values_list('isbn')
  281. [(u'159059725',)]
  282. >>> Book.objects.filter(pk=1).annotate(mean_age=Avg('authors__age')).values_list('mean_age')
  283. [(34.5,)]
  284. >>> Book.objects.filter(pk=1).annotate(mean_age=Avg('authors__age')).values_list('mean_age', flat=True)
  285. [34.5]
  286. """}