tests.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. import datetime
  2. from copy import deepcopy
  3. from django.core.exceptions import FieldError, MultipleObjectsReturned
  4. from django.db import models, transaction
  5. from django.db.utils import IntegrityError
  6. from django.test import TestCase
  7. from django.utils.translation import gettext_lazy
  8. from .models import (
  9. Article, Category, Child, ChildNullableParent, City, Country, District,
  10. First, Parent, Record, Relation, Reporter, School, Student, Third,
  11. ToFieldChild,
  12. )
  13. class ManyToOneTests(TestCase):
  14. def setUp(self):
  15. # Create a few Reporters.
  16. self.r = Reporter(first_name='John', last_name='Smith', email='john@example.com')
  17. self.r.save()
  18. self.r2 = Reporter(first_name='Paul', last_name='Jones', email='paul@example.com')
  19. self.r2.save()
  20. # Create an Article.
  21. self.a = Article(headline="This is a test", pub_date=datetime.date(2005, 7, 27), reporter=self.r)
  22. self.a.save()
  23. def test_get(self):
  24. # Article objects have access to their related Reporter objects.
  25. r = self.a.reporter
  26. self.assertEqual(r.id, self.r.id)
  27. self.assertEqual((r.first_name, self.r.last_name), ('John', 'Smith'))
  28. def test_create(self):
  29. # You can also instantiate an Article by passing the Reporter's ID
  30. # instead of a Reporter object.
  31. a3 = Article(headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id)
  32. a3.save()
  33. self.assertEqual(a3.reporter.id, self.r.id)
  34. # Similarly, the reporter ID can be a string.
  35. a4 = Article(headline="Fourth article", pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id))
  36. a4.save()
  37. self.assertEqual(repr(a4.reporter), "<Reporter: John Smith>")
  38. def test_add(self):
  39. # Create an Article via the Reporter object.
  40. new_article = self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29))
  41. self.assertEqual(repr(new_article), "<Article: John's second story>")
  42. self.assertEqual(new_article.reporter.id, self.r.id)
  43. # Create a new article, and add it to the article set.
  44. new_article2 = Article(headline="Paul's story", pub_date=datetime.date(2006, 1, 17))
  45. msg = "<Article: Paul's story> instance isn't saved. Use bulk=False or save the object first."
  46. with self.assertRaisesMessage(ValueError, msg):
  47. self.r.article_set.add(new_article2)
  48. self.r.article_set.add(new_article2, bulk=False)
  49. self.assertEqual(new_article2.reporter.id, self.r.id)
  50. self.assertQuerysetEqual(
  51. self.r.article_set.all(),
  52. ["<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>"]
  53. )
  54. # Add the same article to a different article set - check that it moves.
  55. self.r2.article_set.add(new_article2)
  56. self.assertEqual(new_article2.reporter.id, self.r2.id)
  57. self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"])
  58. # Adding an object of the wrong type raises TypeError.
  59. with transaction.atomic():
  60. with self.assertRaisesMessage(TypeError, "'Article' instance expected, got <Reporter:"):
  61. self.r.article_set.add(self.r2)
  62. self.assertQuerysetEqual(
  63. self.r.article_set.all(),
  64. ["<Article: John's second story>", "<Article: This is a test>"]
  65. )
  66. def test_set(self):
  67. new_article = self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29))
  68. new_article2 = self.r2.article_set.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17))
  69. # Assign the article to the reporter.
  70. new_article2.reporter = self.r
  71. new_article2.save()
  72. self.assertEqual(repr(new_article2.reporter), "<Reporter: John Smith>")
  73. self.assertEqual(new_article2.reporter.id, self.r.id)
  74. self.assertQuerysetEqual(self.r.article_set.all(), [
  75. "<Article: John's second story>",
  76. "<Article: Paul's story>",
  77. "<Article: This is a test>",
  78. ])
  79. self.assertQuerysetEqual(self.r2.article_set.all(), [])
  80. # Set the article back again.
  81. self.r2.article_set.set([new_article, new_article2])
  82. self.assertQuerysetEqual(self.r.article_set.all(), ["<Article: This is a test>"])
  83. self.assertQuerysetEqual(
  84. self.r2.article_set.all(),
  85. ["<Article: John's second story>", "<Article: Paul's story>"]
  86. )
  87. # Funny case - because the ForeignKey cannot be null,
  88. # existing members of the set must remain.
  89. self.r.article_set.set([new_article])
  90. self.assertQuerysetEqual(
  91. self.r.article_set.all(),
  92. ["<Article: John's second story>", "<Article: This is a test>"]
  93. )
  94. self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"])
  95. def test_reverse_assignment_deprecation(self):
  96. msg = (
  97. "Direct assignment to the reverse side of a related set is "
  98. "prohibited. Use article_set.set() instead."
  99. )
  100. with self.assertRaisesMessage(TypeError, msg):
  101. self.r2.article_set = []
  102. def test_assign(self):
  103. new_article = self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29))
  104. new_article2 = self.r2.article_set.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17))
  105. # Assign the article to the reporter directly using the descriptor.
  106. new_article2.reporter = self.r
  107. new_article2.save()
  108. self.assertEqual(repr(new_article2.reporter), "<Reporter: John Smith>")
  109. self.assertEqual(new_article2.reporter.id, self.r.id)
  110. self.assertQuerysetEqual(self.r.article_set.all(), [
  111. "<Article: John's second story>",
  112. "<Article: Paul's story>",
  113. "<Article: This is a test>",
  114. ])
  115. self.assertQuerysetEqual(self.r2.article_set.all(), [])
  116. # Set the article back again using set() method.
  117. self.r2.article_set.set([new_article, new_article2])
  118. self.assertQuerysetEqual(self.r.article_set.all(), ["<Article: This is a test>"])
  119. self.assertQuerysetEqual(
  120. self.r2.article_set.all(),
  121. ["<Article: John's second story>", "<Article: Paul's story>"]
  122. )
  123. # Because the ForeignKey cannot be null, existing members of the set
  124. # must remain.
  125. self.r.article_set.set([new_article])
  126. self.assertQuerysetEqual(
  127. self.r.article_set.all(),
  128. ["<Article: John's second story>", "<Article: This is a test>"]
  129. )
  130. self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"])
  131. # Reporter cannot be null - there should not be a clear or remove method
  132. self.assertFalse(hasattr(self.r2.article_set, 'remove'))
  133. self.assertFalse(hasattr(self.r2.article_set, 'clear'))
  134. def test_assign_fk_id_value(self):
  135. parent = Parent.objects.create(name='jeff')
  136. child1 = Child.objects.create(name='frank', parent=parent)
  137. child2 = Child.objects.create(name='randy', parent=parent)
  138. parent.bestchild = child1
  139. parent.save()
  140. parent.bestchild_id = child2.pk
  141. parent.save()
  142. self.assertEqual(parent.bestchild_id, child2.pk)
  143. self.assertFalse(Parent.bestchild.is_cached(parent))
  144. self.assertEqual(parent.bestchild, child2)
  145. self.assertTrue(Parent.bestchild.is_cached(parent))
  146. # Reassigning the same value doesn't clear cached instance.
  147. parent.bestchild_id = child2.pk
  148. self.assertTrue(Parent.bestchild.is_cached(parent))
  149. def test_assign_fk_id_none(self):
  150. parent = Parent.objects.create(name='jeff')
  151. child = Child.objects.create(name='frank', parent=parent)
  152. parent.bestchild = child
  153. parent.save()
  154. parent.bestchild_id = None
  155. parent.save()
  156. self.assertIsNone(parent.bestchild_id)
  157. self.assertFalse(Parent.bestchild.is_cached(parent))
  158. self.assertIsNone(parent.bestchild)
  159. self.assertTrue(Parent.bestchild.is_cached(parent))
  160. def test_selects(self):
  161. self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29))
  162. self.r2.article_set.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17))
  163. # Reporter objects have access to their related Article objects.
  164. self.assertQuerysetEqual(self.r.article_set.all(), [
  165. "<Article: John's second story>",
  166. "<Article: This is a test>",
  167. ])
  168. self.assertQuerysetEqual(self.r.article_set.filter(headline__startswith='This'), ["<Article: This is a test>"])
  169. self.assertEqual(self.r.article_set.count(), 2)
  170. self.assertEqual(self.r2.article_set.count(), 1)
  171. # Get articles by id
  172. self.assertQuerysetEqual(Article.objects.filter(id__exact=self.a.id), ["<Article: This is a test>"])
  173. self.assertQuerysetEqual(Article.objects.filter(pk=self.a.id), ["<Article: This is a test>"])
  174. # Query on an article property
  175. self.assertQuerysetEqual(Article.objects.filter(headline__startswith='This'), ["<Article: This is a test>"])
  176. # The API automatically follows relationships as far as you need.
  177. # Use double underscores to separate relationships.
  178. # This works as many levels deep as you want. There's no limit.
  179. # Find all Articles for any Reporter whose first name is "John".
  180. self.assertQuerysetEqual(
  181. Article.objects.filter(reporter__first_name__exact='John'),
  182. ["<Article: John's second story>", "<Article: This is a test>"]
  183. )
  184. # Implied __exact also works
  185. self.assertQuerysetEqual(
  186. Article.objects.filter(reporter__first_name='John'),
  187. ["<Article: John's second story>", "<Article: This is a test>"]
  188. )
  189. # Query twice over the related field.
  190. self.assertQuerysetEqual(
  191. Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith'),
  192. ["<Article: John's second story>", "<Article: This is a test>"]
  193. )
  194. # The underlying query only makes one join when a related table is referenced twice.
  195. queryset = Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith')
  196. self.assertNumQueries(1, list, queryset)
  197. self.assertEqual(queryset.query.get_compiler(queryset.db).as_sql()[0].count('INNER JOIN'), 1)
  198. # The automatically joined table has a predictable name.
  199. self.assertQuerysetEqual(
  200. Article.objects.filter(reporter__first_name__exact='John').extra(
  201. where=["many_to_one_reporter.last_name='Smith'"]),
  202. ["<Article: John's second story>", "<Article: This is a test>"]
  203. )
  204. # ... and should work fine with the string that comes out of forms.Form.cleaned_data
  205. self.assertQuerysetEqual(
  206. (Article.objects
  207. .filter(reporter__first_name__exact='John')
  208. .extra(where=["many_to_one_reporter.last_name='%s'" % 'Smith'])),
  209. ["<Article: John's second story>", "<Article: This is a test>"]
  210. )
  211. # Find all Articles for a Reporter.
  212. # Use direct ID check, pk check, and object comparison
  213. self.assertQuerysetEqual(
  214. Article.objects.filter(reporter__id__exact=self.r.id),
  215. [
  216. "<Article: John's second story>",
  217. "<Article: This is a test>",
  218. ])
  219. self.assertQuerysetEqual(
  220. Article.objects.filter(reporter__pk=self.r.id),
  221. [
  222. "<Article: John's second story>",
  223. "<Article: This is a test>",
  224. ])
  225. self.assertQuerysetEqual(
  226. Article.objects.filter(reporter=self.r.id),
  227. [
  228. "<Article: John's second story>",
  229. "<Article: This is a test>",
  230. ])
  231. self.assertQuerysetEqual(
  232. Article.objects.filter(reporter=self.r),
  233. [
  234. "<Article: John's second story>",
  235. "<Article: This is a test>",
  236. ])
  237. self.assertQuerysetEqual(
  238. Article.objects.filter(reporter__in=[self.r.id, self.r2.id]).distinct(),
  239. [
  240. "<Article: John's second story>",
  241. "<Article: Paul's story>",
  242. "<Article: This is a test>",
  243. ])
  244. self.assertQuerysetEqual(
  245. Article.objects.filter(reporter__in=[self.r, self.r2]).distinct(),
  246. [
  247. "<Article: John's second story>",
  248. "<Article: Paul's story>",
  249. "<Article: This is a test>",
  250. ])
  251. # You can also use a queryset instead of a literal list of instances.
  252. # The queryset must be reduced to a list of values using values(),
  253. # then converted into a query
  254. self.assertQuerysetEqual(
  255. Article.objects.filter(
  256. reporter__in=Reporter.objects.filter(first_name='John').values('pk').query
  257. ).distinct(),
  258. [
  259. "<Article: John's second story>",
  260. "<Article: This is a test>",
  261. ])
  262. def test_reverse_selects(self):
  263. a3 = Article.objects.create(
  264. headline="Third article",
  265. pub_date=datetime.date(2005, 7, 27),
  266. reporter_id=self.r.id,
  267. )
  268. Article.objects.create(
  269. headline="Fourth article",
  270. pub_date=datetime.date(2005, 7, 27),
  271. reporter_id=self.r.id,
  272. )
  273. john_smith = ["<Reporter: John Smith>"]
  274. # Reporters can be queried
  275. self.assertQuerysetEqual(Reporter.objects.filter(id__exact=self.r.id), john_smith)
  276. self.assertQuerysetEqual(Reporter.objects.filter(pk=self.r.id), john_smith)
  277. self.assertQuerysetEqual(Reporter.objects.filter(first_name__startswith='John'), john_smith)
  278. # Reporters can query in opposite direction of ForeignKey definition
  279. self.assertQuerysetEqual(Reporter.objects.filter(article__id__exact=self.a.id), john_smith)
  280. self.assertQuerysetEqual(Reporter.objects.filter(article__pk=self.a.id), john_smith)
  281. self.assertQuerysetEqual(Reporter.objects.filter(article=self.a.id), john_smith)
  282. self.assertQuerysetEqual(Reporter.objects.filter(article=self.a), john_smith)
  283. self.assertQuerysetEqual(Reporter.objects.filter(article__in=[self.a.id, a3.id]).distinct(), john_smith)
  284. self.assertQuerysetEqual(Reporter.objects.filter(article__in=[self.a.id, a3]).distinct(), john_smith)
  285. self.assertQuerysetEqual(Reporter.objects.filter(article__in=[self.a, a3]).distinct(), john_smith)
  286. self.assertQuerysetEqual(
  287. Reporter.objects.filter(article__headline__startswith='T'),
  288. ["<Reporter: John Smith>", "<Reporter: John Smith>"],
  289. ordered=False
  290. )
  291. self.assertQuerysetEqual(Reporter.objects.filter(article__headline__startswith='T').distinct(), john_smith)
  292. # Counting in the opposite direction works in conjunction with distinct()
  293. self.assertEqual(Reporter.objects.filter(article__headline__startswith='T').count(), 2)
  294. self.assertEqual(Reporter.objects.filter(article__headline__startswith='T').distinct().count(), 1)
  295. # Queries can go round in circles.
  296. self.assertQuerysetEqual(
  297. Reporter.objects.filter(article__reporter__first_name__startswith='John'),
  298. [
  299. "<Reporter: John Smith>",
  300. "<Reporter: John Smith>",
  301. "<Reporter: John Smith>",
  302. ],
  303. ordered=False
  304. )
  305. self.assertQuerysetEqual(
  306. Reporter.objects.filter(article__reporter__first_name__startswith='John').distinct(),
  307. john_smith
  308. )
  309. self.assertQuerysetEqual(Reporter.objects.filter(article__reporter__exact=self.r).distinct(), john_smith)
  310. # Implied __exact also works.
  311. self.assertQuerysetEqual(Reporter.objects.filter(article__reporter=self.r).distinct(), john_smith)
  312. # It's possible to use values() calls across many-to-one relations.
  313. # (Note, too, that we clear the ordering here so as not to drag the
  314. # 'headline' field into the columns being used to determine uniqueness)
  315. d = {'reporter__first_name': 'John', 'reporter__last_name': 'Smith'}
  316. qs = Article.objects.filter(
  317. reporter=self.r,
  318. ).distinct().order_by().values('reporter__first_name', 'reporter__last_name')
  319. self.assertEqual([d], list(qs))
  320. def test_select_related(self):
  321. # Article.objects.select_related().dates() works properly when there
  322. # are multiple Articles with the same date but different foreign-key
  323. # objects (Reporters).
  324. r1 = Reporter.objects.create(first_name='Mike', last_name='Royko', email='royko@suntimes.com')
  325. r2 = Reporter.objects.create(first_name='John', last_name='Kass', email='jkass@tribune.com')
  326. Article.objects.create(headline='First', pub_date=datetime.date(1980, 4, 23), reporter=r1)
  327. Article.objects.create(headline='Second', pub_date=datetime.date(1980, 4, 23), reporter=r2)
  328. self.assertEqual(
  329. list(Article.objects.select_related().dates('pub_date', 'day')),
  330. [datetime.date(1980, 4, 23), datetime.date(2005, 7, 27)]
  331. )
  332. self.assertEqual(
  333. list(Article.objects.select_related().dates('pub_date', 'month')),
  334. [datetime.date(1980, 4, 1), datetime.date(2005, 7, 1)]
  335. )
  336. self.assertEqual(
  337. list(Article.objects.select_related().dates('pub_date', 'year')),
  338. [datetime.date(1980, 1, 1), datetime.date(2005, 1, 1)]
  339. )
  340. def test_delete(self):
  341. self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29))
  342. self.r2.article_set.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17))
  343. Article.objects.create(headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id)
  344. Article.objects.create(
  345. headline="Fourth article",
  346. pub_date=datetime.date(2005, 7, 27),
  347. reporter_id=str(self.r.id),
  348. )
  349. # If you delete a reporter, his articles will be deleted.
  350. self.assertQuerysetEqual(
  351. Article.objects.all(),
  352. [
  353. "<Article: Fourth article>",
  354. "<Article: John's second story>",
  355. "<Article: Paul's story>",
  356. "<Article: Third article>",
  357. "<Article: This is a test>",
  358. ]
  359. )
  360. self.assertQuerysetEqual(
  361. Reporter.objects.order_by('first_name'),
  362. ["<Reporter: John Smith>", "<Reporter: Paul Jones>"]
  363. )
  364. self.r2.delete()
  365. self.assertQuerysetEqual(
  366. Article.objects.all(),
  367. [
  368. "<Article: Fourth article>",
  369. "<Article: John's second story>",
  370. "<Article: Third article>",
  371. "<Article: This is a test>",
  372. ]
  373. )
  374. self.assertQuerysetEqual(Reporter.objects.order_by('first_name'), ["<Reporter: John Smith>"])
  375. # You can delete using a JOIN in the query.
  376. Reporter.objects.filter(article__headline__startswith='This').delete()
  377. self.assertQuerysetEqual(Reporter.objects.all(), [])
  378. self.assertQuerysetEqual(Article.objects.all(), [])
  379. def test_explicit_fk(self):
  380. # Create a new Article with get_or_create using an explicit value
  381. # for a ForeignKey.
  382. a2, created = Article.objects.get_or_create(
  383. headline="John's second test",
  384. pub_date=datetime.date(2011, 5, 7),
  385. reporter_id=self.r.id,
  386. )
  387. self.assertTrue(created)
  388. self.assertEqual(a2.reporter.id, self.r.id)
  389. # You can specify filters containing the explicit FK value.
  390. self.assertQuerysetEqual(
  391. Article.objects.filter(reporter_id__exact=self.r.id),
  392. ["<Article: John's second test>", "<Article: This is a test>"]
  393. )
  394. # Create an Article by Paul for the same date.
  395. a3 = Article.objects.create(
  396. headline="Paul's commentary",
  397. pub_date=datetime.date(2011, 5, 7),
  398. reporter_id=self.r2.id,
  399. )
  400. self.assertEqual(a3.reporter.id, self.r2.id)
  401. # Get should respect explicit foreign keys as well.
  402. msg = 'get() returned more than one Article -- it returned 2!'
  403. with self.assertRaisesMessage(MultipleObjectsReturned, msg):
  404. Article.objects.get(reporter_id=self.r.id)
  405. self.assertEqual(
  406. repr(a3),
  407. repr(Article.objects.get(reporter_id=self.r2.id, pub_date=datetime.date(2011, 5, 7)))
  408. )
  409. def test_deepcopy_and_circular_references(self):
  410. # Regression for #12876 -- Model methods that include queries that
  411. # recursive don't cause recursion depth problems under deepcopy.
  412. self.r.cached_query = Article.objects.filter(reporter=self.r)
  413. self.assertEqual(repr(deepcopy(self.r)), "<Reporter: John Smith>")
  414. def test_manager_class_caching(self):
  415. r1 = Reporter.objects.create(first_name='Mike')
  416. r2 = Reporter.objects.create(first_name='John')
  417. # Same twice
  418. self.assertIs(r1.article_set.__class__, r1.article_set.__class__)
  419. # Same as each other
  420. self.assertIs(r1.article_set.__class__, r2.article_set.__class__)
  421. def test_create_relation_with_gettext_lazy(self):
  422. reporter = Reporter.objects.create(first_name='John', last_name='Smith', email='john.smith@example.com')
  423. lazy = gettext_lazy('test')
  424. reporter.article_set.create(headline=lazy, pub_date=datetime.date(2011, 6, 10))
  425. notlazy = str(lazy)
  426. article = reporter.article_set.get()
  427. self.assertEqual(article.headline, notlazy)
  428. def test_values_list_exception(self):
  429. expected_message = "Cannot resolve keyword 'notafield' into field. Choices are: %s"
  430. reporter_fields = ', '.join(sorted(f.name for f in Reporter._meta.get_fields()))
  431. with self.assertRaisesMessage(FieldError, expected_message % reporter_fields):
  432. Article.objects.values_list('reporter__notafield')
  433. article_fields = ', '.join(['EXTRA'] + sorted(f.name for f in Article._meta.get_fields()))
  434. with self.assertRaisesMessage(FieldError, expected_message % article_fields):
  435. Article.objects.extra(select={'EXTRA': 'EXTRA_SELECT'}).values_list('notafield')
  436. def test_fk_assignment_and_related_object_cache(self):
  437. # Tests of ForeignKey assignment and the related-object cache (see #6886).
  438. p = Parent.objects.create(name="Parent")
  439. c = Child.objects.create(name="Child", parent=p)
  440. # Look up the object again so that we get a "fresh" object.
  441. c = Child.objects.get(name="Child")
  442. p = c.parent
  443. # Accessing the related object again returns the exactly same object.
  444. self.assertIs(c.parent, p)
  445. # But if we kill the cache, we get a new object.
  446. del c._state.fields_cache['parent']
  447. self.assertIsNot(c.parent, p)
  448. # Assigning a new object results in that object getting cached immediately.
  449. p2 = Parent.objects.create(name="Parent 2")
  450. c.parent = p2
  451. self.assertIs(c.parent, p2)
  452. # Assigning None succeeds if field is null=True.
  453. p.bestchild = None
  454. self.assertIsNone(p.bestchild)
  455. # bestchild should still be None after saving.
  456. p.save()
  457. self.assertIsNone(p.bestchild)
  458. # bestchild should still be None after fetching the object again.
  459. p = Parent.objects.get(name="Parent")
  460. self.assertIsNone(p.bestchild)
  461. # Assigning None will not fail: Child.parent is null=False.
  462. setattr(c, "parent", None)
  463. # You also can't assign an object of the wrong type here
  464. msg = (
  465. 'Cannot assign "<First: First object (1)>": "Child.parent" must '
  466. 'be a "Parent" instance.'
  467. )
  468. with self.assertRaisesMessage(ValueError, msg):
  469. setattr(c, "parent", First(id=1, second=1))
  470. # You can assign None to Child.parent during object creation.
  471. Child(name='xyzzy', parent=None)
  472. # But when trying to save a Child with parent=None, the database will
  473. # raise IntegrityError.
  474. with self.assertRaises(IntegrityError), transaction.atomic():
  475. Child.objects.create(name='xyzzy', parent=None)
  476. # Creation using keyword argument should cache the related object.
  477. p = Parent.objects.get(name="Parent")
  478. c = Child(parent=p)
  479. self.assertIs(c.parent, p)
  480. # Creation using keyword argument and unsaved related instance (#8070).
  481. p = Parent()
  482. msg = "save() prohibited to prevent data loss due to unsaved related object 'parent'."
  483. with self.assertRaisesMessage(ValueError, msg):
  484. Child.objects.create(parent=p)
  485. msg = "save() prohibited to prevent data loss due to unsaved related object 'parent'."
  486. with self.assertRaisesMessage(ValueError, msg):
  487. ToFieldChild.objects.create(parent=p)
  488. # Creation using attname keyword argument and an id will cause the
  489. # related object to be fetched.
  490. p = Parent.objects.get(name="Parent")
  491. c = Child(parent_id=p.id)
  492. self.assertIsNot(c.parent, p)
  493. self.assertEqual(c.parent, p)
  494. def test_save_nullable_fk_after_parent(self):
  495. parent = Parent()
  496. child = ChildNullableParent(parent=parent)
  497. parent.save()
  498. child.save()
  499. child.refresh_from_db()
  500. self.assertEqual(child.parent, parent)
  501. def test_save_nullable_fk_after_parent_with_to_field(self):
  502. parent = Parent(name='jeff')
  503. child = ToFieldChild(parent=parent)
  504. parent.save()
  505. child.save()
  506. child.refresh_from_db()
  507. self.assertEqual(child.parent, parent)
  508. self.assertEqual(child.parent_id, parent.name)
  509. def test_fk_to_bigautofield(self):
  510. ch = City.objects.create(name='Chicago')
  511. District.objects.create(city=ch, name='Far South')
  512. District.objects.create(city=ch, name='North')
  513. ny = City.objects.create(name='New York', id=2 ** 33)
  514. District.objects.create(city=ny, name='Brooklyn')
  515. District.objects.create(city=ny, name='Manhattan')
  516. def test_fk_to_smallautofield(self):
  517. us = Country.objects.create(name='United States')
  518. City.objects.create(country=us, name='Chicago')
  519. City.objects.create(country=us, name='New York')
  520. uk = Country.objects.create(name='United Kingdom', id=2 ** 11)
  521. City.objects.create(country=uk, name='London')
  522. City.objects.create(country=uk, name='Edinburgh')
  523. def test_multiple_foreignkeys(self):
  524. # Test of multiple ForeignKeys to the same model (bug #7125).
  525. c1 = Category.objects.create(name='First')
  526. c2 = Category.objects.create(name='Second')
  527. c3 = Category.objects.create(name='Third')
  528. r1 = Record.objects.create(category=c1)
  529. r2 = Record.objects.create(category=c1)
  530. r3 = Record.objects.create(category=c2)
  531. r4 = Record.objects.create(category=c2)
  532. r5 = Record.objects.create(category=c3)
  533. Relation.objects.create(left=r1, right=r2)
  534. Relation.objects.create(left=r3, right=r4)
  535. Relation.objects.create(left=r1, right=r3)
  536. Relation.objects.create(left=r5, right=r2)
  537. Relation.objects.create(left=r3, right=r2)
  538. q1 = Relation.objects.filter(left__category__name__in=['First'], right__category__name__in=['Second'])
  539. self.assertQuerysetEqual(q1, ["<Relation: First - Second>"])
  540. q2 = Category.objects.filter(record__left_set__right__category__name='Second').order_by('name')
  541. self.assertQuerysetEqual(q2, ["<Category: First>", "<Category: Second>"])
  542. p = Parent.objects.create(name="Parent")
  543. c = Child.objects.create(name="Child", parent=p)
  544. msg = 'Cannot assign "%r": "Child.parent" must be a "Parent" instance.' % c
  545. with self.assertRaisesMessage(ValueError, msg):
  546. Child.objects.create(name="Grandchild", parent=c)
  547. def test_fk_instantiation_outside_model(self):
  548. # Regression for #12190 -- Should be able to instantiate a FK outside
  549. # of a model, and interrogate its related field.
  550. cat = models.ForeignKey(Category, models.CASCADE)
  551. self.assertEqual('id', cat.remote_field.get_related_field().name)
  552. def test_relation_unsaved(self):
  553. # The <field>_set manager does not join on Null value fields (#17541)
  554. Third.objects.create(name='Third 1')
  555. Third.objects.create(name='Third 2')
  556. th = Third(name="testing")
  557. # The object isn't saved and thus the relation field is null - we won't even
  558. # execute a query in this case.
  559. with self.assertNumQueries(0):
  560. self.assertEqual(th.child_set.count(), 0)
  561. th.save()
  562. # Now the model is saved, so we will need to execute a query.
  563. with self.assertNumQueries(1):
  564. self.assertEqual(th.child_set.count(), 0)
  565. def test_related_object(self):
  566. public_school = School.objects.create(is_public=True)
  567. public_student = Student.objects.create(school=public_school)
  568. private_school = School.objects.create(is_public=False)
  569. private_student = Student.objects.create(school=private_school)
  570. # Only one school is available via all() due to the custom default manager.
  571. self.assertSequenceEqual(School.objects.all(), [public_school])
  572. self.assertEqual(public_student.school, public_school)
  573. # Make sure the base manager is used so that a student can still access
  574. # its related school even if the default manager doesn't normally
  575. # allow it.
  576. self.assertEqual(private_student.school, private_school)
  577. School._meta.base_manager_name = 'objects'
  578. School._meta._expire_cache()
  579. try:
  580. private_student = Student.objects.get(pk=private_student.pk)
  581. with self.assertRaises(School.DoesNotExist):
  582. private_student.school
  583. finally:
  584. School._meta.base_manager_name = None
  585. School._meta._expire_cache()
  586. def test_hasattr_related_object(self):
  587. # The exception raised on attribute access when a related object
  588. # doesn't exist should be an instance of a subclass of `AttributeError`
  589. # refs #21563
  590. self.assertFalse(hasattr(Article(), 'reporter'))
  591. def test_clear_after_prefetch(self):
  592. c = City.objects.create(name='Musical City')
  593. District.objects.create(name='Ladida', city=c)
  594. city = City.objects.prefetch_related('districts').get(id=c.id)
  595. self.assertQuerysetEqual(city.districts.all(), ['<District: Ladida>'])
  596. city.districts.clear()
  597. self.assertQuerysetEqual(city.districts.all(), [])
  598. def test_remove_after_prefetch(self):
  599. c = City.objects.create(name='Musical City')
  600. d = District.objects.create(name='Ladida', city=c)
  601. city = City.objects.prefetch_related('districts').get(id=c.id)
  602. self.assertQuerysetEqual(city.districts.all(), ['<District: Ladida>'])
  603. city.districts.remove(d)
  604. self.assertQuerysetEqual(city.districts.all(), [])
  605. def test_add_after_prefetch(self):
  606. c = City.objects.create(name='Musical City')
  607. District.objects.create(name='Ladida', city=c)
  608. d2 = District.objects.create(name='Ladidu')
  609. city = City.objects.prefetch_related('districts').get(id=c.id)
  610. self.assertEqual(city.districts.count(), 1)
  611. city.districts.add(d2)
  612. self.assertEqual(city.districts.count(), 2)
  613. def test_set_after_prefetch(self):
  614. c = City.objects.create(name='Musical City')
  615. District.objects.create(name='Ladida', city=c)
  616. d2 = District.objects.create(name='Ladidu')
  617. city = City.objects.prefetch_related('districts').get(id=c.id)
  618. self.assertEqual(city.districts.count(), 1)
  619. city.districts.set([d2])
  620. self.assertQuerysetEqual(city.districts.all(), ['<District: Ladidu>'])
  621. def test_add_then_remove_after_prefetch(self):
  622. c = City.objects.create(name='Musical City')
  623. District.objects.create(name='Ladida', city=c)
  624. d2 = District.objects.create(name='Ladidu')
  625. city = City.objects.prefetch_related('districts').get(id=c.id)
  626. self.assertEqual(city.districts.count(), 1)
  627. city.districts.add(d2)
  628. self.assertEqual(city.districts.count(), 2)
  629. city.districts.remove(d2)
  630. self.assertEqual(city.districts.count(), 1)
  631. def test_cached_relation_invalidated_on_save(self):
  632. """
  633. Model.save() invalidates stale ForeignKey relations after a primary key
  634. assignment.
  635. """
  636. self.assertEqual(self.a.reporter, self.r) # caches a.reporter
  637. self.a.reporter_id = self.r2.pk
  638. self.a.save()
  639. self.assertEqual(self.a.reporter, self.r2)
  640. def test_cached_foreign_key_with_to_field_not_cleared_by_save(self):
  641. parent = Parent.objects.create(name='a')
  642. child = ToFieldChild.objects.create(parent=parent)
  643. with self.assertNumQueries(0):
  644. self.assertIs(child.parent, parent)
  645. def test_reverse_foreign_key_instance_to_field_caching(self):
  646. parent = Parent.objects.create(name='a')
  647. ToFieldChild.objects.create(parent=parent)
  648. child = parent.to_field_children.get()
  649. with self.assertNumQueries(0):
  650. self.assertIs(child.parent, parent)