1 | from django.db import models
|
---|
2 |
|
---|
3 | class Poll(models.Model):
|
---|
4 | question = models.CharField(maxlength=200)
|
---|
5 |
|
---|
6 | def __str__(self):
|
---|
7 | return "Q: %s " % self.question
|
---|
8 |
|
---|
9 | class Meta:
|
---|
10 | db_table = 'poll'
|
---|
11 |
|
---|
12 | class Choice(models.Model):
|
---|
13 | poll = models.ForeignKey(Poll, related_name="choices")
|
---|
14 | choice = models.CharField(maxlength=200)
|
---|
15 |
|
---|
16 | def __str__(self):
|
---|
17 | return "Choice: %s in poll %s" % (self.choice, self.poll)
|
---|
18 |
|
---|
19 | class Meta:
|
---|
20 | db_table = 'poll_choices'
|
---|
21 |
|
---|
22 | __test__ = {'API_TESTS':"""
|
---|
23 | # Regression test for the use of .group_by() on querysets.
|
---|
24 | # Set up some initial polls and choices
|
---|
25 | >>> p1 = Poll(question='Why?')
|
---|
26 | >>> p1.save()
|
---|
27 | >>> c1 = Choice(poll=p1, choice='Because.')
|
---|
28 | >>> c1.save()
|
---|
29 | >>> c2 = Choice(poll=p1, choice='Why Not?')
|
---|
30 | >>> c2.save()
|
---|
31 | >>> c3 = Choice(poll=p1, choice='Group by is useful.')
|
---|
32 | >>> c3.save()
|
---|
33 |
|
---|
34 | # GROUP BY on poll_id should return 1 result
|
---|
35 | >>> Choice.objects.all().group_by('poll').count()
|
---|
36 | 1
|
---|
37 |
|
---|
38 | # .group_by() does not support DESC (only MySQL does) so it fails
|
---|
39 | # because -poll is an invalid column name
|
---|
40 | >>> Choice.objects.all().group_by('-poll')
|
---|
41 | Traceback (most recent call last):
|
---|
42 | ...
|
---|
43 | OperationalError: no such column: poll_choices.-poll
|
---|
44 |
|
---|
45 | # GROUP BY on poll_id with a COUNT() should return the number of choices
|
---|
46 | >>> Poll.objects.all().extra(select={'choice_count': 'COUNT(`poll_choices`.`id`)'}, tables=['`poll_choices`'], where=['`poll_choices`.`poll_id` = `poll`.`id`']).group_by('id').get().choice_count
|
---|
47 | 3
|
---|
48 | """}
|
---|
49 |
|
---|