2006-05-02 09:31:56 +08:00
|
|
|
"""
|
|
|
|
25. Reverse lookups
|
|
|
|
|
|
|
|
This demonstrates the reverse lookup features of the database API.
|
|
|
|
"""
|
|
|
|
|
|
|
|
from django.db import models
|
|
|
|
|
|
|
|
class User(models.Model):
|
|
|
|
name = models.CharField(maxlength=200)
|
2006-06-04 08:23:51 +08:00
|
|
|
|
|
|
|
def __str__(self):
|
2006-05-02 09:31:56 +08:00
|
|
|
return self.name
|
|
|
|
|
|
|
|
class Poll(models.Model):
|
|
|
|
question = models.CharField(maxlength=200)
|
|
|
|
creator = models.ForeignKey(User)
|
2006-06-04 08:23:51 +08:00
|
|
|
|
|
|
|
def __str__(self):
|
2006-05-02 09:31:56 +08:00
|
|
|
return self.question
|
|
|
|
|
|
|
|
class Choice(models.Model):
|
|
|
|
name = models.CharField(maxlength=100)
|
|
|
|
poll = models.ForeignKey(Poll, related_name="poll_choice")
|
|
|
|
related_poll = models.ForeignKey(Poll, related_name="related_choice")
|
2006-06-04 08:23:51 +08:00
|
|
|
|
|
|
|
def __str(self):
|
2006-05-02 09:31:56 +08:00
|
|
|
return self.name
|
|
|
|
|
2006-08-27 21:59:47 +08:00
|
|
|
__test__ = {'API_TESTS':"""
|
2006-05-02 09:31:56 +08:00
|
|
|
>>> john = User(name="John Doe")
|
|
|
|
>>> john.save()
|
|
|
|
>>> jim = User(name="Jim Bo")
|
|
|
|
>>> jim.save()
|
|
|
|
>>> first_poll = Poll(question="What's the first question?", creator=john)
|
|
|
|
>>> first_poll.save()
|
|
|
|
>>> second_poll = Poll(question="What's the second question?", creator=jim)
|
|
|
|
>>> second_poll.save()
|
|
|
|
>>> new_choice = Choice(poll=first_poll, related_poll=second_poll, name="This is the answer.")
|
|
|
|
>>> new_choice.save()
|
|
|
|
|
|
|
|
>>> # Reverse lookups by field name:
|
|
|
|
>>> User.objects.get(poll__question__exact="What's the first question?")
|
2006-06-04 08:23:51 +08:00
|
|
|
<User: John Doe>
|
2006-05-02 09:31:56 +08:00
|
|
|
>>> User.objects.get(poll__question__exact="What's the second question?")
|
2006-06-04 08:23:51 +08:00
|
|
|
<User: Jim Bo>
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
>>> # Reverse lookups by related_name:
|
|
|
|
>>> Poll.objects.get(poll_choice__name__exact="This is the answer.")
|
2006-06-04 08:23:51 +08:00
|
|
|
<Poll: What's the first question?>
|
2006-05-02 09:31:56 +08:00
|
|
|
>>> Poll.objects.get(related_choice__name__exact="This is the answer.")
|
2006-06-04 08:23:51 +08:00
|
|
|
<Poll: What's the second question?>
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
>>> # If a related_name is given you can't use the field name instead:
|
|
|
|
>>> Poll.objects.get(choice__name__exact="This is the answer")
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
2007-05-01 11:21:54 +08:00
|
|
|
TypeError: Cannot resolve keyword 'choice' into field, choices are: poll_choice, related_choice, id, question, creator
|
2006-08-27 21:59:47 +08:00
|
|
|
"""}
|