/tests/modeltests/reverse_lookup/tests.py

https://code.google.com/p/mango-py/ · Python · 49 lines · 38 code · 8 blank · 3 comment · 0 complexity · 3153f74ddce30c288798fbc92e91f876 MD5 · raw file

  1. from django.test import TestCase
  2. from django.core.exceptions import FieldError
  3. from models import User, Poll, Choice
  4. class ReverseLookupTests(TestCase):
  5. def setUp(self):
  6. john = User.objects.create(name="John Doe")
  7. jim = User.objects.create(name="Jim Bo")
  8. first_poll = Poll.objects.create(
  9. question="What's the first question?",
  10. creator=john
  11. )
  12. second_poll = Poll.objects.create(
  13. question="What's the second question?",
  14. creator=jim
  15. )
  16. new_choice = Choice.objects.create(
  17. poll=first_poll,
  18. related_poll=second_poll,
  19. name="This is the answer."
  20. )
  21. def test_reverse_by_field(self):
  22. u1 = User.objects.get(
  23. poll__question__exact="What's the first question?"
  24. )
  25. self.assertEqual(u1.name, "John Doe")
  26. u2 = User.objects.get(
  27. poll__question__exact="What's the second question?"
  28. )
  29. self.assertEqual(u2.name, "Jim Bo")
  30. def test_reverse_by_related_name(self):
  31. p1 = Poll.objects.get(poll_choice__name__exact="This is the answer.")
  32. self.assertEqual(p1.question, "What's the first question?")
  33. p2 = Poll.objects.get(
  34. related_choice__name__exact="This is the answer.")
  35. self.assertEqual(p2.question, "What's the second question?")
  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. self.assertRaises(FieldError, Poll.objects.get,
  41. choice__name__exact="This is the answer")