tests.py 24 KB

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