thirdparty/google_appengine/lib/django/tests/modeltests/reverse_lookup/models.py
changeset 2866 a04b1e4126c4
parent 2864 2e0b0af889be
child 2868 9f7f269383f7
equal deleted inserted replaced
2864:2e0b0af889be 2866:a04b1e4126c4
     1 """
       
     2 25. 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 
       
    12     def __str__(self):
       
    13         return self.name
       
    14 
       
    15 class Poll(models.Model):
       
    16     question = models.CharField(maxlength=200)
       
    17     creator = models.ForeignKey(User)
       
    18 
       
    19     def __str__(self):
       
    20         return self.question
       
    21 
       
    22 class Choice(models.Model):
       
    23     name = models.CharField(maxlength=100)
       
    24     poll = models.ForeignKey(Poll, related_name="poll_choice")
       
    25     related_poll = models.ForeignKey(Poll, related_name="related_choice")
       
    26 
       
    27     def __str(self):
       
    28         return self.name
       
    29 
       
    30 __test__ = {'API_TESTS':"""
       
    31 >>> john = User(name="John Doe")
       
    32 >>> john.save()
       
    33 >>> jim = User(name="Jim Bo")
       
    34 >>> jim.save()
       
    35 >>> first_poll = Poll(question="What's the first question?", creator=john)
       
    36 >>> first_poll.save()
       
    37 >>> second_poll = Poll(question="What's the second question?", creator=jim)
       
    38 >>> second_poll.save()
       
    39 >>> new_choice = Choice(poll=first_poll, related_poll=second_poll, name="This is the answer.")
       
    40 >>> new_choice.save()
       
    41 
       
    42 >>> # Reverse lookups by field name:
       
    43 >>> User.objects.get(poll__question__exact="What's the first question?")
       
    44 <User: John Doe>
       
    45 >>> User.objects.get(poll__question__exact="What's the second question?")
       
    46 <User: Jim Bo>
       
    47 
       
    48 >>> # Reverse lookups by related_name:
       
    49 >>> Poll.objects.get(poll_choice__name__exact="This is the answer.")
       
    50 <Poll: What's the first question?>
       
    51 >>> Poll.objects.get(related_choice__name__exact="This is the answer.")
       
    52 <Poll: What's the second question?>
       
    53 
       
    54 >>> # If a related_name is given you can't use the field name instead:
       
    55 >>> Poll.objects.get(choice__name__exact="This is the answer")
       
    56 Traceback (most recent call last):
       
    57     ...
       
    58 TypeError: Cannot resolve keyword 'choice' into field
       
    59 """}