1
0
mirror of https://github.com/django/django.git synced 2024-12-26 11:06:07 +00:00
django/tests/modeltests/reverse_lookup/models.py
Malcolm Tredinnick 953badbea5 Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.

Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702


git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 12:11:04 +00:00

60 lines
1.8 KiB
Python

"""
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)
def __unicode__(self):
return self.name
class Poll(models.Model):
question = models.CharField(maxlength=200)
creator = models.ForeignKey(User)
def __unicode__(self):
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")
def __unicode__(self):
return self.name
__test__ = {'API_TESTS':"""
>>> 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?")
<User: John Doe>
>>> User.objects.get(poll__question__exact="What's the second question?")
<User: Jim Bo>
>>> # Reverse lookups by related_name:
>>> Poll.objects.get(poll_choice__name__exact="This is the answer.")
<Poll: What's the first question?>
>>> Poll.objects.get(related_choice__name__exact="This is the answer.")
<Poll: What's the second question?>
>>> # 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):
...
TypeError: Cannot resolve keyword 'choice' into field. Choices are: poll_choice, related_choice, id, question, creator
"""}