| 1 |
from django.core.exceptions import FieldError |
| 2 |
from django.test import TestCase |
| 3 |
|
| 4 |
from .models import Choice, Poll, User |
| 5 |
|
| 6 |
|
| 7 |
class ReverseLookupTests(TestCase): |
| 8 |
@classmethod |
| 9 |
def setUpTestData(cls): |
| 10 |
john = User.objects.create(name="John Doe") |
| 11 |
jim = User.objects.create(name="Jim Bo") |
| 12 |
first_poll = Poll.objects.create( |
| 13 |
question="What's the first question?", creator=john |
| 14 |
) |
| 15 |
second_poll = Poll.objects.create( |
| 16 |
question="What's the second question?", creator=jim |
| 17 |
) |
| 18 |
Choice.objects.create( |
| 19 |
poll=first_poll, related_poll=second_poll, name="This is the answer." |
| 20 |
) |
| 21 |
|
| 22 |
def test_reverse_by_field(self): |
| 23 |
u1 = User.objects.get(poll__question__exact="What's the first question?") |
| 24 |
self.assertEqual(u1.name, "John Doe") |
| 25 |
|
| 26 |
u2 = User.objects.get(poll__question__exact="What's the second question?") |
| 27 |
self.assertEqual(u2.name, "Jim Bo") |
| 28 |
|
| 29 |
def test_reverse_by_related_name(self): |
| 30 |
p1 = Poll.objects.get(poll_choice__name__exact="This is the answer.") |
| 31 |
self.assertEqual(p1.question, "What's the first question?") |
| 32 |
|
| 33 |
p2 = Poll.objects.get(related_choice__name__exact="This is the answer.") |
| 34 |
self.assertEqual(p2.question, "What's the second question?") |
| 35 |
|
| 36 |
def test_reverse_field_name_disallowed(self): |
| 37 |
""" |
| 38 |
If a related_name is given you can't use the field name instead |
| 39 |
""" |
| 40 |
msg = ( |
| 41 |
"Cannot resolve keyword 'choice' into field. Choices are: " |
| 42 |
"creator, creator_id, id, poll_choice, question, related_choice" |
| 43 |
) |
| 44 |
with self.assertRaisesMessage(FieldError, msg): |
| 45 |
Poll.objects.get(choice__name__exact="This is the answer") |