Django

Code

Ticket #5020: models.py

File models.py, 2.0 kB (added by David Cramer <dcramer@gmail.com>, 1 year ago)

unit tests

Line 
1 from django.db import models
2
3 class Page(models.Model):
4     name = models.CharField(maxlength=100)
5
6 class Poll(models.Model):
7     question = models.CharField(maxlength=200)
8     page = models.ForeignKey(Page)
9
10     class Meta:
11         db_table = 'poll'
12
13 class Choice(models.Model):
14     poll = models.ForeignKey(Poll, related_name="choices")
15     choice = models.CharField(maxlength=200)
16
17     class Meta:
18         db_table = 'poll_choices'
19
20 __test__ = {'API_TESTS':"""
21 # Regression test for the use of .select_related() on querysets.
22 # Set up some initial models
23 >>> from django.db import connection
24 >>> s1 = Page.objects.create(name="Hi")
25 >>> p1 = Poll.objects.create(question='Why?', page=s1)
26 >>> p2 = Poll.objects.create(question='Why 2?', page=s1)
27 >>> p3 = Poll.objects.create(question='Why 3?', page=s1)
28 >>> p4 = Poll.objects.create(question='Why 4?', page=s1)
29 >>> c1 = Choice.objects.create(poll=p1, choice='Because.')
30 >>> c2 = Choice.objects.create(poll=p1, choice='Why Not?')
31 >>> c3 = Choice.objects.create(poll=p1, choice='Group by is useful.')
32
33 # select_related(depth=1) shouldn't cause us extra queries
34 >>> z = Choice.objects.all().select_related(depth=1).order_by('id')
35 >>> q = len(connection.queries)
36 >>> z[0].poll
37 <Poll: Poll object>
38 >>> len(connection.queries)-q
39 0
40
41 # select_related('poll') shouldn't cause us extra queries
42 >>> z = Choice.objects.all().select_related('poll').order_by('id')
43 >>> q = len(connection.queries)
44 >>> z[0].poll
45 <Poll: Poll object>
46 >>> len(connection.queries)-q
47 0
48
49 # select_related('poll__page') shouldn't cause us extra queries
50 >>> z = Choice.objects.all().select_related('poll__page').order_by('id')
51 >>> q = len(connection.queries)
52 >>> z[0].poll.page
53 <Page: Page object>
54 >>> len(connection.queries)-q
55 0
56
57 # verify it's joining on the right table
58 >>> Choice.objects.all().select_related('poll').order_by('id')[0:1].get().poll.question
59 'Why?'
60
61 # should raise FieldDoesNotExist exception
62 >>> Choice.objects.all().select_related('wtf').order_by('id')
63 Traceback (most recent call last):
64 ...
65 FieldDoesNotExist: Choice has no field named wtf
66 """}