| 1 | """
|
|---|
| 2 | 20. Reverse lookups
|
|---|
| 3 |
|
|---|
| 4 | This demonstrates the reverse lookup features of the database API.
|
|---|
| 5 | """
|
|---|
| 6 |
|
|---|
| 7 | from django.db import models
|
|---|
| 8 |
|
|---|
| 9 | class User(models.Model):
|
|---|
| 10 | name = models.CharField(maxlength=200)
|
|---|
| 11 | def __repr__(self):
|
|---|
| 12 | return self.name
|
|---|
| 13 |
|
|---|
| 14 | class Poll(models.Model):
|
|---|
| 15 | question = models.CharField(maxlength=200)
|
|---|
| 16 | creator = models.ForeignKey(User)
|
|---|
| 17 | def __repr__(self):
|
|---|
| 18 | return self.question
|
|---|
| 19 |
|
|---|
| 20 | class 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 |
|
|---|
| 27 | API_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?")
|
|---|
| 41 | John Doe
|
|---|
| 42 | >>> User.objects.get(poll__question__exact="What's the second question?")
|
|---|
| 43 | Jim Bo
|
|---|
| 44 |
|
|---|
| 45 | >>> # Reverse lookups by related_name:
|
|---|
| 46 | >>> Poll.objects.get(poll_choice__name__exact="This is the answer.")
|
|---|
| 47 | What's the first question?
|
|---|
| 48 | >>> Poll.objects.get(related_choice__name__exact="This is the answer.")
|
|---|
| 49 | What'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")
|
|---|
| 53 | Traceback (most recent call last):
|
|---|
| 54 | ...
|
|---|
| 55 | TypeError: Cannot resolve keyword 'choice' into field
|
|---|
| 56 | """
|
|---|