Ticket #1305: reverse_lookup.unit_tests.py

File reverse_lookup.unit_tests.py, 1.7 KB (added by andreas@…, 13 years ago)

Reverse lookup unit tests

Line 
1"""
220. Reverse lookups
3
4This demonstrates the reverse lookup features of the database API.
5"""
6
7from django.db import models
8
9class User(models.Model):
10    name = models.CharField(maxlength=200)
11    def __repr__(self):
12        return self.name
13
14class Poll(models.Model):
15    question = models.CharField(maxlength=200)
16    creator = models.ForeignKey(User)
17    def __repr__(self):
18        return self.question
19
20class Choice(models.Model):
21    name = models.CharField(maxlength=100)
22    poll = models.ForeignKey(Poll, related_name="poll_choice")
23    related_poll = models.ForeignKey(Poll, related_name="related_choice")
24    def __repr(self):
25        return self.name
26
27API_TESTS = """
28>>> john = User(name="John Doe")
29>>> john.save()
30>>> jim = User(name="Jim Bo")
31>>> jim.save()
32>>> first_poll = Poll(question="What's the first question?", creator=john)
33>>> first_poll.save()
34>>> second_poll = Poll(question="What's the second question?", creator=jim)
35>>> second_poll.save()
36>>> new_choice = Choice(poll=first_poll, related_poll=second_poll, name="This is the answer.")
37>>> new_choice.save()
38
39>>> # Reverse lookups by field name:
40>>> User.objects.get(poll__question__exact="What's the first question?")
41John Doe
42>>> User.objects.get(poll__question__exact="What's the second question?")
43Jim Bo
44
45>>> # Reverse lookups by related_name:
46>>> Poll.objects.get(poll_choice__name__exact="This is the answer.")
47What's the first question?
48>>> Poll.objects.get(related_choice__name__exact="This is the answer.")
49What's the second question?
50
51>>> # If a related_name is given you can't use the field name instead:
52>>> Poll.objects.get(choice__name__exact="This is the answer")
53Traceback (most recent call last):
54    ...
55TypeError: Cannot resolve keyword 'choice' into field
56"""
Back to Top