tests.py 30 KB

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