parts/django/tests/modeltests/reverse_lookup/tests.py
changeset 69 c6bca38c1cbf
equal deleted inserted replaced
68:5ff1fc726848 69:c6bca38c1cbf
       
     1 from django.test import TestCase
       
     2 from django.core.exceptions import FieldError
       
     3 
       
     4 from models import User, Poll, Choice
       
     5 
       
     6 class ReverseLookupTests(TestCase):
       
     7 
       
     8     def setUp(self):
       
     9         john = User.objects.create(name="John Doe")
       
    10         jim = User.objects.create(name="Jim Bo")
       
    11         first_poll = Poll.objects.create(
       
    12             question="What's the first question?",
       
    13             creator=john
       
    14         )
       
    15         second_poll = Poll.objects.create(
       
    16             question="What's the second question?",
       
    17             creator=jim
       
    18         )
       
    19         new_choice = Choice.objects.create(
       
    20             poll=first_poll,
       
    21             related_poll=second_poll,
       
    22             name="This is the answer."
       
    23         )
       
    24 
       
    25     def test_reverse_by_field(self):
       
    26         u1 = User.objects.get(
       
    27             poll__question__exact="What's the first question?"
       
    28         )
       
    29         self.assertEqual(u1.name, "John Doe")
       
    30 
       
    31         u2 = User.objects.get(
       
    32             poll__question__exact="What's the second question?"
       
    33         )
       
    34         self.assertEqual(u2.name, "Jim Bo")
       
    35 
       
    36     def test_reverse_by_related_name(self):
       
    37         p1 = Poll.objects.get(poll_choice__name__exact="This is the answer.")
       
    38         self.assertEqual(p1.question, "What's the first question?")
       
    39 
       
    40         p2 = Poll.objects.get(
       
    41             related_choice__name__exact="This is the answer.")
       
    42         self.assertEqual(p2.question, "What's the second question?")
       
    43 
       
    44     def test_reverse_field_name_disallowed(self):
       
    45         """
       
    46         If a related_name is given you can't use the field name instead
       
    47         """
       
    48         self.assertRaises(FieldError, Poll.objects.get,
       
    49             choice__name__exact="This is the answer")