tests.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. """
  2. Regression tests for Model inheritance behavior.
  3. """
  4. import datetime
  5. from operator import attrgetter
  6. from unittest import expectedFailure
  7. from django import forms
  8. from django.test import TestCase
  9. from .models import (
  10. ArticleWithAuthor, BachelorParty, BirthdayParty, BusStation, Child,
  11. DerivedM, InternalCertificationAudit, ItalianRestaurant, M2MChild,
  12. MessyBachelorParty, ParkingLot, ParkingLot3, ParkingLot4A, ParkingLot4B,
  13. Person, Place, Profile, QualityControl, Restaurant, SelfRefChild,
  14. SelfRefParent, Senator, Supplier, TrainStation, User, Wholesaler,
  15. )
  16. class ModelInheritanceTest(TestCase):
  17. def test_model_inheritance(self):
  18. # Regression for #7350, #7202
  19. # When you create a Parent object with a specific reference to an
  20. # existent child instance, saving the Parent doesn't duplicate the
  21. # child. This behavior is only activated during a raw save - it is
  22. # mostly relevant to deserialization, but any sort of CORBA style
  23. # 'narrow()' API would require a similar approach.
  24. # Create a child-parent-grandparent chain
  25. place1 = Place(
  26. name="Guido's House of Pasta",
  27. address='944 W. Fullerton')
  28. place1.save_base(raw=True)
  29. restaurant = Restaurant(
  30. place_ptr=place1,
  31. serves_hot_dogs=True,
  32. serves_pizza=False)
  33. restaurant.save_base(raw=True)
  34. italian_restaurant = ItalianRestaurant(
  35. restaurant_ptr=restaurant,
  36. serves_gnocchi=True)
  37. italian_restaurant.save_base(raw=True)
  38. # Create a child-parent chain with an explicit parent link
  39. place2 = Place(name='Main St', address='111 Main St')
  40. place2.save_base(raw=True)
  41. park = ParkingLot(parent=place2, capacity=100)
  42. park.save_base(raw=True)
  43. # No extra parent objects have been created.
  44. places = list(Place.objects.all())
  45. self.assertEqual(places, [place1, place2])
  46. dicts = list(Restaurant.objects.values('name', 'serves_hot_dogs'))
  47. self.assertEqual(dicts, [{
  48. 'name': "Guido's House of Pasta",
  49. 'serves_hot_dogs': True
  50. }])
  51. dicts = list(ItalianRestaurant.objects.values(
  52. 'name', 'serves_hot_dogs', 'serves_gnocchi'))
  53. self.assertEqual(dicts, [{
  54. 'name': "Guido's House of Pasta",
  55. 'serves_gnocchi': True,
  56. 'serves_hot_dogs': True,
  57. }])
  58. dicts = list(ParkingLot.objects.values('name', 'capacity'))
  59. self.assertEqual(dicts, [{
  60. 'capacity': 100,
  61. 'name': 'Main St',
  62. }])
  63. # You can also update objects when using a raw save.
  64. place1.name = "Guido's All New House of Pasta"
  65. place1.save_base(raw=True)
  66. restaurant.serves_hot_dogs = False
  67. restaurant.save_base(raw=True)
  68. italian_restaurant.serves_gnocchi = False
  69. italian_restaurant.save_base(raw=True)
  70. place2.name = 'Derelict lot'
  71. place2.save_base(raw=True)
  72. park.capacity = 50
  73. park.save_base(raw=True)
  74. # No extra parent objects after an update, either.
  75. places = list(Place.objects.all())
  76. self.assertEqual(places, [place2, place1])
  77. self.assertEqual(places[0].name, 'Derelict lot')
  78. self.assertEqual(places[1].name, "Guido's All New House of Pasta")
  79. dicts = list(Restaurant.objects.values('name', 'serves_hot_dogs'))
  80. self.assertEqual(dicts, [{
  81. 'name': "Guido's All New House of Pasta",
  82. 'serves_hot_dogs': False,
  83. }])
  84. dicts = list(ItalianRestaurant.objects.values(
  85. 'name', 'serves_hot_dogs', 'serves_gnocchi'))
  86. self.assertEqual(dicts, [{
  87. 'name': "Guido's All New House of Pasta",
  88. 'serves_gnocchi': False,
  89. 'serves_hot_dogs': False,
  90. }])
  91. dicts = list(ParkingLot.objects.values('name', 'capacity'))
  92. self.assertEqual(dicts, [{
  93. 'capacity': 50,
  94. 'name': 'Derelict lot',
  95. }])
  96. # If you try to raw_save a parent attribute onto a child object,
  97. # the attribute will be ignored.
  98. italian_restaurant.name = "Lorenzo's Pasta Hut"
  99. italian_restaurant.save_base(raw=True)
  100. # Note that the name has not changed
  101. # - name is an attribute of Place, not ItalianRestaurant
  102. dicts = list(ItalianRestaurant.objects.values(
  103. 'name', 'serves_hot_dogs', 'serves_gnocchi'))
  104. self.assertEqual(dicts, [{
  105. 'name': "Guido's All New House of Pasta",
  106. 'serves_gnocchi': False,
  107. 'serves_hot_dogs': False,
  108. }])
  109. def test_issue_7105(self):
  110. # Regressions tests for #7105: dates() queries should be able to use
  111. # fields from the parent model as easily as the child.
  112. Child.objects.create(
  113. name='child',
  114. created=datetime.datetime(2008, 6, 26, 17, 0, 0))
  115. datetimes = list(Child.objects.datetimes('created', 'month'))
  116. self.assertEqual(datetimes, [datetime.datetime(2008, 6, 1, 0, 0)])
  117. def test_issue_7276(self):
  118. # Regression test for #7276: calling delete() on a model with
  119. # multi-table inheritance should delete the associated rows from any
  120. # ancestor tables, as well as any descendent objects.
  121. place1 = Place(
  122. name="Guido's House of Pasta",
  123. address='944 W. Fullerton')
  124. place1.save_base(raw=True)
  125. restaurant = Restaurant(
  126. place_ptr=place1,
  127. serves_hot_dogs=True,
  128. serves_pizza=False)
  129. restaurant.save_base(raw=True)
  130. italian_restaurant = ItalianRestaurant(
  131. restaurant_ptr=restaurant,
  132. serves_gnocchi=True)
  133. italian_restaurant.save_base(raw=True)
  134. ident = ItalianRestaurant.objects.all()[0].id
  135. self.assertEqual(Place.objects.get(pk=ident), place1)
  136. Restaurant.objects.create(
  137. name='a',
  138. address='xx',
  139. serves_hot_dogs=True,
  140. serves_pizza=False)
  141. # This should delete both Restaurants, plus the related places, plus
  142. # the ItalianRestaurant.
  143. Restaurant.objects.all().delete()
  144. with self.assertRaises(Place.DoesNotExist):
  145. Place.objects.get(pk=ident)
  146. with self.assertRaises(ItalianRestaurant.DoesNotExist):
  147. ItalianRestaurant.objects.get(pk=ident)
  148. def test_issue_6755(self):
  149. """
  150. Regression test for #6755
  151. """
  152. r = Restaurant(serves_pizza=False, serves_hot_dogs=False)
  153. r.save()
  154. self.assertEqual(r.id, r.place_ptr_id)
  155. orig_id = r.id
  156. r = Restaurant(place_ptr_id=orig_id, serves_pizza=True, serves_hot_dogs=False)
  157. r.save()
  158. self.assertEqual(r.id, orig_id)
  159. self.assertEqual(r.id, r.place_ptr_id)
  160. def test_issue_7488(self):
  161. # Regression test for #7488. This looks a little crazy, but it's the
  162. # equivalent of what the admin interface has to do for the edit-inline
  163. # case.
  164. suppliers = Supplier.objects.filter(
  165. restaurant=Restaurant(name='xx', address='yy'))
  166. suppliers = list(suppliers)
  167. self.assertEqual(suppliers, [])
  168. def test_issue_11764(self):
  169. """
  170. Regression test for #11764
  171. """
  172. wholesalers = list(Wholesaler.objects.all().select_related())
  173. self.assertEqual(wholesalers, [])
  174. def test_issue_7853(self):
  175. """
  176. Regression test for #7853
  177. If the parent class has a self-referential link, make sure that any
  178. updates to that link via the child update the right table.
  179. """
  180. obj = SelfRefChild.objects.create(child_data=37, parent_data=42)
  181. obj.delete()
  182. def test_get_next_previous_by_date(self):
  183. """
  184. Regression tests for #8076
  185. get_(next/previous)_by_date should work
  186. """
  187. c1 = ArticleWithAuthor(
  188. headline='ArticleWithAuthor 1',
  189. author="Person 1",
  190. pub_date=datetime.datetime(2005, 8, 1, 3, 0))
  191. c1.save()
  192. c2 = ArticleWithAuthor(
  193. headline='ArticleWithAuthor 2',
  194. author="Person 2",
  195. pub_date=datetime.datetime(2005, 8, 1, 10, 0))
  196. c2.save()
  197. c3 = ArticleWithAuthor(
  198. headline='ArticleWithAuthor 3',
  199. author="Person 3",
  200. pub_date=datetime.datetime(2005, 8, 2))
  201. c3.save()
  202. self.assertEqual(c1.get_next_by_pub_date(), c2)
  203. self.assertEqual(c2.get_next_by_pub_date(), c3)
  204. with self.assertRaises(ArticleWithAuthor.DoesNotExist):
  205. c3.get_next_by_pub_date()
  206. self.assertEqual(c3.get_previous_by_pub_date(), c2)
  207. self.assertEqual(c2.get_previous_by_pub_date(), c1)
  208. with self.assertRaises(ArticleWithAuthor.DoesNotExist):
  209. c1.get_previous_by_pub_date()
  210. def test_inherited_fields(self):
  211. """
  212. Regression test for #8825 and #9390
  213. Make sure all inherited fields (esp. m2m fields, in this case) appear
  214. on the child class.
  215. """
  216. m2mchildren = list(M2MChild.objects.filter(articles__isnull=False))
  217. self.assertEqual(m2mchildren, [])
  218. # Ordering should not include any database column more than once (this
  219. # is most likely to occur naturally with model inheritance, so we
  220. # check it here). Regression test for #9390. This necessarily pokes at
  221. # the SQL string for the query, since the duplicate problems are only
  222. # apparent at that late stage.
  223. qs = ArticleWithAuthor.objects.order_by('pub_date', 'pk')
  224. sql = qs.query.get_compiler(qs.db).as_sql()[0]
  225. fragment = sql[sql.find('ORDER BY'):]
  226. pos = fragment.find('pub_date')
  227. self.assertEqual(fragment.find('pub_date', pos + 1), -1)
  228. def test_queryset_update_on_parent_model(self):
  229. """
  230. Regression test for #10362
  231. It is possible to call update() and only change a field in
  232. an ancestor model.
  233. """
  234. article = ArticleWithAuthor.objects.create(
  235. author="fred",
  236. headline="Hey there!",
  237. pub_date=datetime.datetime(2009, 3, 1, 8, 0, 0))
  238. update = ArticleWithAuthor.objects.filter(
  239. author="fred").update(headline="Oh, no!")
  240. self.assertEqual(update, 1)
  241. update = ArticleWithAuthor.objects.filter(
  242. pk=article.pk).update(headline="Oh, no!")
  243. self.assertEqual(update, 1)
  244. derivedm1 = DerivedM.objects.create(
  245. customPK=44,
  246. base_name="b1",
  247. derived_name="d1")
  248. self.assertEqual(derivedm1.customPK, 44)
  249. self.assertEqual(derivedm1.base_name, 'b1')
  250. self.assertEqual(derivedm1.derived_name, 'd1')
  251. derivedms = list(DerivedM.objects.all())
  252. self.assertEqual(derivedms, [derivedm1])
  253. def test_use_explicit_o2o_to_parent_as_pk(self):
  254. """
  255. The connector from child to parent need not be the pk on the child.
  256. """
  257. self.assertEqual(ParkingLot3._meta.pk.name, "primary_key")
  258. # the child->parent link
  259. self.assertEqual(ParkingLot3._meta.get_ancestor_link(Place).name, "parent")
  260. def test_use_explicit_o2o_to_parent_from_abstract_model(self):
  261. self.assertEqual(ParkingLot4A._meta.pk.name, "parent")
  262. ParkingLot4A.objects.create(
  263. name="Parking4A",
  264. address='21 Jump Street',
  265. )
  266. self.assertEqual(ParkingLot4B._meta.pk.name, "parent")
  267. ParkingLot4A.objects.create(
  268. name="Parking4B",
  269. address='21 Jump Street',
  270. )
  271. def test_all_fields_from_abstract_base_class(self):
  272. """
  273. Regression tests for #7588
  274. """
  275. # All fields from an ABC, including those inherited non-abstractly
  276. # should be available on child classes (#7588). Creating this instance
  277. # should work without error.
  278. QualityControl.objects.create(
  279. headline="Problems in Django",
  280. pub_date=datetime.datetime.now(),
  281. quality=10,
  282. assignee="adrian")
  283. def test_abstract_base_class_m2m_relation_inheritance(self):
  284. # many-to-many relations defined on an abstract base class are
  285. # correctly inherited (and created) on the child class.
  286. p1 = Person.objects.create(name='Alice')
  287. p2 = Person.objects.create(name='Bob')
  288. p3 = Person.objects.create(name='Carol')
  289. p4 = Person.objects.create(name='Dave')
  290. birthday = BirthdayParty.objects.create(
  291. name='Birthday party for Alice')
  292. birthday.attendees.set([p1, p3])
  293. bachelor = BachelorParty.objects.create(name='Bachelor party for Bob')
  294. bachelor.attendees.set([p2, p4])
  295. parties = list(p1.birthdayparty_set.all())
  296. self.assertEqual(parties, [birthday])
  297. parties = list(p1.bachelorparty_set.all())
  298. self.assertEqual(parties, [])
  299. parties = list(p2.bachelorparty_set.all())
  300. self.assertEqual(parties, [bachelor])
  301. # A subclass of a subclass of an abstract model doesn't get its own
  302. # accessor.
  303. self.assertFalse(hasattr(p2, 'messybachelorparty_set'))
  304. # ... but it does inherit the m2m from its parent
  305. messy = MessyBachelorParty.objects.create(
  306. name='Bachelor party for Dave')
  307. messy.attendees.set([p4])
  308. messy_parent = messy.bachelorparty_ptr
  309. parties = list(p4.bachelorparty_set.all())
  310. self.assertEqual(parties, [bachelor, messy_parent])
  311. def test_abstract_verbose_name_plural_inheritance(self):
  312. """
  313. verbose_name_plural correctly inherited from ABC if inheritance chain
  314. includes an abstract model.
  315. """
  316. # Regression test for #11369: verbose_name_plural should be inherited
  317. # from an ABC even when there are one or more intermediate
  318. # abstract models in the inheritance chain, for consistency with
  319. # verbose_name.
  320. self.assertEqual(
  321. InternalCertificationAudit._meta.verbose_name_plural,
  322. 'Audits'
  323. )
  324. def test_inherited_nullable_exclude(self):
  325. obj = SelfRefChild.objects.create(child_data=37, parent_data=42)
  326. self.assertQuerysetEqual(
  327. SelfRefParent.objects.exclude(self_data=72), [
  328. obj.pk
  329. ],
  330. attrgetter("pk")
  331. )
  332. self.assertQuerysetEqual(
  333. SelfRefChild.objects.exclude(self_data=72), [
  334. obj.pk
  335. ],
  336. attrgetter("pk")
  337. )
  338. def test_concrete_abstract_concrete_pk(self):
  339. """
  340. Primary key set correctly with concrete->abstract->concrete inheritance.
  341. """
  342. # Regression test for #13987: Primary key is incorrectly determined
  343. # when more than one model has a concrete->abstract->concrete
  344. # inheritance hierarchy.
  345. self.assertEqual(
  346. len([field for field in BusStation._meta.local_fields if field.primary_key]),
  347. 1
  348. )
  349. self.assertEqual(
  350. len([field for field in TrainStation._meta.local_fields if field.primary_key]),
  351. 1
  352. )
  353. self.assertIs(BusStation._meta.pk.model, BusStation)
  354. self.assertIs(TrainStation._meta.pk.model, TrainStation)
  355. def test_inherited_unique_field_with_form(self):
  356. """
  357. A model which has different primary key for the parent model passes
  358. unique field checking correctly (#17615).
  359. """
  360. class ProfileForm(forms.ModelForm):
  361. class Meta:
  362. model = Profile
  363. fields = '__all__'
  364. User.objects.create(username="user_only")
  365. p = Profile.objects.create(username="user_with_profile")
  366. form = ProfileForm({'username': "user_with_profile", 'extra': "hello"}, instance=p)
  367. self.assertTrue(form.is_valid())
  368. def test_inheritance_joins(self):
  369. # Test for #17502 - check that filtering through two levels of
  370. # inheritance chain doesn't generate extra joins.
  371. qs = ItalianRestaurant.objects.all()
  372. self.assertEqual(str(qs.query).count('JOIN'), 2)
  373. qs = ItalianRestaurant.objects.filter(name='foo')
  374. self.assertEqual(str(qs.query).count('JOIN'), 2)
  375. @expectedFailure
  376. def test_inheritance_values_joins(self):
  377. # It would be nice (but not too important) to skip the middle join in
  378. # this case. Skipping is possible as nothing from the middle model is
  379. # used in the qs and top contains direct pointer to the bottom model.
  380. qs = ItalianRestaurant.objects.values_list('serves_gnocchi').filter(name='foo')
  381. self.assertEqual(str(qs.query).count('JOIN'), 1)
  382. def test_issue_21554(self):
  383. senator = Senator.objects.create(name='John Doe', title='X', state='Y')
  384. senator = Senator.objects.get(pk=senator.pk)
  385. self.assertEqual(senator.name, 'John Doe')
  386. self.assertEqual(senator.title, 'X')
  387. self.assertEqual(senator.state, 'Y')
  388. def test_inheritance_resolve_columns(self):
  389. Restaurant.objects.create(name='Bobs Cafe', address="Somewhere",
  390. serves_pizza=True, serves_hot_dogs=True)
  391. p = Place.objects.all().select_related('restaurant')[0]
  392. self.assertIsInstance(p.restaurant.serves_pizza, bool)
  393. def test_inheritance_select_related(self):
  394. # Regression test for #7246
  395. r1 = Restaurant.objects.create(
  396. name="Nobu", serves_hot_dogs=True, serves_pizza=False
  397. )
  398. r2 = Restaurant.objects.create(
  399. name="Craft", serves_hot_dogs=False, serves_pizza=True
  400. )
  401. Supplier.objects.create(name="John", restaurant=r1)
  402. Supplier.objects.create(name="Jane", restaurant=r2)
  403. self.assertQuerysetEqual(
  404. Supplier.objects.order_by("name").select_related(), [
  405. "Jane",
  406. "John",
  407. ],
  408. attrgetter("name")
  409. )
  410. jane = Supplier.objects.order_by("name").select_related("restaurant")[0]
  411. self.assertEqual(jane.restaurant.name, "Craft")
  412. def test_filter_with_parent_fk(self):
  413. r = Restaurant.objects.create()
  414. s = Supplier.objects.create(restaurant=r)
  415. # The mismatch between Restaurant and Place is intentional (#28175).
  416. self.assertSequenceEqual(Supplier.objects.filter(restaurant__in=Place.objects.all()), [s])
  417. def test_ptr_accessor_assigns_state(self):
  418. r = Restaurant.objects.create()
  419. self.assertIs(r.place_ptr._state.adding, False)
  420. self.assertEqual(r.place_ptr._state.db, 'default')
  421. def test_related_filtering_query_efficiency_ticket_15844(self):
  422. r = Restaurant.objects.create(
  423. name="Guido's House of Pasta",
  424. address='944 W. Fullerton',
  425. serves_hot_dogs=True,
  426. serves_pizza=False,
  427. )
  428. s = Supplier.objects.create(restaurant=r)
  429. with self.assertNumQueries(1):
  430. self.assertSequenceEqual(Supplier.objects.filter(restaurant=r), [s])
  431. with self.assertNumQueries(1):
  432. self.assertSequenceEqual(r.supplier_set.all(), [s])
  433. def test_queries_on_parent_access(self):
  434. italian_restaurant = ItalianRestaurant.objects.create(
  435. name="Guido's House of Pasta",
  436. address='944 W. Fullerton',
  437. serves_hot_dogs=True,
  438. serves_pizza=False,
  439. serves_gnocchi=True,
  440. )
  441. # No queries are made when accessing the parent objects.
  442. italian_restaurant = ItalianRestaurant.objects.get(pk=italian_restaurant.pk)
  443. with self.assertNumQueries(0):
  444. restaurant = italian_restaurant.restaurant_ptr
  445. self.assertEqual(restaurant.place_ptr.restaurant, restaurant)
  446. self.assertEqual(restaurant.italianrestaurant, italian_restaurant)
  447. # One query is made when accessing the parent objects when the instance
  448. # is deferred.
  449. italian_restaurant = ItalianRestaurant.objects.only('serves_gnocchi').get(pk=italian_restaurant.pk)
  450. with self.assertNumQueries(1):
  451. restaurant = italian_restaurant.restaurant_ptr
  452. self.assertEqual(restaurant.place_ptr.restaurant, restaurant)
  453. self.assertEqual(restaurant.italianrestaurant, italian_restaurant)
  454. # No queries are made when accessing the parent objects when the
  455. # instance has deferred a field not present in the parent table.
  456. italian_restaurant = ItalianRestaurant.objects.defer('serves_gnocchi').get(pk=italian_restaurant.pk)
  457. with self.assertNumQueries(0):
  458. restaurant = italian_restaurant.restaurant_ptr
  459. self.assertEqual(restaurant.place_ptr.restaurant, restaurant)
  460. self.assertEqual(restaurant.italianrestaurant, italian_restaurant)