Debian Codegraph @

tests/many_to_many/tests.py

raw
1 from unittest import mock
2
3 from django.db import connection, transaction
4 from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
5 from django.utils.deprecation import RemovedInDjango60Warning
6
7 from .models import (
8 Article,
9 InheritedArticleA,
10 InheritedArticleB,
11 NullablePublicationThrough,
12 NullableTargetArticle,
13 Publication,
14 User,
15 )
16
17
18 class ManyToManyTests(TestCase):
19 @classmethod
20 def setUpTestData(cls):
21 # Create a couple of Publications.
22 cls.p1 = Publication.objects.create(title="The Python Journal")
23 cls.p2 = Publication.objects.create(title="Science News")
24 cls.p3 = Publication.objects.create(title="Science Weekly")
25 cls.p4 = Publication.objects.create(title="Highlights for Children")
26
27 cls.a1 = Article.objects.create(
28 headline="Django lets you build web apps easily"
29 )
30 cls.a1.publications.add(cls.p1)
31
32 cls.a2 = Article.objects.create(headline="NASA uses Python")
33 cls.a2.publications.add(cls.p1, cls.p2, cls.p3, cls.p4)
34
35 cls.a3 = Article.objects.create(headline="NASA finds intelligent life on Earth")
36 cls.a3.publications.add(cls.p2)
37
38 cls.a4 = Article.objects.create(headline="Oxygen-free diet works wonders")
39 cls.a4.publications.add(cls.p2)
40
41 def test_add(self):
42 # Create an Article.
43 a5 = Article(headline="Django lets you create web apps easily")
44 # You can't associate it with a Publication until it's been saved.
45 msg = (
46 '"<Article: Django lets you create web apps easily>" needs to have '
47 'a value for field "id" before this many-to-many relationship can be used.'
48 )
49 with self.assertRaisesMessage(ValueError, msg):
50 getattr(a5, "publications")
51 # Save it!
52 a5.save()
53 # Associate the Article with a Publication.
54 a5.publications.add(self.p1)
55 self.assertSequenceEqual(a5.publications.all(), [self.p1])
56 # Create another Article, and set it to appear in both Publications.
57 a6 = Article(headline="ESA uses Python")
58 a6.save()
59 a6.publications.add(self.p1, self.p2)
60 a6.publications.add(self.p3)
61 # Adding a second time is OK
62 a6.publications.add(self.p3)
63 self.assertSequenceEqual(
64 a6.publications.all(),
65 [self.p2, self.p3, self.p1],
66 )
67
68 # Adding an object of the wrong type raises TypeError
69 msg = (
70 "'Publication' instance expected, got <Article: Django lets you create web "
71 "apps easily>"
72 )
73 with self.assertRaisesMessage(TypeError, msg):
74 with transaction.atomic():
75 a6.publications.add(a5)
76
77 # Add a Publication directly via publications.add by using keyword arguments.
78 p5 = a6.publications.create(title="Highlights for Adults")
79 self.assertSequenceEqual(
80 a6.publications.all(),
81 [p5, self.p2, self.p3, self.p1],
82 )
83
84 def test_add_remove_set_by_pk(self):
85 a5 = Article.objects.create(headline="Django lets you create web apps easily")
86 a5.publications.add(self.p1.pk)
87 self.assertSequenceEqual(a5.publications.all(), [self.p1])
88 a5.publications.set([self.p2.pk])
89 self.assertSequenceEqual(a5.publications.all(), [self.p2])
90 a5.publications.remove(self.p2.pk)
91 self.assertSequenceEqual(a5.publications.all(), [])
92
93 def test_add_remove_set_by_to_field(self):
94 user_1 = User.objects.create(username="Jean")
95 user_2 = User.objects.create(username="Joe")
96 a5 = Article.objects.create(headline="Django lets you create web apps easily")
97 a5.authors.add(user_1.username)
98 self.assertSequenceEqual(a5.authors.all(), [user_1])
99 a5.authors.set([user_2.username])
100 self.assertSequenceEqual(a5.authors.all(), [user_2])
101 a5.authors.remove(user_2.username)
102 self.assertSequenceEqual(a5.authors.all(), [])
103
104 def test_related_manager_refresh(self):
105 user_1 = User.objects.create(username="Jean")
106 user_2 = User.objects.create(username="Joe")
107 self.a3.authors.add(user_1.username)
108 self.assertSequenceEqual(user_1.article_set.all(), [self.a3])
109 # Change the username on a different instance of the same user.
110 user_1_from_db = User.objects.get(pk=user_1.pk)
111 self.assertSequenceEqual(user_1_from_db.article_set.all(), [self.a3])
112 user_1_from_db.username = "Paul"
113 self.a3.authors.set([user_2.username])
114 user_1_from_db.save()
115 # Assign a different article.
116 self.a4.authors.add(user_1_from_db.username)
117 self.assertSequenceEqual(user_1_from_db.article_set.all(), [self.a4])
118 # Refresh the instance with an evaluated related manager.
119 user_1.refresh_from_db()
120 self.assertEqual(user_1.username, "Paul")
121 self.assertSequenceEqual(user_1.article_set.all(), [self.a4])
122
123 def test_add_remove_invalid_type(self):
124 msg = "Field 'id' expected a number but got 'invalid'."
125 for method in ["add", "remove"]:
126 with self.subTest(method), self.assertRaisesMessage(ValueError, msg):
127 getattr(self.a1.publications, method)("invalid")
128
129 def test_reverse_add(self):
130 # Adding via the 'other' end of an m2m
131 a5 = Article(headline="NASA finds intelligent life on Mars")
132 a5.save()
133 self.p2.article_set.add(a5)
134 self.assertSequenceEqual(
135 self.p2.article_set.all(),
136 [self.a3, a5, self.a2, self.a4],
137 )
138 self.assertSequenceEqual(a5.publications.all(), [self.p2])
139
140 # Adding via the other end using keywords
141 a6 = self.p2.article_set.create(headline="Carbon-free diet works wonders")
142 self.assertSequenceEqual(
143 self.p2.article_set.all(),
144 [a6, self.a3, a5, self.a2, self.a4],
145 )
146 a6 = self.p2.article_set.all()[3]
147 self.assertSequenceEqual(
148 a6.publications.all(),
149 [self.p4, self.p2, self.p3, self.p1],
150 )
151
152 @skipUnlessDBFeature("supports_ignore_conflicts")
153 def test_fast_add_ignore_conflicts(self):
154 """
155 A single query is necessary to add auto-created through instances if
156 the database backend supports bulk_create(ignore_conflicts) and no
157 m2m_changed signals receivers are connected.
158 """
159 with self.assertNumQueries(1):
160 self.a1.publications.add(self.p1, self.p2)
161
162 @skipIfDBFeature("supports_ignore_conflicts")
163 def test_add_existing_different_type(self):
164 # A single SELECT query is necessary to compare existing values to the
165 # provided one; no INSERT should be attempted.
166 with self.assertNumQueries(1):
167 self.a1.publications.add(str(self.p1.pk))
168 self.assertEqual(self.a1.publications.get(), self.p1)
169
170 @skipUnlessDBFeature("supports_ignore_conflicts")
171 def test_slow_add_ignore_conflicts(self):
172 manager_cls = self.a1.publications.__class__
173 # Simulate a race condition between the missing ids retrieval and
174 # the bulk insertion attempt.
175 missing_target_ids = {self.p1.id}
176 # Disable fast-add to test the case where the slow add path is taken.
177 add_plan = (True, False, False)
178 with mock.patch.object(
179 manager_cls, "_get_missing_target_ids", return_value=missing_target_ids
180 ) as mocked:
181 with mock.patch.object(manager_cls, "_get_add_plan", return_value=add_plan):
182 self.a1.publications.add(self.p1)
183 mocked.assert_called_once()
184
185 def test_related_sets(self):
186 # Article objects have access to their related Publication objects.
187 self.assertSequenceEqual(self.a1.publications.all(), [self.p1])
188 self.assertSequenceEqual(
189 self.a2.publications.all(),
190 [self.p4, self.p2, self.p3, self.p1],
191 )
192 # Publication objects have access to their related Article objects.
193 self.assertSequenceEqual(
194 self.p2.article_set.all(),
195 [self.a3, self.a2, self.a4],
196 )
197 self.assertSequenceEqual(
198 self.p1.article_set.all(),
199 [self.a1, self.a2],
200 )
201 self.assertSequenceEqual(
202 Publication.objects.get(id=self.p4.id).article_set.all(),
203 [self.a2],
204 )
205
206 def test_selects(self):
207 # We can perform kwarg queries across m2m relationships
208 self.assertSequenceEqual(
209 Article.objects.filter(publications__id__exact=self.p1.id),
210 [self.a1, self.a2],
211 )
212 self.assertSequenceEqual(
213 Article.objects.filter(publications__pk=self.p1.id),
214 [self.a1, self.a2],
215 )
216 self.assertSequenceEqual(
217 Article.objects.filter(publications=self.p1.id),
218 [self.a1, self.a2],
219 )
220 self.assertSequenceEqual(
221 Article.objects.filter(publications=self.p1),
222 [self.a1, self.a2],
223 )
224 self.assertSequenceEqual(
225 Article.objects.filter(publications__title__startswith="Science"),
226 [self.a3, self.a2, self.a2, self.a4],
227 )
228 self.assertSequenceEqual(
229 Article.objects.filter(
230 publications__title__startswith="Science"
231 ).distinct(),
232 [self.a3, self.a2, self.a4],
233 )
234
235 # The count() function respects distinct() as well.
236 self.assertEqual(
237 Article.objects.filter(publications__title__startswith="Science").count(), 4
238 )
239 self.assertEqual(
240 Article.objects.filter(publications__title__startswith="Science")
241 .distinct()
242 .count(),
243 3,
244 )
245 self.assertSequenceEqual(
246 Article.objects.filter(
247 publications__in=[self.p1.id, self.p2.id]
248 ).distinct(),
249 [self.a1, self.a3, self.a2, self.a4],
250 )
251 self.assertSequenceEqual(
252 Article.objects.filter(publications__in=[self.p1.id, self.p2]).distinct(),
253 [self.a1, self.a3, self.a2, self.a4],
254 )
255 self.assertSequenceEqual(
256 Article.objects.filter(publications__in=[self.p1, self.p2]).distinct(),
257 [self.a1, self.a3, self.a2, self.a4],
258 )
259
260 # Excluding a related item works as you would expect, too (although the SQL
261 # involved is a little complex).
262 self.assertSequenceEqual(
263 Article.objects.exclude(publications=self.p2),
264 [self.a1],
265 )
266
267 def test_reverse_selects(self):
268 # Reverse m2m queries are supported (i.e., starting at the table that
269 # doesn't have a ManyToManyField).
270 python_journal = [self.p1]
271 self.assertSequenceEqual(
272 Publication.objects.filter(id__exact=self.p1.id), python_journal
273 )
274 self.assertSequenceEqual(
275 Publication.objects.filter(pk=self.p1.id), python_journal
276 )
277 self.assertSequenceEqual(
278 Publication.objects.filter(article__headline__startswith="NASA"),
279 [self.p4, self.p2, self.p2, self.p3, self.p1],
280 )
281
282 self.assertSequenceEqual(
283 Publication.objects.filter(article__id__exact=self.a1.id), python_journal
284 )
285 self.assertSequenceEqual(
286 Publication.objects.filter(article__pk=self.a1.id), python_journal
287 )
288 self.assertSequenceEqual(
289 Publication.objects.filter(article=self.a1.id), python_journal
290 )
291 self.assertSequenceEqual(
292 Publication.objects.filter(article=self.a1), python_journal
293 )
294
295 self.assertSequenceEqual(
296 Publication.objects.filter(article__in=[self.a1.id, self.a2.id]).distinct(),
297 [self.p4, self.p2, self.p3, self.p1],
298 )
299 self.assertSequenceEqual(
300 Publication.objects.filter(article__in=[self.a1.id, self.a2]).distinct(),
301 [self.p4, self.p2, self.p3, self.p1],
302 )
303 self.assertSequenceEqual(
304 Publication.objects.filter(article__in=[self.a1, self.a2]).distinct(),
305 [self.p4, self.p2, self.p3, self.p1],
306 )
307
308 def test_delete(self):
309 # If we delete a Publication, its Articles won't be able to access it.
310 self.p1.delete()
311 self.assertSequenceEqual(
312 Publication.objects.all(),
313 [self.p4, self.p2, self.p3],
314 )
315 self.assertSequenceEqual(self.a1.publications.all(), [])
316 # If we delete an Article, its Publications won't be able to access it.
317 self.a2.delete()
318 self.assertSequenceEqual(
319 Article.objects.all(),
320 [self.a1, self.a3, self.a4],
321 )
322 self.assertSequenceEqual(
323 self.p2.article_set.all(),
324 [self.a3, self.a4],
325 )
326
327 def test_bulk_delete(self):
328 # Bulk delete some Publications - references to deleted publications should go
329 Publication.objects.filter(title__startswith="Science").delete()
330 self.assertSequenceEqual(
331 Publication.objects.all(),
332 [self.p4, self.p1],
333 )
334 self.assertSequenceEqual(
335 Article.objects.all(),
336 [self.a1, self.a3, self.a2, self.a4],
337 )
338 self.assertSequenceEqual(
339 self.a2.publications.all(),
340 [self.p4, self.p1],
341 )
342
343 # Bulk delete some articles - references to deleted objects should go
344 q = Article.objects.filter(headline__startswith="Django")
345 self.assertSequenceEqual(q, [self.a1])
346 q.delete()
347 # After the delete, the QuerySet cache needs to be cleared,
348 # and the referenced objects should be gone
349 self.assertSequenceEqual(q, [])
350 self.assertSequenceEqual(self.p1.article_set.all(), [self.a2])
351
352 def test_remove(self):
353 # Removing publication from an article:
354 self.assertSequenceEqual(
355 self.p2.article_set.all(),
356 [self.a3, self.a2, self.a4],
357 )
358 self.a4.publications.remove(self.p2)
359 self.assertSequenceEqual(
360 self.p2.article_set.all(),
361 [self.a3, self.a2],
362 )
363 self.assertSequenceEqual(self.a4.publications.all(), [])
364 # And from the other end
365 self.p2.article_set.remove(self.a3)
366 self.assertSequenceEqual(self.p2.article_set.all(), [self.a2])
367 self.assertSequenceEqual(self.a3.publications.all(), [])
368
369 def test_set(self):
370 self.p2.article_set.set([self.a4, self.a3])
371 self.assertSequenceEqual(
372 self.p2.article_set.all(),
373 [self.a3, self.a4],
374 )
375 self.assertSequenceEqual(self.a4.publications.all(), [self.p2])
376 self.a4.publications.set([self.p3.id])
377 self.assertSequenceEqual(self.p2.article_set.all(), [self.a3])
378 self.assertSequenceEqual(self.a4.publications.all(), [self.p3])
379
380 self.p2.article_set.set([])
381 self.assertSequenceEqual(self.p2.article_set.all(), [])
382 self.a4.publications.set([])
383 self.assertSequenceEqual(self.a4.publications.all(), [])
384
385 self.p2.article_set.set([self.a4, self.a3], clear=True)
386 self.assertSequenceEqual(
387 self.p2.article_set.all(),
388 [self.a3, self.a4],
389 )
390 self.assertSequenceEqual(self.a4.publications.all(), [self.p2])
391 self.a4.publications.set([self.p3.id], clear=True)
392 self.assertSequenceEqual(self.p2.article_set.all(), [self.a3])
393 self.assertSequenceEqual(self.a4.publications.all(), [self.p3])
394
395 self.p2.article_set.set([], clear=True)
396 self.assertSequenceEqual(self.p2.article_set.all(), [])
397 self.a4.publications.set([], clear=True)
398 self.assertSequenceEqual(self.a4.publications.all(), [])
399
400 def test_set_existing_different_type(self):
401 # Existing many-to-many relations remain the same for values provided
402 # with a different type.
403 ids = set(
404 Publication.article_set.through.objects.filter(
405 article__in=[self.a4, self.a3],
406 publication=self.p2,
407 ).values_list("id", flat=True)
408 )
409 self.p2.article_set.set([str(self.a4.pk), str(self.a3.pk)])
410 new_ids = set(
411 Publication.article_set.through.objects.filter(
412 publication=self.p2,
413 ).values_list("id", flat=True)
414 )
415 self.assertEqual(ids, new_ids)
416
417 def test_assign_forward(self):
418 msg = (
419 "Direct assignment to the reverse side of a many-to-many set is "
420 "prohibited. Use article_set.set() instead."
421 )
422 with self.assertRaisesMessage(TypeError, msg):
423 self.p2.article_set = [self.a4, self.a3]
424
425 def test_assign_reverse(self):
426 msg = (
427 "Direct assignment to the forward side of a many-to-many "
428 "set is prohibited. Use publications.set() instead."
429 )
430 with self.assertRaisesMessage(TypeError, msg):
431 self.a1.publications = [self.p1, self.p2]
432
433 def test_assign(self):
434 # Relation sets can be assigned using set().
435 self.p2.article_set.set([self.a4, self.a3])
436 self.assertSequenceEqual(
437 self.p2.article_set.all(),
438 [self.a3, self.a4],
439 )
440 self.assertSequenceEqual(self.a4.publications.all(), [self.p2])
441 self.a4.publications.set([self.p3.id])
442 self.assertSequenceEqual(self.p2.article_set.all(), [self.a3])
443 self.assertSequenceEqual(self.a4.publications.all(), [self.p3])
444
445 # An alternate to calling clear() is to set an empty set.
446 self.p2.article_set.set([])
447 self.assertSequenceEqual(self.p2.article_set.all(), [])
448 self.a4.publications.set([])
449 self.assertSequenceEqual(self.a4.publications.all(), [])
450
451 def test_assign_ids(self):
452 # Relation sets can also be set using primary key values
453 self.p2.article_set.set([self.a4.id, self.a3.id])
454 self.assertSequenceEqual(
455 self.p2.article_set.all(),
456 [self.a3, self.a4],
457 )
458 self.assertSequenceEqual(self.a4.publications.all(), [self.p2])
459 self.a4.publications.set([self.p3.id])
460 self.assertSequenceEqual(self.p2.article_set.all(), [self.a3])
461 self.assertSequenceEqual(self.a4.publications.all(), [self.p3])
462
463 def test_forward_assign_with_queryset(self):
464 # Querysets used in m2m assignments are pre-evaluated so their value
465 # isn't affected by the clearing operation in ManyRelatedManager.set()
466 # (#19816).
467 self.a1.publications.set([self.p1, self.p2])
468
469 qs = self.a1.publications.filter(title="The Python Journal")
470 self.a1.publications.set(qs)
471
472 self.assertEqual(1, self.a1.publications.count())
473 self.assertEqual(1, qs.count())
474
475 def test_reverse_assign_with_queryset(self):
476 # Querysets used in M2M assignments are pre-evaluated so their value
477 # isn't affected by the clearing operation in ManyRelatedManager.set()
478 # (#19816).
479 self.p1.article_set.set([self.a1, self.a2])
480
481 qs = self.p1.article_set.filter(
482 headline="Django lets you build web apps easily"
483 )
484 self.p1.article_set.set(qs)
485
486 self.assertEqual(1, self.p1.article_set.count())
487 self.assertEqual(1, qs.count())
488
489 def test_clear(self):
490 # Relation sets can be cleared:
491 self.p2.article_set.clear()
492 self.assertSequenceEqual(self.p2.article_set.all(), [])
493 self.assertSequenceEqual(self.a4.publications.all(), [])
494
495 # And you can clear from the other end
496 self.p2.article_set.add(self.a3, self.a4)
497 self.assertSequenceEqual(
498 self.p2.article_set.all(),
499 [self.a3, self.a4],
500 )
501 self.assertSequenceEqual(self.a4.publications.all(), [self.p2])
502 self.a4.publications.clear()
503 self.assertSequenceEqual(self.a4.publications.all(), [])
504 self.assertSequenceEqual(self.p2.article_set.all(), [self.a3])
505
506 def test_clear_after_prefetch(self):
507 a4 = Article.objects.prefetch_related("publications").get(id=self.a4.id)
508 self.assertSequenceEqual(a4.publications.all(), [self.p2])
509 a4.publications.clear()
510 self.assertSequenceEqual(a4.publications.all(), [])
511
512 def test_remove_after_prefetch(self):
513 a4 = Article.objects.prefetch_related("publications").get(id=self.a4.id)
514 self.assertSequenceEqual(a4.publications.all(), [self.p2])
515 a4.publications.remove(self.p2)
516 self.assertSequenceEqual(a4.publications.all(), [])
517
518 def test_add_after_prefetch(self):
519 a4 = Article.objects.prefetch_related("publications").get(id=self.a4.id)
520 self.assertEqual(a4.publications.count(), 1)
521 a4.publications.add(self.p1)
522 self.assertEqual(a4.publications.count(), 2)
523
524 def test_create_after_prefetch(self):
525 a4 = Article.objects.prefetch_related("publications").get(id=self.a4.id)
526 self.assertSequenceEqual(a4.publications.all(), [self.p2])
527 p5 = a4.publications.create(title="Django beats")
528 self.assertCountEqual(a4.publications.all(), [self.p2, p5])
529
530 def test_set_after_prefetch(self):
531 a4 = Article.objects.prefetch_related("publications").get(id=self.a4.id)
532 self.assertEqual(a4.publications.count(), 1)
533 a4.publications.set([self.p2, self.p1])
534 self.assertEqual(a4.publications.count(), 2)
535 a4.publications.set([self.p1])
536 self.assertEqual(a4.publications.count(), 1)
537
538 def test_add_then_remove_after_prefetch(self):
539 a4 = Article.objects.prefetch_related("publications").get(id=self.a4.id)
540 self.assertEqual(a4.publications.count(), 1)
541 a4.publications.add(self.p1)
542 self.assertEqual(a4.publications.count(), 2)
543 a4.publications.remove(self.p1)
544 self.assertSequenceEqual(a4.publications.all(), [self.p2])
545
546 def test_inherited_models_selects(self):
547 """
548 #24156 - Objects from child models where the parent's m2m field uses
549 related_name='+' should be retrieved correctly.
550 """
551 a = InheritedArticleA.objects.create()
552 b = InheritedArticleB.objects.create()
553 a.publications.add(self.p1, self.p2)
554 self.assertSequenceEqual(
555 a.publications.all(),
556 [self.p2, self.p1],
557 )
558 self.assertSequenceEqual(b.publications.all(), [])
559 b.publications.add(self.p3)
560 self.assertSequenceEqual(
561 a.publications.all(),
562 [self.p2, self.p1],
563 )
564 self.assertSequenceEqual(b.publications.all(), [self.p3])
565
566 def test_custom_default_manager_exists_count(self):
567 a5 = Article.objects.create(headline="deleted")
568 a5.publications.add(self.p2)
569 with self.assertNumQueries(2) as ctx:
570 self.assertEqual(
571 self.p2.article_set.count(), self.p2.article_set.all().count()
572 )
573 self.assertIn("JOIN", ctx.captured_queries[0]["sql"])
574 with self.assertNumQueries(2) as ctx:
575 self.assertEqual(
576 self.p3.article_set.exists(), self.p3.article_set.all().exists()
577 )
578 self.assertIn("JOIN", ctx.captured_queries[0]["sql"])
579
580 def test_get_prefetch_queryset_warning(self):
581 articles = Article.objects.all()
582 msg = (
583 "get_prefetch_queryset() is deprecated. Use get_prefetch_querysets() "
584 "instead."
585 )
586 with self.assertWarnsMessage(RemovedInDjango60Warning, msg) as ctx:
587 self.a1.publications.get_prefetch_queryset(articles)
588 self.assertEqual(ctx.filename, __file__)
589
590 def test_get_prefetch_querysets_invalid_querysets_length(self):
591 articles = Article.objects.all()
592 msg = (
593 "querysets argument of get_prefetch_querysets() should have a length of 1."
594 )
595 with self.assertRaisesMessage(ValueError, msg):
596 self.a1.publications.get_prefetch_querysets(
597 instances=articles,
598 querysets=[Publication.objects.all(), Publication.objects.all()],
599 )
600
601
602 class ManyToManyQueryTests(TestCase):
603 """
604 SQL is optimized to reference the through table without joining against the
605 related table when using count() and exists() functions on a queryset for
606 many to many relations. The optimization applies to the case where there
607 are no filters.
608 """
609
610 @classmethod
611 def setUpTestData(cls):
612 cls.article = Article.objects.create(
613 headline="Django lets you build Web apps easily"
614 )
615 cls.nullable_target_article = NullableTargetArticle.objects.create(
616 headline="The python is good"
617 )
618 NullablePublicationThrough.objects.create(
619 article=cls.nullable_target_article, publication=None
620 )
621
622 @skipUnlessDBFeature("supports_foreign_keys")
623 def test_count_join_optimization(self):
624 with self.assertNumQueries(1) as ctx:
625 self.article.publications.count()
626 self.assertNotIn("JOIN", ctx.captured_queries[0]["sql"])
627
628 with self.assertNumQueries(1) as ctx:
629 self.article.publications.count()
630 self.assertNotIn("JOIN", ctx.captured_queries[0]["sql"])
631 self.assertEqual(self.nullable_target_article.publications.count(), 0)
632
633 def test_count_join_optimization_disabled(self):
634 with (
635 mock.patch.object(connection.features, "supports_foreign_keys", False),
636 self.assertNumQueries(1) as ctx,
637 ):
638 self.article.publications.count()
639
640 self.assertIn("JOIN", ctx.captured_queries[0]["sql"])
641
642 @skipUnlessDBFeature("supports_foreign_keys")
643 def test_exists_join_optimization(self):
644 with self.assertNumQueries(1) as ctx:
645 self.article.publications.exists()
646 self.assertNotIn("JOIN", ctx.captured_queries[0]["sql"])
647
648 self.article.publications.prefetch_related()
649 with self.assertNumQueries(1) as ctx:
650 self.article.publications.exists()
651 self.assertNotIn("JOIN", ctx.captured_queries[0]["sql"])
652 self.assertIs(self.nullable_target_article.publications.exists(), False)
653
654 def test_exists_join_optimization_disabled(self):
655 with (
656 mock.patch.object(connection.features, "supports_foreign_keys", False),
657 self.assertNumQueries(1) as ctx,
658 ):
659 self.article.publications.exists()
660
661 self.assertIn("JOIN", ctx.captured_queries[0]["sql"])
662
663 def test_prefetch_related_no_queries_optimization_disabled(self):
664 qs = Article.objects.prefetch_related("publications")
665 article = qs.get()
666 with self.assertNumQueries(0):
667 article.publications.count()
668 with self.assertNumQueries(0):
669 article.publications.exists()