2010-09-13 13:28:59 +08:00
|
|
|
from django.core.exceptions import FieldError
|
2011-10-14 02:04:12 +08:00
|
|
|
from django.test import TestCase
|
|
|
|
|
2015-01-28 20:35:27 +08:00
|
|
|
from .models import Choice, Poll, User
|
2010-09-13 13:28:59 +08:00
|
|
|
|
|
|
|
|
|
|
|
class ReverseLookupTests(TestCase):
|
2018-11-24 09:59:38 +08:00
|
|
|
@classmethod
|
|
|
|
def setUpTestData(cls):
|
2010-09-13 13:28:59 +08:00
|
|
|
john = User.objects.create(name="John Doe")
|
|
|
|
jim = User.objects.create(name="Jim Bo")
|
|
|
|
first_poll = Poll.objects.create(
|
|
|
|
question="What's the first question?", creator=john
|
|
|
|
)
|
|
|
|
second_poll = Poll.objects.create(
|
|
|
|
question="What's the second question?", creator=jim
|
|
|
|
)
|
2013-10-19 20:31:38 +08:00
|
|
|
Choice.objects.create(
|
2010-09-13 13:28:59 +08:00
|
|
|
poll=first_poll, related_poll=second_poll, name="This is the answer."
|
|
|
|
)
|
|
|
|
|
|
|
|
def test_reverse_by_field(self):
|
|
|
|
u1 = User.objects.get(poll__question__exact="What's the first question?")
|
|
|
|
self.assertEqual(u1.name, "John Doe")
|
|
|
|
|
|
|
|
u2 = User.objects.get(poll__question__exact="What's the second question?")
|
|
|
|
self.assertEqual(u2.name, "Jim Bo")
|
|
|
|
|
|
|
|
def test_reverse_by_related_name(self):
|
|
|
|
p1 = Poll.objects.get(poll_choice__name__exact="This is the answer.")
|
|
|
|
self.assertEqual(p1.question, "What's the first question?")
|
|
|
|
|
2018-03-16 17:54:34 +08:00
|
|
|
p2 = Poll.objects.get(related_choice__name__exact="This is the answer.")
|
2010-09-13 13:28:59 +08:00
|
|
|
self.assertEqual(p2.question, "What's the second question?")
|
|
|
|
|
|
|
|
def test_reverse_field_name_disallowed(self):
|
|
|
|
"""
|
|
|
|
If a related_name is given you can't use the field name instead
|
|
|
|
"""
|
2017-05-29 03:37:21 +08:00
|
|
|
msg = (
|
|
|
|
"Cannot resolve keyword 'choice' into field. Choices are: "
|
|
|
|
"creator, creator_id, id, poll_choice, question, related_choice"
|
|
|
|
)
|
|
|
|
with self.assertRaisesMessage(FieldError, msg):
|
2016-01-17 19:26:39 +08:00
|
|
|
Poll.objects.get(choice__name__exact="This is the answer")
|