tests.py 12 KB

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