/tests/modeltests/model_inheritance/tests.py

https://code.google.com/p/mango-py/ · Python · 275 lines · 194 code · 32 blank · 49 comment · 2 complexity · 00749b6b999857e5b4a8f15b6ce5d7ac MD5 · raw file

  1. from operator import attrgetter
  2. from django.core.exceptions import FieldError
  3. from django.test import TestCase
  4. from models import (Chef, CommonInfo, ItalianRestaurant, ParkingLot, Place,
  5. Post, Restaurant, Student, StudentWorker, Supplier, Worker, MixinModel)
  6. class ModelInheritanceTests(TestCase):
  7. def test_abstract(self):
  8. # The Student and Worker models both have 'name' and 'age' fields on
  9. # them and inherit the __unicode__() method, just as with normal Python
  10. # subclassing. This is useful if you want to factor out common
  11. # information for programming purposes, but still completely
  12. # independent separate models at the database level.
  13. w1 = Worker.objects.create(name="Fred", age=35, job="Quarry worker")
  14. w2 = Worker.objects.create(name="Barney", age=34, job="Quarry worker")
  15. s = Student.objects.create(name="Pebbles", age=5, school_class="1B")
  16. self.assertEqual(unicode(w1), "Worker Fred")
  17. self.assertEqual(unicode(s), "Student Pebbles")
  18. # The children inherit the Meta class of their parents (if they don't
  19. # specify their own).
  20. self.assertQuerysetEqual(
  21. Worker.objects.values("name"), [
  22. {"name": "Barney"},
  23. {"name": "Fred"},
  24. ],
  25. lambda o: o
  26. )
  27. # Since Student does not subclass CommonInfo's Meta, it has the effect
  28. # of completely overriding it. So ordering by name doesn't take place
  29. # for Students.
  30. self.assertEqual(Student._meta.ordering, [])
  31. # However, the CommonInfo class cannot be used as a normal model (it
  32. # doesn't exist as a model).
  33. self.assertRaises(AttributeError, lambda: CommonInfo.objects.all())
  34. # A StudentWorker which does not exist is both a Student and Worker
  35. # which does not exist.
  36. self.assertRaises(Student.DoesNotExist,
  37. StudentWorker.objects.get, pk=12321321
  38. )
  39. self.assertRaises(Worker.DoesNotExist,
  40. StudentWorker.objects.get, pk=12321321
  41. )
  42. # MultipleObjectsReturned is also inherited.
  43. # This is written out "long form", rather than using __init__/create()
  44. # because of a bug with diamond inheritance (#10808)
  45. sw1 = StudentWorker()
  46. sw1.name = "Wilma"
  47. sw1.age = 35
  48. sw1.save()
  49. sw2 = StudentWorker()
  50. sw2.name = "Betty"
  51. sw2.age = 24
  52. sw2.save()
  53. self.assertRaises(Student.MultipleObjectsReturned,
  54. StudentWorker.objects.get, pk__lt=sw2.pk + 100
  55. )
  56. self.assertRaises(Worker.MultipleObjectsReturned,
  57. StudentWorker.objects.get, pk__lt=sw2.pk + 100
  58. )
  59. def test_multiple_table(self):
  60. post = Post.objects.create(title="Lorem Ipsum")
  61. # The Post model has distinct accessors for the Comment and Link models.
  62. post.attached_comment_set.create(content="Save $ on V1agr@", is_spam=True)
  63. post.attached_link_set.create(
  64. content="The Web framework for perfections with deadlines.",
  65. url="http://www.djangoproject.com/"
  66. )
  67. # The Post model doesn't have an attribute called
  68. # 'attached_%(class)s_set'.
  69. self.assertRaises(AttributeError,
  70. getattr, post, "attached_%(class)s_set"
  71. )
  72. # The Place/Restaurant/ItalianRestaurant models all exist as
  73. # independent models. However, the subclasses also have transparent
  74. # access to the fields of their ancestors.
  75. # Create a couple of Places.
  76. p1 = Place.objects.create(name="Master Shakes", address="666 W. Jersey")
  77. p2 = Place.objects.create(name="Ace Harware", address="1013 N. Ashland")
  78. # Test constructor for Restaurant.
  79. r = Restaurant.objects.create(
  80. name="Demon Dogs",
  81. address="944 W. Fullerton",
  82. serves_hot_dogs=True,
  83. serves_pizza=False,
  84. rating=2
  85. )
  86. # Test the constructor for ItalianRestaurant.
  87. c = Chef.objects.create(name="Albert")
  88. ir = ItalianRestaurant.objects.create(
  89. name="Ristorante Miron",
  90. address="1234 W. Ash",
  91. serves_hot_dogs=False,
  92. serves_pizza=False,
  93. serves_gnocchi=True,
  94. rating=4,
  95. chef=c
  96. )
  97. self.assertQuerysetEqual(
  98. ItalianRestaurant.objects.filter(address="1234 W. Ash"), [
  99. "Ristorante Miron",
  100. ],
  101. attrgetter("name")
  102. )
  103. ir.address = "1234 W. Elm"
  104. ir.save()
  105. self.assertQuerysetEqual(
  106. ItalianRestaurant.objects.filter(address="1234 W. Elm"), [
  107. "Ristorante Miron",
  108. ],
  109. attrgetter("name")
  110. )
  111. # Make sure Restaurant and ItalianRestaurant have the right fields in
  112. # the right order.
  113. self.assertEqual(
  114. [f.name for f in Restaurant._meta.fields],
  115. ["id", "name", "address", "place_ptr", "rating", "serves_hot_dogs", "serves_pizza", "chef"]
  116. )
  117. self.assertEqual(
  118. [f.name for f in ItalianRestaurant._meta.fields],
  119. ["id", "name", "address", "place_ptr", "rating", "serves_hot_dogs", "serves_pizza", "chef", "restaurant_ptr", "serves_gnocchi"],
  120. )
  121. self.assertEqual(Restaurant._meta.ordering, ["-rating"])
  122. # Even though p.supplier for a Place 'p' (a parent of a Supplier), a
  123. # Restaurant object cannot access that reverse relation, since it's not
  124. # part of the Place-Supplier Hierarchy.
  125. self.assertQuerysetEqual(Place.objects.filter(supplier__name="foo"), [])
  126. self.assertRaises(FieldError,
  127. Restaurant.objects.filter, supplier__name="foo"
  128. )
  129. # Parent fields can be used directly in filters on the child model.
  130. self.assertQuerysetEqual(
  131. Restaurant.objects.filter(name="Demon Dogs"), [
  132. "Demon Dogs",
  133. ],
  134. attrgetter("name")
  135. )
  136. self.assertQuerysetEqual(
  137. ItalianRestaurant.objects.filter(address="1234 W. Elm"), [
  138. "Ristorante Miron",
  139. ],
  140. attrgetter("name")
  141. )
  142. # Filters against the parent model return objects of the parent's type.
  143. p = Place.objects.get(name="Demon Dogs")
  144. self.assertIs(type(p), Place)
  145. # Since the parent and child are linked by an automatically created
  146. # OneToOneField, you can get from the parent to the child by using the
  147. # child's name.
  148. self.assertEqual(
  149. p.restaurant, Restaurant.objects.get(name="Demon Dogs")
  150. )
  151. self.assertEqual(
  152. Place.objects.get(name="Ristorante Miron").restaurant.italianrestaurant,
  153. ItalianRestaurant.objects.get(name="Ristorante Miron")
  154. )
  155. self.assertEqual(
  156. Restaurant.objects.get(name="Ristorante Miron").italianrestaurant,
  157. ItalianRestaurant.objects.get(name="Ristorante Miron")
  158. )
  159. # This won't work because the Demon Dogs restaurant is not an Italian
  160. # restaurant.
  161. self.assertRaises(ItalianRestaurant.DoesNotExist,
  162. lambda: p.restaurant.italianrestaurant
  163. )
  164. # An ItalianRestaurant which does not exist is also a Place which does
  165. # not exist.
  166. self.assertRaises(Place.DoesNotExist,
  167. ItalianRestaurant.objects.get, name="The Noodle Void"
  168. )
  169. # MultipleObjectsReturned is also inherited.
  170. self.assertRaises(Place.MultipleObjectsReturned,
  171. Restaurant.objects.get, id__lt=12321
  172. )
  173. # Related objects work just as they normally do.
  174. s1 = Supplier.objects.create(name="Joe's Chickens", address="123 Sesame St")
  175. s1.customers = [r, ir]
  176. s2 = Supplier.objects.create(name="Luigi's Pasta", address="456 Sesame St")
  177. s2.customers = [ir]
  178. # This won't work because the Place we select is not a Restaurant (it's
  179. # a Supplier).
  180. p = Place.objects.get(name="Joe's Chickens")
  181. self.assertRaises(Restaurant.DoesNotExist,
  182. lambda: p.restaurant
  183. )
  184. self.assertEqual(p.supplier, s1)
  185. self.assertQuerysetEqual(
  186. ir.provider.order_by("-name"), [
  187. "Luigi's Pasta",
  188. "Joe's Chickens"
  189. ],
  190. attrgetter("name")
  191. )
  192. self.assertQuerysetEqual(
  193. Restaurant.objects.filter(provider__name__contains="Chickens"), [
  194. "Ristorante Miron",
  195. "Demon Dogs",
  196. ],
  197. attrgetter("name")
  198. )
  199. self.assertQuerysetEqual(
  200. ItalianRestaurant.objects.filter(provider__name__contains="Chickens"), [
  201. "Ristorante Miron",
  202. ],
  203. attrgetter("name"),
  204. )
  205. park1 = ParkingLot.objects.create(
  206. name="Main St", address="111 Main St", main_site=s1
  207. )
  208. park2 = ParkingLot.objects.create(
  209. name="Well Lit", address="124 Sesame St", main_site=ir
  210. )
  211. self.assertEqual(
  212. Restaurant.objects.get(lot__name="Well Lit").name,
  213. "Ristorante Miron"
  214. )
  215. # The update() command can update fields in parent and child classes at
  216. # once (although it executed multiple SQL queries to do so).
  217. rows = Restaurant.objects.filter(
  218. serves_hot_dogs=True, name__contains="D"
  219. ).update(
  220. name="Demon Puppies", serves_hot_dogs=False
  221. )
  222. self.assertEqual(rows, 1)
  223. r1 = Restaurant.objects.get(pk=r.pk)
  224. self.assertFalse(r1.serves_hot_dogs)
  225. self.assertEqual(r1.name, "Demon Puppies")
  226. # The values() command also works on fields from parent models.
  227. self.assertQuerysetEqual(
  228. ItalianRestaurant.objects.values("name", "rating"), [
  229. {"rating": 4, "name": "Ristorante Miron"}
  230. ],
  231. lambda o: o
  232. )
  233. # select_related works with fields from the parent object as if they
  234. # were a normal part of the model.
  235. self.assertNumQueries(2,
  236. lambda: ItalianRestaurant.objects.all()[0].chef
  237. )
  238. self.assertNumQueries(1,
  239. lambda: ItalianRestaurant.objects.select_related("chef")[0].chef
  240. )
  241. def test_mixin_init(self):
  242. m = MixinModel()
  243. self.assertEqual(m.other_attr, 1)