repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_squashed_extra/__init__.py
tests/migrations/test_migrations_squashed_extra/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/__init__.py
tests/test_runner_apps/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/failures/__init__.py
tests/test_runner_apps/failures/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/failures/tests_failures.py
tests/test_runner_apps/failures/tests_failures.py
from unittest import TestCase, expectedFailure class FailureTestCase(TestCase): def test_sample(self): self.assertEqual(0, 1) class ErrorTestCase(TestCase): def test_sample(self): raise Exception("test") class ExpectedFailureTestCase(TestCase): @expectedFailure def test_sample(self): self.assertEqual(0, 1) class UnexpectedSuccessTestCase(TestCase): @expectedFailure def test_sample(self): self.assertEqual(1, 1)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/databases/__init__.py
tests/test_runner_apps/databases/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/databases/tests.py
tests/test_runner_apps/databases/tests.py
import unittest class NoDatabaseTests(unittest.TestCase): def test_nothing(self): pass class DefaultDatabaseTests(NoDatabaseTests): databases = {"default"} class DefaultDatabaseSerializedTests(NoDatabaseTests): databases = {"default"} serialized_rollback = True class OtherDatabaseTests(NoDatabaseTests): databases = {"other"} class AllDatabasesTests(NoDatabaseTests): databases = "__all__"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/simple/__init__.py
tests/test_runner_apps/simple/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/simple/tests.py
tests/test_runner_apps/simple/tests.py
from unittest import TestCase from django.test import SimpleTestCase from django.test import TestCase as DjangoTestCase class DjangoCase1(DjangoTestCase): def test_1(self): pass def test_2(self): pass class DjangoCase2(DjangoTestCase): def test_1(self): pass def test_2(self): pass class SimpleCase1(SimpleTestCase): def test_1(self): pass def test_2(self): pass class SimpleCase2(SimpleTestCase): def test_1(self): pass def test_2(self): pass class UnittestCase1(TestCase): def test_1(self): pass def test_2(self): pass class UnittestCase2(TestCase): def test_1(self): pass def test_2(self): pass def test_3_test(self): pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/tagged/tests_inheritance.py
tests/test_runner_apps/tagged/tests_inheritance.py
from unittest import TestCase from django.test import tag @tag("foo") class FooBase(TestCase): pass class Foo(FooBase): def test_no_new_tags(self): pass @tag("baz") def test_new_func_tag(self): pass @tag("bar") class FooBar(FooBase): def test_new_class_tag_only(self): pass @tag("baz") def test_new_class_and_func_tags(self): pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/tagged/tests_syntax_error.py
tests/test_runner_apps/tagged/tests_syntax_error.py
from unittest import TestCase from django.test import tag @tag('syntax_error') class SyntaxErrorTestCase(TestCase): pass 1syntax_error # NOQA
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/tagged/__init__.py
tests/test_runner_apps/tagged/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/tagged/tests.py
tests/test_runner_apps/tagged/tests.py
from unittest import TestCase from django.test import tag @tag("slow") class TaggedTestCase(TestCase): @tag("fast") def test_single_tag(self): self.assertEqual(1, 1) @tag("fast", "core") def test_multiple_tags(self): self.assertEqual(1, 1)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/sample/doctests.py
tests/test_runner_apps/sample/doctests.py
""" Doctest example from the official Python documentation. https://docs.python.org/library/doctest.html """ def factorial(n): """Return the factorial of n, an exact integer >= 0. >>> [factorial(n) for n in range(6)] [1, 1, 2, 6, 24, 120] >>> factorial(30) # doctest: +ELLIPSIS 265252859812191058636308480000000... >>> factorial(-1) Traceback (most recent call last): ... ValueError: n must be >= 0 Factorials of floats are OK, but the float must be an exact integer: >>> factorial(30.1) Traceback (most recent call last): ... ValueError: n must be exact integer >>> factorial(30.0) # doctest: +ELLIPSIS 265252859812191058636308480000000... It must also not be ridiculously large: >>> factorial(1e100) Traceback (most recent call last): ... OverflowError: n too large """ import math if not n >= 0: raise ValueError("n must be >= 0") if math.floor(n) != n: raise ValueError("n must be exact integer") if n + 1 == n: # catch a value like 1e300 raise OverflowError("n too large") result = 1 factor = 2 while factor <= n: result *= factor factor += 1 return result
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/sample/tests_sample.py
tests/test_runner_apps/sample/tests_sample.py
import doctest from unittest import TestCase from django.test import SimpleTestCase from django.test import TestCase as DjangoTestCase from . import doctests class TestVanillaUnittest(TestCase): def test_sample(self): self.assertEqual(1, 1) class TestDjangoTestCase(DjangoTestCase): def test_sample(self): self.assertEqual(1, 1) class TestZimpleTestCase(SimpleTestCase): # Z is used to trick this test case to appear after Vanilla in default # suite def test_sample(self): self.assertEqual(1, 1) class EmptyTestCase(TestCase): pass def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(doctests)) return tests
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/sample/__init__.py
tests/test_runner_apps/sample/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/sample/empty.py
tests/test_runner_apps/sample/empty.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/sample/pattern_tests.py
tests/test_runner_apps/sample/pattern_tests.py
from unittest import TestCase class Test(TestCase): def test_sample(self): self.assertEqual(1, 1)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/sample/tests/__init__.py
tests/test_runner_apps/sample/tests/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/sample/tests/tests.py
tests/test_runner_apps/sample/tests/tests.py
from unittest import TestCase class Test(TestCase): def test_sample(self): pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_runner_apps/buffer/tests_buffer.py
tests/test_runner_apps/buffer/tests_buffer.py
import sys from unittest import TestCase class WriteToStdoutStderrTestCase(TestCase): def test_pass(self): sys.stderr.write("Write to stderr.") sys.stdout.write("Write to stdout.") self.assertTrue(True) def test_fail(self): sys.stderr.write("Write to stderr.") sys.stdout.write("Write to stdout.") self.assertTrue(False)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/null_fk_ordering/models.py
tests/null_fk_ordering/models.py
""" Regression tests for proper working of ForeignKey(null=True). Tests these bugs: * #7512: including a nullable foreign key reference in Meta ordering has unexpected results """ from django.db import models # The first two models represent a very simple null FK ordering case. class Author(models.Model): name = models.CharField(max_length=150) class Article(models.Model): title = models.CharField(max_length=150) author = models.ForeignKey(Author, models.SET_NULL, null=True) class Meta: ordering = ["author__name"] # These following 4 models represent a far more complex ordering case. class SystemInfo(models.Model): system_name = models.CharField(max_length=32) class Forum(models.Model): system_info = models.ForeignKey(SystemInfo, models.CASCADE) forum_name = models.CharField(max_length=32) class Post(models.Model): forum = models.ForeignKey(Forum, models.SET_NULL, null=True) title = models.CharField(max_length=32) class Comment(models.Model): post = models.ForeignKey(Post, models.SET_NULL, null=True) comment_text = models.CharField(max_length=250) class Meta: ordering = ["post__forum__system_info__system_name", "comment_text"]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/null_fk_ordering/__init__.py
tests/null_fk_ordering/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/null_fk_ordering/tests.py
tests/null_fk_ordering/tests.py
from django.test import TestCase from .models import Article, Author, Comment, Forum, Post, SystemInfo class NullFkOrderingTests(TestCase): def test_ordering_across_null_fk(self): """ Regression test for #7512 ordering across nullable Foreign Keys shouldn't exclude results """ author_1 = Author.objects.create(name="Tom Jones") author_2 = Author.objects.create(name="Bob Smith") Article.objects.create(title="No author on this article") Article.objects.create( author=author_1, title="This article written by Tom Jones" ) Article.objects.create( author=author_2, title="This article written by Bob Smith" ) # We can't compare results directly (since different databases sort # NULLs to different ends of the ordering), but we can check that all # results are returned. self.assertEqual(len(list(Article.objects.all())), 3) s = SystemInfo.objects.create(system_name="System Info") f = Forum.objects.create(system_info=s, forum_name="First forum") p = Post.objects.create(forum=f, title="First Post") Comment.objects.create(post=p, comment_text="My first comment") Comment.objects.create(comment_text="My second comment") s2 = SystemInfo.objects.create(system_name="More System Info") f2 = Forum.objects.create(system_info=s2, forum_name="Second forum") p2 = Post.objects.create(forum=f2, title="Second Post") Comment.objects.create(comment_text="Another first comment") Comment.objects.create(post=p2, comment_text="Another second comment") # We have to test this carefully. Some databases sort NULL values # before everything else, some sort them afterward. So we extract the # ordered list and check the length. Before the fix, this list was too # short (some values were omitted). self.assertEqual(len(list(Comment.objects.all())), 4)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/aggregation/models.py
tests/aggregation/models.py
from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() friends = models.ManyToManyField("self", blank=True) rating = models.FloatField(null=True) def __str__(self): return self.name class Publisher(models.Model): name = models.CharField(max_length=255) num_awards = models.IntegerField() duration = models.DurationField(blank=True, null=True) def __str__(self): return self.name class Book(models.Model): isbn = models.CharField(max_length=9) name = models.CharField(max_length=255) pages = models.IntegerField() rating = models.FloatField() price = models.DecimalField(decimal_places=2, max_digits=6) authors = models.ManyToManyField(Author) contact = models.ForeignKey(Author, models.CASCADE, related_name="book_contact_set") publisher = models.ForeignKey(Publisher, models.CASCADE) pubdate = models.DateField() def __str__(self): return self.name class Store(models.Model): name = models.CharField(max_length=255) books = models.ManyToManyField(Book) original_opening = models.DateTimeField() friday_night_closing = models.TimeField() def __str__(self): return self.name class Employee(models.Model): work_day_preferences = models.JSONField() class Meta: required_db_features = {"supports_json_field"}
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/aggregation/__init__.py
tests/aggregation/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/aggregation/test_filter_argument.py
tests/aggregation/test_filter_argument.py
import datetime from decimal import Decimal from django.db.models import ( Avg, Case, Count, Exists, F, Max, OuterRef, Q, StdDev, Subquery, Sum, Variance, When, ) from django.test import TestCase from django.test.utils import Approximate from .models import Author, Book, Publisher class FilteredAggregateTests(TestCase): @classmethod def setUpTestData(cls): cls.a1 = Author.objects.create(name="test", age=40) cls.a2 = Author.objects.create(name="test2", age=60) cls.a3 = Author.objects.create(name="test3", age=100) cls.p1 = Publisher.objects.create( name="Apress", num_awards=3, duration=datetime.timedelta(days=1) ) cls.b1 = Book.objects.create( isbn="159059725", name="The Definitive Guide to Django: Web Development Done Right", pages=447, rating=4.5, price=Decimal("30.00"), contact=cls.a1, publisher=cls.p1, pubdate=datetime.date(2007, 12, 6), ) cls.b2 = Book.objects.create( isbn="067232959", name="Sams Teach Yourself Django in 24 Hours", pages=528, rating=3.0, price=Decimal("23.09"), contact=cls.a2, publisher=cls.p1, pubdate=datetime.date(2008, 3, 3), ) cls.b3 = Book.objects.create( isbn="159059996", name="Practical Django Projects", pages=600, rating=4.5, price=Decimal("29.69"), contact=cls.a3, publisher=cls.p1, pubdate=datetime.date(2008, 6, 23), ) cls.a1.friends.add(cls.a2) cls.a1.friends.add(cls.a3) cls.b1.authors.add(cls.a1) cls.b1.authors.add(cls.a3) cls.b2.authors.add(cls.a2) cls.b3.authors.add(cls.a3) def test_filtered_aggregates(self): agg = Sum("age", filter=Q(name__startswith="test")) self.assertEqual(Author.objects.aggregate(age=agg)["age"], 200) def test_filtered_numerical_aggregates(self): for aggregate, expected_result in ( (Avg, Approximate(66.7, 1)), (StdDev, Approximate(24.9, 1)), (Variance, Approximate(622.2, 1)), ): with self.subTest(aggregate=aggregate.__name__): agg = aggregate("age", filter=Q(name__startswith="test")) self.assertEqual( Author.objects.aggregate(age=agg)["age"], expected_result ) def test_empty_filtered_aggregates(self): agg = Count("pk", filter=Q()) self.assertEqual(Author.objects.aggregate(count=agg)["count"], 3) def test_empty_filtered_aggregates_with_annotation(self): agg = Count("pk", filter=Q()) self.assertEqual( Author.objects.annotate( age_annotation=F("age"), ).aggregate( count=agg )["count"], 3, ) def test_double_filtered_aggregates(self): agg = Sum("age", filter=Q(Q(name="test2") & ~Q(name="test"))) self.assertEqual(Author.objects.aggregate(age=agg)["age"], 60) def test_excluded_aggregates(self): agg = Sum("age", filter=~Q(name="test2")) self.assertEqual(Author.objects.aggregate(age=agg)["age"], 140) def test_related_aggregates_m2m(self): agg = Sum("friends__age", filter=~Q(friends__name="test")) self.assertEqual( Author.objects.filter(name="test").aggregate(age=agg)["age"], 160 ) def test_related_aggregates_m2m_and_fk(self): q = Q(friends__book__publisher__name="Apress") & ~Q(friends__name="test3") agg = Sum("friends__book__pages", filter=q) self.assertEqual( Author.objects.filter(name="test").aggregate(pages=agg)["pages"], 528 ) def test_plain_annotate(self): agg = Sum("book__pages", filter=Q(book__rating__gt=3)) qs = Author.objects.annotate(pages=agg).order_by("pk") self.assertSequenceEqual([a.pages for a in qs], [447, None, 1047]) def test_filtered_aggregate_on_annotate(self): pages_annotate = Sum("book__pages", filter=Q(book__rating__gt=3)) age_agg = Sum("age", filter=Q(total_pages__gte=400)) aggregated = Author.objects.annotate(total_pages=pages_annotate).aggregate( summed_age=age_agg ) self.assertEqual(aggregated, {"summed_age": 140}) def test_case_aggregate(self): agg = Sum( Case(When(friends__age=40, then=F("friends__age"))), filter=Q(friends__name__startswith="test"), ) self.assertEqual(Author.objects.aggregate(age=agg)["age"], 80) def test_sum_star_exception(self): msg = "Star cannot be used with filter. Please specify a field." with self.assertRaisesMessage(ValueError, msg): Count("*", filter=Q(age=40)) def test_filtered_reused_subquery(self): qs = Author.objects.annotate( older_friends_count=Count("friends", filter=Q(friends__age__gt=F("age"))), ).filter( older_friends_count__gte=2, ) self.assertEqual(qs.get(pk__in=qs.values("pk")), self.a1) def test_filtered_aggregate_ref_annotation(self): aggs = Author.objects.annotate(double_age=F("age") * 2).aggregate( cnt=Count("pk", filter=Q(double_age__gt=100)), ) self.assertEqual(aggs["cnt"], 2) def test_filtered_aggregate_ref_subquery_annotation(self): aggs = Author.objects.annotate( earliest_book_year=Subquery( Book.objects.filter( contact__pk=OuterRef("pk"), ) .order_by("pubdate") .values("pubdate__year")[:1] ), ).aggregate( cnt=Count("pk", filter=Q(earliest_book_year=2008)), ) self.assertEqual(aggs["cnt"], 2) def test_filtered_aggregate_ref_multiple_subquery_annotation(self): aggregate = ( Book.objects.values("publisher") .annotate( has_authors=Exists( Book.authors.through.objects.filter(book=OuterRef("pk")), ), authors_have_other_books=Exists( Book.objects.filter( authors__in=Author.objects.filter( book_contact_set=OuterRef(OuterRef("pk")), ) ).exclude(pk=OuterRef("pk")), ), ) .aggregate( max_rating=Max( "rating", filter=Q(has_authors=True, authors_have_other_books=False), ) ) ) self.assertEqual(aggregate, {"max_rating": 4.5}) def test_filtered_aggregrate_ref_in_subquery_annotation(self): aggs = ( Author.objects.annotate( count=Subquery( Book.objects.annotate( weird_count=Count( "pk", filter=Q(pages=OuterRef("age")), ) ).values("weird_count")[:1] ), ) .order_by("pk") .aggregate(sum=Sum("count")) ) self.assertEqual(aggs["sum"], 0) def test_filtered_aggregate_on_exists(self): aggregate = Book.objects.values("publisher").aggregate( max_rating=Max( "rating", filter=Exists( Book.authors.through.objects.filter(book=OuterRef("pk")), ), ), ) self.assertEqual(aggregate, {"max_rating": 4.5}) def test_filtered_aggregate_empty_condition(self): book = Book.objects.annotate( authors_count=Count( "authors", filter=Q(authors__in=[]), ), ).get(pk=self.b1.pk) self.assertEqual(book.authors_count, 0) aggregate = Book.objects.aggregate( max_rating=Max("rating", filter=Q(rating__in=[])) ) self.assertEqual(aggregate, {"max_rating": None}) def test_filtered_aggregate_full_condition(self): book = Book.objects.annotate( authors_count=Count( "authors", filter=~Q(authors__in=[]), ), ).get(pk=self.b1.pk) self.assertEqual(book.authors_count, 2) aggregate = Book.objects.aggregate( max_rating=Max("rating", filter=~Q(rating__in=[])) ) self.assertEqual(aggregate, {"max_rating": 4.5})
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/aggregation/tests.py
tests/aggregation/tests.py
import datetime import math import re from decimal import Decimal from django.core.exceptions import FieldError from django.db import NotSupportedError, connection from django.db.models import ( AnyValue, Avg, Case, CharField, Count, DateField, DateTimeField, DecimalField, DurationField, Exists, F, FloatField, IntegerField, Max, Min, OuterRef, Q, StdDev, StringAgg, Subquery, Sum, TimeField, Transform, Value, Variance, When, Window, ) from django.db.models.expressions import Func, RawSQL from django.db.models.fields.json import KeyTextTransform from django.db.models.functions import ( Cast, Coalesce, Concat, Greatest, Least, Lower, Mod, Now, Pi, TruncDate, TruncHour, ) from django.test import TestCase from django.test.testcases import skipIfDBFeature, skipUnlessDBFeature from django.test.utils import Approximate, CaptureQueriesContext from django.utils import timezone from .models import Author, Book, Employee, Publisher, Store class NowUTC(Now): template = "CURRENT_TIMESTAMP" output_field = DateTimeField() def as_sql(self, compiler, connection, **extra_context): if connection.features.test_now_utc_template: extra_context["template"] = connection.features.test_now_utc_template return super().as_sql(compiler, connection, **extra_context) class AggregateTestCase(TestCase): @classmethod def setUpTestData(cls): cls.a1 = Author.objects.create(name="Adrian Holovaty", age=34) cls.a2 = Author.objects.create(name="Jacob Kaplan-Moss", age=35) cls.a3 = Author.objects.create(name="Brad Dayley", age=45) cls.a4 = Author.objects.create(name="James Bennett", age=29) cls.a5 = Author.objects.create(name="Jeffrey Forcier", age=37) cls.a6 = Author.objects.create(name="Paul Bissex", age=29) cls.a7 = Author.objects.create(name="Wesley J. Chun", age=25) cls.a8 = Author.objects.create(name="Peter Norvig", age=57) cls.a9 = Author.objects.create(name="Stuart Russell", age=46) cls.a1.friends.add(cls.a2, cls.a4) cls.a2.friends.add(cls.a1, cls.a7) cls.a4.friends.add(cls.a1) cls.a5.friends.add(cls.a6, cls.a7) cls.a6.friends.add(cls.a5, cls.a7) cls.a7.friends.add(cls.a2, cls.a5, cls.a6) cls.a8.friends.add(cls.a9) cls.a9.friends.add(cls.a8) cls.p1 = Publisher.objects.create( name="Apress", num_awards=3, duration=datetime.timedelta(days=1) ) cls.p2 = Publisher.objects.create( name="Sams", num_awards=1, duration=datetime.timedelta(days=2) ) cls.p3 = Publisher.objects.create(name="Prentice Hall", num_awards=7) cls.p4 = Publisher.objects.create(name="Morgan Kaufmann", num_awards=9) cls.p5 = Publisher.objects.create(name="Jonno's House of Books", num_awards=0) cls.b1 = Book.objects.create( isbn="159059725", name="The Definitive Guide to Django: Web Development Done Right", pages=447, rating=4.5, price=Decimal("30.00"), contact=cls.a1, publisher=cls.p1, pubdate=datetime.date(2007, 12, 6), ) cls.b2 = Book.objects.create( isbn="067232959", name="Sams Teach Yourself Django in 24 Hours", pages=528, rating=3.0, price=Decimal("23.09"), contact=cls.a3, publisher=cls.p2, pubdate=datetime.date(2008, 3, 3), ) cls.b3 = Book.objects.create( isbn="159059996", name="Practical Django Projects", pages=300, rating=4.0, price=Decimal("29.69"), contact=cls.a4, publisher=cls.p1, pubdate=datetime.date(2008, 6, 23), ) cls.b4 = Book.objects.create( isbn="013235613", name="Python Web Development with Django", pages=350, rating=4.0, price=Decimal("29.69"), contact=cls.a5, publisher=cls.p3, pubdate=datetime.date(2008, 11, 3), ) cls.b5 = Book.objects.create( isbn="013790395", name="Artificial Intelligence: A Modern Approach", pages=1132, rating=4.0, price=Decimal("82.80"), contact=cls.a8, publisher=cls.p3, pubdate=datetime.date(1995, 1, 15), ) cls.b6 = Book.objects.create( isbn="155860191", name=( "Paradigms of Artificial Intelligence Programming: Case Studies in " "Common Lisp" ), pages=946, rating=5.0, price=Decimal("75.00"), contact=cls.a8, publisher=cls.p4, pubdate=datetime.date(1991, 10, 15), ) cls.b1.authors.add(cls.a1, cls.a2) cls.b2.authors.add(cls.a3) cls.b3.authors.add(cls.a4) cls.b4.authors.add(cls.a5, cls.a6, cls.a7) cls.b5.authors.add(cls.a8, cls.a9) cls.b6.authors.add(cls.a8) s1 = Store.objects.create( name="Amazon.com", original_opening=datetime.datetime(1994, 4, 23, 9, 17, 42), friday_night_closing=datetime.time(23, 59, 59), ) s2 = Store.objects.create( name="Books.com", original_opening=datetime.datetime(2001, 3, 15, 11, 23, 37), friday_night_closing=datetime.time(23, 59, 59), ) s3 = Store.objects.create( name="Mamma and Pappa's Books", original_opening=datetime.datetime(1945, 4, 25, 16, 24, 14), friday_night_closing=datetime.time(21, 30), ) s1.books.add(cls.b1, cls.b2, cls.b3, cls.b4, cls.b5, cls.b6) s2.books.add(cls.b1, cls.b3, cls.b5, cls.b6) s3.books.add(cls.b3, cls.b4, cls.b6) def test_empty_aggregate(self): self.assertEqual(Author.objects.aggregate(), {}) def test_aggregate_in_order_by(self): msg = ( "Using an aggregate in order_by() without also including it in " "annotate() is not allowed: Avg(F(book__rating)" ) with self.assertRaisesMessage(FieldError, msg): Author.objects.values("age").order_by(Avg("book__rating")) def test_single_aggregate(self): vals = Author.objects.aggregate(Avg("age")) self.assertEqual(vals, {"age__avg": Approximate(37.4, places=1)}) def test_multiple_aggregates(self): vals = Author.objects.aggregate(Sum("age"), Avg("age")) self.assertEqual( vals, {"age__sum": 337, "age__avg": Approximate(37.4, places=1)} ) def test_filter_aggregate(self): vals = Author.objects.filter(age__gt=29).aggregate(Sum("age")) self.assertEqual(vals, {"age__sum": 254}) def test_related_aggregate(self): vals = Author.objects.aggregate(Avg("friends__age")) self.assertEqual(vals, {"friends__age__avg": Approximate(34.07, places=2)}) vals = Book.objects.filter(rating__lt=4.5).aggregate(Avg("authors__age")) self.assertEqual(vals, {"authors__age__avg": Approximate(38.2857, places=2)}) vals = Author.objects.filter(name__contains="a").aggregate(Avg("book__rating")) self.assertEqual(vals, {"book__rating__avg": 4.0}) vals = Book.objects.aggregate(Sum("publisher__num_awards")) self.assertEqual(vals, {"publisher__num_awards__sum": 30}) vals = Publisher.objects.aggregate(Sum("book__price")) self.assertEqual(vals, {"book__price__sum": Decimal("270.27")}) def test_aggregate_multi_join(self): vals = Store.objects.aggregate(Max("books__authors__age")) self.assertEqual(vals, {"books__authors__age__max": 57}) vals = Author.objects.aggregate(Min("book__publisher__num_awards")) self.assertEqual(vals, {"book__publisher__num_awards__min": 1}) def test_aggregate_alias(self): vals = Store.objects.filter(name="Amazon.com").aggregate( amazon_mean=Avg("books__rating") ) self.assertEqual(vals, {"amazon_mean": Approximate(4.08, places=2)}) def test_aggregate_transform(self): vals = Store.objects.aggregate(min_month=Min("original_opening__month")) self.assertEqual(vals, {"min_month": 3}) def test_aggregate_join_transform(self): vals = Publisher.objects.aggregate(min_year=Min("book__pubdate__year")) self.assertEqual(vals, {"min_year": 1991}) def test_annotate_basic(self): self.assertQuerySetEqual( Book.objects.annotate().order_by("pk"), [ "The Definitive Guide to Django: Web Development Done Right", "Sams Teach Yourself Django in 24 Hours", "Practical Django Projects", "Python Web Development with Django", "Artificial Intelligence: A Modern Approach", "Paradigms of Artificial Intelligence Programming: Case Studies in " "Common Lisp", ], lambda b: b.name, ) books = Book.objects.annotate(mean_age=Avg("authors__age")) b = books.get(pk=self.b1.pk) self.assertEqual( b.name, "The Definitive Guide to Django: Web Development Done Right" ) self.assertEqual(b.mean_age, 34.5) def test_annotate_defer(self): qs = ( Book.objects.annotate(page_sum=Sum("pages")) .defer("name") .filter(pk=self.b1.pk) ) rows = [ ( self.b1.id, "159059725", 447, "The Definitive Guide to Django: Web Development Done Right", ) ] self.assertQuerySetEqual( qs.order_by("pk"), rows, lambda r: (r.id, r.isbn, r.page_sum, r.name) ) def test_annotate_defer_select_related(self): qs = ( Book.objects.select_related("contact") .annotate(page_sum=Sum("pages")) .defer("name") .filter(pk=self.b1.pk) ) rows = [ ( self.b1.id, "159059725", 447, "Adrian Holovaty", "The Definitive Guide to Django: Web Development Done Right", ) ] self.assertQuerySetEqual( qs.order_by("pk"), rows, lambda r: (r.id, r.isbn, r.page_sum, r.contact.name, r.name), ) def test_annotate_m2m(self): books = ( Book.objects.filter(rating__lt=4.5) .annotate(Avg("authors__age")) .order_by("name") ) self.assertQuerySetEqual( books, [ ("Artificial Intelligence: A Modern Approach", 51.5), ("Practical Django Projects", 29.0), ("Python Web Development with Django", Approximate(30.3, places=1)), ("Sams Teach Yourself Django in 24 Hours", 45.0), ], lambda b: (b.name, b.authors__age__avg), ) books = Book.objects.annotate(num_authors=Count("authors")).order_by("name") self.assertQuerySetEqual( books, [ ("Artificial Intelligence: A Modern Approach", 2), ( "Paradigms of Artificial Intelligence Programming: Case Studies in " "Common Lisp", 1, ), ("Practical Django Projects", 1), ("Python Web Development with Django", 3), ("Sams Teach Yourself Django in 24 Hours", 1), ("The Definitive Guide to Django: Web Development Done Right", 2), ], lambda b: (b.name, b.num_authors), ) def test_backwards_m2m_annotate(self): authors = ( Author.objects.filter(name__contains="a") .annotate(Avg("book__rating")) .order_by("name") ) self.assertQuerySetEqual( authors, [ ("Adrian Holovaty", 4.5), ("Brad Dayley", 3.0), ("Jacob Kaplan-Moss", 4.5), ("James Bennett", 4.0), ("Paul Bissex", 4.0), ("Stuart Russell", 4.0), ], lambda a: (a.name, a.book__rating__avg), ) authors = Author.objects.annotate(num_books=Count("book")).order_by("name") self.assertQuerySetEqual( authors, [ ("Adrian Holovaty", 1), ("Brad Dayley", 1), ("Jacob Kaplan-Moss", 1), ("James Bennett", 1), ("Jeffrey Forcier", 1), ("Paul Bissex", 1), ("Peter Norvig", 2), ("Stuart Russell", 1), ("Wesley J. Chun", 1), ], lambda a: (a.name, a.num_books), ) def test_reverse_fkey_annotate(self): books = Book.objects.annotate(Sum("publisher__num_awards")).order_by("name") self.assertQuerySetEqual( books, [ ("Artificial Intelligence: A Modern Approach", 7), ( "Paradigms of Artificial Intelligence Programming: Case Studies in " "Common Lisp", 9, ), ("Practical Django Projects", 3), ("Python Web Development with Django", 7), ("Sams Teach Yourself Django in 24 Hours", 1), ("The Definitive Guide to Django: Web Development Done Right", 3), ], lambda b: (b.name, b.publisher__num_awards__sum), ) publishers = Publisher.objects.annotate(Sum("book__price")).order_by("name") self.assertQuerySetEqual( publishers, [ ("Apress", Decimal("59.69")), ("Jonno's House of Books", None), ("Morgan Kaufmann", Decimal("75.00")), ("Prentice Hall", Decimal("112.49")), ("Sams", Decimal("23.09")), ], lambda p: (p.name, p.book__price__sum), ) def test_annotate_values(self): books = list( Book.objects.filter(pk=self.b1.pk) .annotate(mean_age=Avg("authors__age")) .values() ) self.assertEqual( books, [ { "contact_id": self.a1.id, "id": self.b1.id, "isbn": "159059725", "mean_age": 34.5, "name": ( "The Definitive Guide to Django: Web Development Done Right" ), "pages": 447, "price": Approximate(Decimal("30")), "pubdate": datetime.date(2007, 12, 6), "publisher_id": self.p1.id, "rating": 4.5, } ], ) books = ( Book.objects.filter(pk=self.b1.pk) .annotate(mean_age=Avg("authors__age")) .values("pk", "isbn", "mean_age") ) self.assertEqual( list(books), [ { "pk": self.b1.pk, "isbn": "159059725", "mean_age": 34.5, } ], ) books = ( Book.objects.filter(pk=self.b1.pk) .annotate(mean_age=Avg("authors__age")) .values("name") ) self.assertEqual( list(books), [{"name": "The Definitive Guide to Django: Web Development Done Right"}], ) books = ( Book.objects.filter(pk=self.b1.pk) .values() .annotate(mean_age=Avg("authors__age")) ) self.assertEqual( list(books), [ { "contact_id": self.a1.id, "id": self.b1.id, "isbn": "159059725", "mean_age": 34.5, "name": ( "The Definitive Guide to Django: Web Development Done Right" ), "pages": 447, "price": Approximate(Decimal("30")), "pubdate": datetime.date(2007, 12, 6), "publisher_id": self.p1.id, "rating": 4.5, } ], ) books = ( Book.objects.values("rating") .annotate(n_authors=Count("authors__id"), mean_age=Avg("authors__age")) .order_by("rating") ) self.assertEqual( list(books), [ { "rating": 3.0, "n_authors": 1, "mean_age": 45.0, }, { "rating": 4.0, "n_authors": 6, "mean_age": Approximate(37.16, places=1), }, { "rating": 4.5, "n_authors": 2, "mean_age": 34.5, }, { "rating": 5.0, "n_authors": 1, "mean_age": 57.0, }, ], ) authors = Author.objects.annotate(Avg("friends__age")).order_by("name") self.assertQuerySetEqual( authors, [ ("Adrian Holovaty", 32.0), ("Brad Dayley", None), ("Jacob Kaplan-Moss", 29.5), ("James Bennett", 34.0), ("Jeffrey Forcier", 27.0), ("Paul Bissex", 31.0), ("Peter Norvig", 46.0), ("Stuart Russell", 57.0), ("Wesley J. Chun", Approximate(33.66, places=1)), ], lambda a: (a.name, a.friends__age__avg), ) def test_count(self): vals = Book.objects.aggregate(Count("rating")) self.assertEqual(vals, {"rating__count": 6}) def test_count_star(self): with self.assertNumQueries(1) as ctx: Book.objects.aggregate(n=Count("*")) sql = ctx.captured_queries[0]["sql"] self.assertIn("SELECT COUNT(*) ", sql) def test_count_distinct_expression(self): aggs = Book.objects.aggregate( distinct_ratings=Count( Case(When(pages__gt=300, then="rating")), distinct=True ), ) self.assertEqual(aggs["distinct_ratings"], 4) def test_distinct_on_aggregate(self): for aggregate, expected_result in ( (Avg, 4.125), (Count, 4), (Sum, 16.5), ): with self.subTest(aggregate=aggregate.__name__): books = Book.objects.aggregate( ratings=aggregate("rating", distinct=True) ) self.assertEqual(books["ratings"], expected_result) @skipUnlessDBFeature("supports_aggregate_distinct_multiple_argument") def test_distinct_on_stringagg(self): books = Book.objects.aggregate( ratings=StringAgg(Cast(F("rating"), CharField()), Value(","), distinct=True) ) self.assertCountEqual(books["ratings"].split(","), ["3", "4", "4.5", "5"]) @skipIfDBFeature("supports_aggregate_distinct_multiple_argument") def test_raises_error_on_multiple_argument_distinct(self): message = ( "StringAgg does not support distinct with multiple expressions on this " "database backend." ) with self.assertRaisesMessage(NotSupportedError, message): Book.objects.aggregate( ratings=StringAgg( Cast(F("rating"), CharField()), Value(","), distinct=True, ) ) def test_non_grouped_annotation_not_in_group_by(self): """ An annotation not included in values() before an aggregate should be excluded from the group by clause. """ qs = ( Book.objects.annotate(xprice=F("price")) .filter(rating=4.0) .values("rating") .annotate(count=Count("publisher_id", distinct=True)) .values("count", "rating") .order_by("count") ) self.assertEqual(list(qs), [{"rating": 4.0, "count": 2}]) def test_grouped_annotation_in_group_by(self): """ An annotation included in values() before an aggregate should be included in the group by clause. """ qs = ( Book.objects.annotate(xprice=F("price")) .filter(rating=4.0) .values("rating", "xprice") .annotate(count=Count("publisher_id", distinct=True)) .values("count", "rating") .order_by("count") ) self.assertEqual( list(qs), [ {"rating": 4.0, "count": 1}, {"rating": 4.0, "count": 2}, ], ) def test_fkey_aggregate(self): explicit = list(Author.objects.annotate(Count("book__id"))) implicit = list(Author.objects.annotate(Count("book"))) self.assertCountEqual(explicit, implicit) def test_annotate_ordering(self): books = ( Book.objects.values("rating") .annotate(oldest=Max("authors__age")) .order_by("oldest", "rating") ) self.assertEqual( list(books), [ {"rating": 4.5, "oldest": 35}, {"rating": 3.0, "oldest": 45}, {"rating": 4.0, "oldest": 57}, {"rating": 5.0, "oldest": 57}, ], ) books = ( Book.objects.values("rating") .annotate(oldest=Max("authors__age")) .order_by("-oldest", "-rating") ) self.assertEqual( list(books), [ {"rating": 5.0, "oldest": 57}, {"rating": 4.0, "oldest": 57}, {"rating": 3.0, "oldest": 45}, {"rating": 4.5, "oldest": 35}, ], ) def test_aggregate_annotation(self): vals = Book.objects.annotate(num_authors=Count("authors__id")).aggregate( Avg("num_authors") ) self.assertEqual(vals, {"num_authors__avg": Approximate(1.66, places=1)}) def test_avg_duration_field(self): # Explicit `output_field`. self.assertEqual( Publisher.objects.aggregate(Avg("duration", output_field=DurationField())), {"duration__avg": datetime.timedelta(days=1, hours=12)}, ) # Implicit `output_field`. self.assertEqual( Publisher.objects.aggregate(Avg("duration")), {"duration__avg": datetime.timedelta(days=1, hours=12)}, ) def test_sum_duration_field(self): self.assertEqual( Publisher.objects.aggregate(Sum("duration", output_field=DurationField())), {"duration__sum": datetime.timedelta(days=3)}, ) def test_sum_distinct_aggregate(self): """ Sum on a distinct() QuerySet should aggregate only the distinct items. """ authors = Author.objects.filter(book__in=[self.b5, self.b6]) self.assertEqual(authors.count(), 3) distinct_authors = authors.distinct() self.assertEqual(distinct_authors.count(), 2) # Selected author ages are 57 and 46 age_sum = distinct_authors.aggregate(Sum("age")) self.assertEqual(age_sum["age__sum"], 103) def test_filtering(self): p = Publisher.objects.create(name="Expensive Publisher", num_awards=0) Book.objects.create( name="ExpensiveBook1", pages=1, isbn="111", rating=3.5, price=Decimal("1000"), publisher=p, contact_id=self.a1.id, pubdate=datetime.date(2008, 12, 1), ) Book.objects.create( name="ExpensiveBook2", pages=1, isbn="222", rating=4.0, price=Decimal("1000"), publisher=p, contact_id=self.a1.id, pubdate=datetime.date(2008, 12, 2), ) Book.objects.create( name="ExpensiveBook3", pages=1, isbn="333", rating=4.5, price=Decimal("35"), publisher=p, contact_id=self.a1.id, pubdate=datetime.date(2008, 12, 3), ) publishers = ( Publisher.objects.annotate(num_books=Count("book__id")) .filter(num_books__gt=1) .order_by("pk") ) self.assertQuerySetEqual( publishers, ["Apress", "Prentice Hall", "Expensive Publisher"], lambda p: p.name, ) publishers = Publisher.objects.filter(book__price__lt=Decimal("40.0")).order_by( "pk" ) self.assertQuerySetEqual( publishers, [ "Apress", "Apress", "Sams", "Prentice Hall", "Expensive Publisher", ], lambda p: p.name, ) publishers = ( Publisher.objects.annotate(num_books=Count("book__id")) .filter(num_books__gt=1, book__price__lt=Decimal("40.0")) .order_by("pk") ) self.assertQuerySetEqual( publishers, ["Apress", "Prentice Hall", "Expensive Publisher"], lambda p: p.name, ) publishers = ( Publisher.objects.filter(book__price__lt=Decimal("40.0")) .annotate(num_books=Count("book__id")) .filter(num_books__gt=1) .order_by("pk") ) self.assertQuerySetEqual(publishers, ["Apress"], lambda p: p.name) publishers = ( Publisher.objects.annotate(num_books=Count("book")) .filter(num_books__range=[1, 3]) .order_by("pk") ) self.assertQuerySetEqual( publishers, [ "Apress", "Sams", "Prentice Hall", "Morgan Kaufmann", "Expensive Publisher", ], lambda p: p.name, ) publishers = ( Publisher.objects.annotate(num_books=Count("book")) .filter(num_books__range=[1, 2]) .order_by("pk") ) self.assertQuerySetEqual( publishers, ["Apress", "Sams", "Prentice Hall", "Morgan Kaufmann"], lambda p: p.name, ) publishers = ( Publisher.objects.annotate(num_books=Count("book")) .filter(num_books__in=[1, 3]) .order_by("pk") ) self.assertQuerySetEqual( publishers, ["Sams", "Morgan Kaufmann", "Expensive Publisher"], lambda p: p.name, ) publishers = Publisher.objects.annotate(num_books=Count("book")).filter( num_books__isnull=True ) self.assertEqual(len(publishers), 0) def test_annotation(self): vals = Author.objects.filter(pk=self.a1.pk).aggregate(Count("friends__id")) self.assertEqual(vals, {"friends__id__count": 2}) books = ( Book.objects.annotate(num_authors=Count("authors__name")) .filter(num_authors__exact=2) .order_by("pk") ) self.assertQuerySetEqual( books, [ "The Definitive Guide to Django: Web Development Done Right", "Artificial Intelligence: A Modern Approach", ], lambda b: b.name, ) authors = ( Author.objects.annotate(num_friends=Count("friends__id", distinct=True)) .filter(num_friends=0) .order_by("pk") ) self.assertQuerySetEqual(authors, ["Brad Dayley"], lambda a: a.name) publishers = ( Publisher.objects.annotate(num_books=Count("book__id")) .filter(num_books__gt=1) .order_by("pk") ) self.assertQuerySetEqual( publishers, ["Apress", "Prentice Hall"], lambda p: p.name ) publishers = ( Publisher.objects.filter(book__price__lt=Decimal("40.0")) .annotate(num_books=Count("book__id")) .filter(num_books__gt=1) ) self.assertQuerySetEqual(publishers, ["Apress"], lambda p: p.name) books = Book.objects.annotate(num_authors=Count("authors__id")).filter( authors__name__contains="Norvig", num_authors__gt=1 ) self.assertQuerySetEqual( books, ["Artificial Intelligence: A Modern Approach"], lambda b: b.name ) def test_more_aggregation(self): a = Author.objects.get(name__contains="Norvig") b = Book.objects.get(name__contains="Done Right") b.authors.add(a) b.save() vals = ( Book.objects.annotate(num_authors=Count("authors__id")) .filter(authors__name__contains="Norvig", num_authors__gt=1) .aggregate(Avg("rating")) ) self.assertEqual(vals, {"rating__avg": 4.25}) def test_even_more_aggregate(self): publishers = ( Publisher.objects.annotate( earliest_book=Min("book__pubdate"), ) .exclude(earliest_book=None) .order_by("earliest_book") .values( "earliest_book", "num_awards", "id", "name", ) ) self.assertEqual( list(publishers), [ { "earliest_book": datetime.date(1991, 10, 15), "num_awards": 9, "id": self.p4.id, "name": "Morgan Kaufmann", }, { "earliest_book": datetime.date(1995, 1, 15), "num_awards": 7, "id": self.p3.id, "name": "Prentice Hall", }, { "earliest_book": datetime.date(2007, 12, 6), "num_awards": 3, "id": self.p1.id, "name": "Apress", }, { "earliest_book": datetime.date(2008, 3, 3), "num_awards": 1, "id": self.p2.id, "name": "Sams", }, ], ) vals = Store.objects.aggregate( Max("friday_night_closing"), Min("original_opening") ) self.assertEqual( vals, { "friday_night_closing__max": datetime.time(23, 59, 59), "original_opening__min": datetime.datetime(1945, 4, 25, 16, 24, 14), }, ) def test_annotate_values_list(self): books = ( Book.objects.filter(pk=self.b1.pk) .annotate(mean_age=Avg("authors__age")) .values_list("pk", "isbn", "mean_age") ) self.assertEqual(list(books), [(self.b1.id, "159059725", 34.5)]) books = ( Book.objects.filter(pk=self.b1.pk) .annotate(mean_age=Avg("authors__age")) .values_list("isbn") ) self.assertEqual(list(books), [("159059725",)]) books = ( Book.objects.filter(pk=self.b1.pk) .annotate(mean_age=Avg("authors__age")) .values_list("mean_age") ) self.assertEqual(list(books), [(34.5,)]) books = ( Book.objects.filter(pk=self.b1.pk) .annotate(mean_age=Avg("authors__age")) .values_list("mean_age", flat=True) ) self.assertEqual(list(books), [34.5]) books = ( Book.objects.values_list("price") .annotate(count=Count("price"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/queries/test_sqlcompiler.py
tests/queries/test_sqlcompiler.py
from django.db import DEFAULT_DB_ALIAS, connection from django.db.models.sql import Query from django.test import SimpleTestCase from .models import Item class SQLCompilerTest(SimpleTestCase): def test_repr(self): query = Query(Item) compiler = query.get_compiler(DEFAULT_DB_ALIAS, connection) self.assertEqual( repr(compiler), f"<SQLCompiler model=Item connection=" f"<DatabaseWrapper vendor={connection.vendor!r} alias='default'> " f"using='default'>", )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/queries/test_q.py
tests/queries/test_q.py
from datetime import datetime from django.core.exceptions import FieldError from django.db import connection from django.db.models import ( BooleanField, Exists, ExpressionWrapper, F, OuterRef, Q, Value, ) from django.db.models.expressions import NegatedExpression, RawSQL from django.db.models.functions import ExtractDay, Lower, TruncDate from django.db.models.lookups import ( Exact, IntegerFieldExact, IntegerLessThanOrEqual, IsNull, ) from django.db.models.sql.where import NothingNode from django.test import SimpleTestCase, TestCase from .models import Tag class QTests(SimpleTestCase): def test_combine_and_empty(self): q = Q(x=1) self.assertEqual(q & Q(), q) self.assertEqual(Q() & q, q) q = Q(x__in={}.keys()) self.assertEqual(q & Q(), q) self.assertEqual(Q() & q, q) def test_combine_and_both_empty(self): self.assertEqual(Q() & Q(), Q()) def test_combine_or_empty(self): q = Q(x=1) self.assertEqual(q | Q(), q) self.assertEqual(Q() | q, q) q = Q(x__in={}.keys()) self.assertEqual(q | Q(), q) self.assertEqual(Q() | q, q) def test_combine_xor_empty(self): q = Q(x=1) self.assertEqual(q ^ Q(), q) self.assertEqual(Q() ^ q, q) q = Q(x__in={}.keys()) self.assertEqual(q ^ Q(), q) self.assertEqual(Q() ^ q, q) def test_combine_empty_copy(self): base_q = Q(x=1) tests = [ base_q | Q(), Q() | base_q, base_q & Q(), Q() & base_q, base_q ^ Q(), Q() ^ base_q, ] for i, q in enumerate(tests): with self.subTest(i=i): self.assertEqual(q, base_q) self.assertIsNot(q, base_q) def test_combine_or_both_empty(self): self.assertEqual(Q() | Q(), Q()) def test_combine_xor_both_empty(self): self.assertEqual(Q() ^ Q(), Q()) def test_combine_not_q_object(self): obj = object() q = Q(x=1) with self.assertRaisesMessage(TypeError, str(obj)): q | obj with self.assertRaisesMessage(TypeError, str(obj)): q & obj with self.assertRaisesMessage(TypeError, str(obj)): q ^ obj def test_combine_negated_boolean_expression(self): tagged = Tag.objects.filter(category=OuterRef("pk")) tests = [ Q() & ~Exists(tagged), Q() | ~Exists(tagged), Q() ^ ~Exists(tagged), ] for q in tests: with self.subTest(q=q): self.assertIsInstance(q, NegatedExpression) def test_deconstruct(self): q = Q(price__gt=F("discounted_price")) path, args, kwargs = q.deconstruct() self.assertEqual(path, "django.db.models.Q") self.assertEqual(args, (("price__gt", F("discounted_price")),)) self.assertEqual(kwargs, {}) def test_deconstruct_negated(self): q = ~Q(price__gt=F("discounted_price")) path, args, kwargs = q.deconstruct() self.assertEqual(args, (("price__gt", F("discounted_price")),)) self.assertEqual(kwargs, {"_negated": True}) def test_deconstruct_or(self): q1 = Q(price__gt=F("discounted_price")) q2 = Q(price=F("discounted_price")) q = q1 | q2 path, args, kwargs = q.deconstruct() self.assertEqual( args, ( ("price__gt", F("discounted_price")), ("price", F("discounted_price")), ), ) self.assertEqual(kwargs, {"_connector": Q.OR}) def test_deconstruct_xor(self): q1 = Q(price__gt=F("discounted_price")) q2 = Q(price=F("discounted_price")) q = q1 ^ q2 path, args, kwargs = q.deconstruct() self.assertEqual( args, ( ("price__gt", F("discounted_price")), ("price", F("discounted_price")), ), ) self.assertEqual(kwargs, {"_connector": Q.XOR}) def test_deconstruct_and(self): q1 = Q(price__gt=F("discounted_price")) q2 = Q(price=F("discounted_price")) q = q1 & q2 path, args, kwargs = q.deconstruct() self.assertEqual( args, ( ("price__gt", F("discounted_price")), ("price", F("discounted_price")), ), ) self.assertEqual(kwargs, {}) def test_deconstruct_multiple_kwargs(self): q = Q(price__gt=F("discounted_price"), price=F("discounted_price")) path, args, kwargs = q.deconstruct() self.assertEqual( args, ( ("price", F("discounted_price")), ("price__gt", F("discounted_price")), ), ) self.assertEqual(kwargs, {}) def test_deconstruct_nested(self): q = Q(Q(price__gt=F("discounted_price"))) path, args, kwargs = q.deconstruct() self.assertEqual(args, (Q(price__gt=F("discounted_price")),)) self.assertEqual(kwargs, {}) def test_deconstruct_boolean_expression(self): expr = RawSQL("1 = 1", BooleanField()) q = Q(expr) _, args, kwargs = q.deconstruct() self.assertEqual(args, (expr,)) self.assertEqual(kwargs, {}) def test_reconstruct(self): q = Q(price__gt=F("discounted_price")) path, args, kwargs = q.deconstruct() self.assertEqual(Q(*args, **kwargs), q) def test_reconstruct_negated(self): q = ~Q(price__gt=F("discounted_price")) path, args, kwargs = q.deconstruct() self.assertEqual(Q(*args, **kwargs), q) def test_reconstruct_or(self): q1 = Q(price__gt=F("discounted_price")) q2 = Q(price=F("discounted_price")) q = q1 | q2 path, args, kwargs = q.deconstruct() self.assertEqual(Q(*args, **kwargs), q) def test_reconstruct_xor(self): q1 = Q(price__gt=F("discounted_price")) q2 = Q(price=F("discounted_price")) q = q1 ^ q2 path, args, kwargs = q.deconstruct() self.assertEqual(Q(*args, **kwargs), q) def test_reconstruct_and(self): q1 = Q(price__gt=F("discounted_price")) q2 = Q(price=F("discounted_price")) q = q1 & q2 path, args, kwargs = q.deconstruct() self.assertEqual(Q(*args, **kwargs), q) def test_equal(self): self.assertEqual(Q(), Q()) self.assertEqual( Q(("pk__in", (1, 2))), Q(("pk__in", [1, 2])), ) self.assertEqual( Q(("pk__in", (1, 2))), Q(pk__in=[1, 2]), ) self.assertEqual( Q(("pk__in", (1, 2))), Q(("pk__in", {1: "first", 2: "second"}.keys())), ) self.assertNotEqual( Q(name__iexact=F("other_name")), Q(name=Lower(F("other_name"))), ) def test_hash(self): self.assertEqual(hash(Q()), hash(Q())) self.assertEqual( hash(Q(("pk__in", (1, 2)))), hash(Q(("pk__in", [1, 2]))), ) self.assertEqual( hash(Q(("pk__in", (1, 2)))), hash(Q(pk__in=[1, 2])), ) self.assertEqual( hash(Q(("pk__in", (1, 2)))), hash(Q(("pk__in", {1: "first", 2: "second"}.keys()))), ) self.assertNotEqual( hash(Q(name__iexact=F("other_name"))), hash(Q(name=Lower(F("other_name")))), ) def test_flatten(self): q = Q() self.assertEqual(list(q.flatten()), [q]) q = Q(NothingNode()) self.assertEqual(list(q.flatten()), [q, q.children[0]]) q = Q( ExpressionWrapper( Q(RawSQL("id = 0", params=(), output_field=BooleanField())) | Q(price=Value("4.55")) | Q(name=Lower("category")), output_field=BooleanField(), ) ) flatten = list(q.flatten()) self.assertEqual(len(flatten), 7) def test_create_helper(self): items = [("a", 1), ("b", 2), ("c", 3)] for connector in [Q.AND, Q.OR, Q.XOR]: with self.subTest(connector=connector): self.assertEqual( Q.create(items, connector=connector), Q(*items, _connector=connector), ) def test_connector_validation(self): msg = f"_connector must be one of {Q.AND!r}, {Q.OR!r}, {Q.XOR!r}, or None." with self.assertRaisesMessage(ValueError, msg): Q(_connector="evil") def test_referenced_base_fields(self): # Make sure Q.referenced_base_fields retrieves all base fields from # both filters and F expressions. tests = [ (Q(field_1=1) & Q(field_2=1), {"field_1", "field_2"}), ( Q(Exact(F("field_3"), IsNull(F("field_4"), True))), {"field_3", "field_4"}, ), (Q(Exact(Q(field_5=F("field_6")), True)), {"field_5", "field_6"}), (Q(field_2=1), {"field_2"}), (Q(field_7__lookup=True), {"field_7"}), (Q(field_7__joined_field__lookup=True), {"field_7"}), ] combined_q = Q(1) combined_q_base_fields = set() for q, expected_base_fields in tests: combined_q &= q combined_q_base_fields |= expected_base_fields tests.append((combined_q, combined_q_base_fields)) for q, expected_base_fields in tests: with self.subTest(q=q): self.assertEqual( q.referenced_base_fields, expected_base_fields, ) def test_replace_expressions(self): replacements = {F("timestamp"): Value(None)} self.assertEqual( Q(timestamp__date__day=25).replace_expressions(replacements), Q(timestamp__date__day=25), ) replacements = {F("timestamp"): Value(datetime(2025, 10, 23))} self.assertEqual( Q(timestamp__date__day=13).replace_expressions(replacements), Q( IntegerFieldExact( ExtractDay(TruncDate(Value(datetime(2025, 10, 23)))), 13, ) ), ) self.assertEqual( Q(timestamp__date__day__lte=25).replace_expressions(replacements), Q( IntegerLessThanOrEqual( ExtractDay(TruncDate(Value(datetime(2025, 10, 23)))), 25, ) ), ) self.assertEqual( ( Q(Q(timestamp__date__day__lte=25), timestamp__date__day=13) ).replace_expressions(replacements), ( Q( Q( IntegerLessThanOrEqual( ExtractDay(TruncDate(Value(datetime(2025, 10, 23)))), 25, ) ), IntegerFieldExact( ExtractDay(TruncDate(Value(datetime(2025, 10, 23)))), 13, ), ) ), ) self.assertEqual( Q(timestamp=None).replace_expressions(replacements), Q(IsNull(Value(datetime(2025, 10, 23)), True)), ) self.assertEqual( Q(timestamp__date__day__invalid=25).replace_expressions(replacements), Q(timestamp__date__day__invalid=25), ) class QCheckTests(TestCase): def test_basic(self): q = Q(price__gt=20) self.assertIs(q.check({"price": 30}), True) self.assertIs(q.check({"price": 10}), False) def test_expression(self): q = Q(name="test") self.assertIs(q.check({"name": Lower(Value("TeSt"))}), True) self.assertIs(q.check({"name": Value("other")}), False) def test_missing_field(self): q = Q(description__startswith="prefix") msg = "Cannot resolve keyword 'description' into field." with self.assertRaisesMessage(FieldError, msg): q.check({"name": "test"}) def test_boolean_expression(self): q = Q(ExpressionWrapper(Q(price__gt=20), output_field=BooleanField())) self.assertIs(q.check({"price": 25}), True) self.assertIs(q.check({"price": Value(10)}), False) def test_rawsql(self): """ RawSQL expressions cause a database error because "price" cannot be replaced by its value. In this case, Q.check() logs a warning and return True. """ q = Q(RawSQL("price > %s", params=(20,), output_field=BooleanField())) with self.assertLogs("django.db.models", "WARNING") as cm: self.assertIs(q.check({"price": 10}), True) self.assertIn( f"Got a database error calling check() on {q!r}: ", cm.records[0].getMessage(), ) # We must leave the connection in a usable state (#35712). self.assertTrue(connection.is_usable())
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/queries/test_query.py
tests/queries/test_query.py
from datetime import datetime from django.core.exceptions import FieldError from django.db import DEFAULT_DB_ALIAS, connection from django.db.models import BooleanField, CharField, F, Q from django.db.models.expressions import ( Col, Exists, ExpressionWrapper, Func, RawSQL, Value, ) from django.db.models.fields.related_lookups import RelatedIsNull from django.db.models.functions import Lower from django.db.models.lookups import Exact, GreaterThan, IsNull, LessThan from django.db.models.sql.constants import SINGLE from django.db.models.sql.query import JoinPromoter, Query, get_field_names_from_opts from django.db.models.sql.where import AND, OR from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import register_lookup from .models import Author, Item, ObjectC, Ranking class TestQuery(SimpleTestCase): def test_simple_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2)) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field("num")) def test_non_alias_cols_query(self): query = Query(Author, alias_cols=False) where = query.build_where(Q(num__gt=2, name__isnull=False) | Q(num__lt=F("id"))) name_isnull_lookup, num_gt_lookup = where.children[0].children self.assertIsInstance(num_gt_lookup, GreaterThan) self.assertIsInstance(num_gt_lookup.lhs, Col) self.assertIsNone(num_gt_lookup.lhs.alias) self.assertIsInstance(name_isnull_lookup, IsNull) self.assertIsInstance(name_isnull_lookup.lhs, Col) self.assertIsNone(name_isnull_lookup.lhs.alias) num_lt_lookup = where.children[1] self.assertIsInstance(num_lt_lookup, LessThan) self.assertIsInstance(num_lt_lookup.rhs, Col) self.assertIsNone(num_lt_lookup.rhs.alias) self.assertIsInstance(num_lt_lookup.lhs, Col) self.assertIsNone(num_lt_lookup.lhs.alias) def test_complex_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2) | Q(num__lt=0)) self.assertEqual(where.connector, OR) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field("num")) lookup = where.children[1] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.rhs, 0) self.assertEqual(lookup.lhs.target, Author._meta.get_field("num")) def test_multiple_fields(self): query = Query(Item, alias_cols=False) where = query.build_where(Q(modified__gt=F("created"))) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertIsInstance(lookup.rhs, Col) self.assertIsNone(lookup.rhs.alias) self.assertIsInstance(lookup.lhs, Col) self.assertIsNone(lookup.lhs.alias) self.assertEqual(lookup.rhs.target, Item._meta.get_field("created")) self.assertEqual(lookup.lhs.target, Item._meta.get_field("modified")) def test_transform(self): query = Query(Author, alias_cols=False) with register_lookup(CharField, Lower): where = query.build_where(~Q(name__lower="foo")) lookup = where.children[0] self.assertIsInstance(lookup, Exact) self.assertIsInstance(lookup.lhs, Lower) self.assertIsInstance(lookup.lhs.lhs, Col) self.assertIsNone(lookup.lhs.lhs.alias) self.assertEqual(lookup.lhs.lhs.target, Author._meta.get_field("name")) def test_negated_nullable(self): query = Query(Item) where = query.build_where(~Q(modified__lt=datetime(2017, 1, 1))) self.assertTrue(where.negated) lookup = where.children[0] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.lhs.target, Item._meta.get_field("modified")) lookup = where.children[1] self.assertIsInstance(lookup, IsNull) self.assertEqual(lookup.lhs.target, Item._meta.get_field("modified")) def test_foreign_key(self): query = Query(Item) msg = "Joined field references are not permitted in this query" with self.assertRaisesMessage(FieldError, msg): query.build_where(Q(creator__num__gt=2)) def test_foreign_key_f(self): query = Query(Ranking) with self.assertRaises(FieldError): query.build_where(Q(rank__gt=F("author__num"))) def test_foreign_key_exclusive(self): query = Query(ObjectC, alias_cols=False) where = query.build_where(Q(objecta=None) | Q(objectb=None)) a_isnull = where.children[0] self.assertIsInstance(a_isnull, RelatedIsNull) self.assertIsInstance(a_isnull.lhs, Col) self.assertIsNone(a_isnull.lhs.alias) self.assertEqual(a_isnull.lhs.target, ObjectC._meta.get_field("objecta")) b_isnull = where.children[1] self.assertIsInstance(b_isnull, RelatedIsNull) self.assertIsInstance(b_isnull.lhs, Col) self.assertIsNone(b_isnull.lhs.alias) self.assertEqual(b_isnull.lhs.target, ObjectC._meta.get_field("objectb")) def test_clone_select_related(self): query = Query(Item) query.add_select_related(["creator"]) clone = query.clone() clone.add_select_related(["note", "creator__extra"]) self.assertEqual(query.select_related, {"creator": {}}) def test_iterable_lookup_value(self): query = Query(Item) where = query.build_where(Q(name=["a", "b"])) name_exact = where.children[0] self.assertIsInstance(name_exact, Exact) self.assertEqual(name_exact.rhs, "['a', 'b']") def test_filter_conditional(self): query = Query(Item) where = query.build_where(Func(output_field=BooleanField())) exact = where.children[0] self.assertIsInstance(exact, Exact) self.assertIsInstance(exact.lhs, Func) self.assertIs(exact.rhs, True) def test_filter_conditional_join(self): query = Query(Item) filter_expr = Func("note__note", output_field=BooleanField()) msg = "Joined field references are not permitted in this query" with self.assertRaisesMessage(FieldError, msg): query.build_where(filter_expr) def test_filter_non_conditional(self): query = Query(Item) msg = "Cannot filter against a non-conditional expression." with self.assertRaisesMessage(TypeError, msg): query.build_where(Func(output_field=CharField())) class TestQueryNoModel(TestCase): def test_rawsql_annotation(self): query = Query(None) sql = "%s = 1" # Wrap with a CASE WHEN expression if a database backend (e.g. Oracle) # doesn't support boolean expression in SELECT list. if not connection.features.supports_boolean_expr_in_select_clause: sql = f"CASE WHEN {sql} THEN 1 ELSE 0 END" query.add_annotation(RawSQL(sql, (1,), BooleanField()), "_check") result = query.get_compiler(using=DEFAULT_DB_ALIAS).execute_sql(SINGLE) self.assertEqual(result[0], 1) def test_subquery_annotation(self): query = Query(None) query.add_annotation(Exists(Item.objects.all()), "_check") result = query.get_compiler(using=DEFAULT_DB_ALIAS).execute_sql(SINGLE) self.assertEqual(result[0], 0) @skipUnlessDBFeature("supports_boolean_expr_in_select_clause") def test_q_annotation(self): query = Query(None) check = ExpressionWrapper( Q(RawSQL("%s = 1", (1,), BooleanField())) | Q(Exists(Item.objects.all())), BooleanField(), ) query.add_annotation(check, "_check") result = query.get_compiler(using=DEFAULT_DB_ALIAS).execute_sql(SINGLE) self.assertEqual(result[0], 1) def test_names_to_path_field(self): query = Query(None) query.add_annotation(Value(True), "value") path, final_field, targets, names = query.names_to_path(["value"], opts=None) self.assertEqual(path, []) self.assertIsInstance(final_field, BooleanField) self.assertEqual(len(targets), 1) self.assertIsInstance(targets[0], BooleanField) self.assertEqual(names, []) def test_names_to_path_field_error(self): query = Query(None) msg = "Cannot resolve keyword 'nonexistent' into field." with self.assertRaisesMessage(FieldError, msg): query.names_to_path(["nonexistent"], opts=None) def test_get_field_names_from_opts(self): self.assertEqual(get_field_names_from_opts(None), set()) class JoinPromoterTest(SimpleTestCase): def test_repr(self): self.assertEqual( repr(JoinPromoter(AND, 3, True)), "JoinPromoter(connector='AND', num_children=3, negated=True)", )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/queries/models.py
tests/queries/models.py
""" Various complex queries that have been problematic in the past. """ import datetime from django.db import models from django.db.models.functions import Now class DumbCategory(models.Model): pass class ProxyCategory(DumbCategory): class Meta: proxy = True class NamedCategory(DumbCategory): name = models.CharField(max_length=10) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=10) parent = models.ForeignKey( "self", models.SET_NULL, blank=True, null=True, related_name="children", ) category = models.ForeignKey( NamedCategory, models.SET_NULL, null=True, default=None ) class Meta: ordering = ["name"] def __str__(self): return self.name class Note(models.Model): note = models.CharField(max_length=100) misc = models.CharField(max_length=25) tag = models.ForeignKey(Tag, models.SET_NULL, blank=True, null=True) negate = models.BooleanField(default=True) class Meta: ordering = ["note"] def __str__(self): return self.note class Annotation(models.Model): name = models.CharField(max_length=10) tag = models.ForeignKey(Tag, models.CASCADE) notes = models.ManyToManyField(Note) def __str__(self): return self.name class DateTimePK(models.Model): date = models.DateTimeField(primary_key=True, default=datetime.datetime.now) class Meta: ordering = ["date"] class ExtraInfo(models.Model): info = models.CharField(max_length=100) note = models.ForeignKey(Note, models.CASCADE, null=True) value = models.IntegerField(null=True) date = models.ForeignKey(DateTimePK, models.SET_NULL, null=True) filterable = models.BooleanField(default=True) class Meta: ordering = ["info"] def __str__(self): return self.info class Author(models.Model): name = models.CharField(max_length=10) num = models.IntegerField(unique=True) extra = models.ForeignKey(ExtraInfo, models.CASCADE) class Meta: ordering = ["name"] def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=10) created = models.DateTimeField() modified = models.DateTimeField(blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True) creator = models.ForeignKey(Author, models.CASCADE) note = models.ForeignKey(Note, models.CASCADE) class Meta: ordering = ["-note", "name"] def __str__(self): return self.name class Report(models.Model): name = models.CharField(max_length=10) creator = models.ForeignKey(Author, models.SET_NULL, to_field="num", null=True) def __str__(self): return self.name class ReportComment(models.Model): report = models.ForeignKey(Report, models.CASCADE) class Ranking(models.Model): rank = models.IntegerField() author = models.ForeignKey(Author, models.CASCADE) class Meta: # A complex ordering specification. Should stress the system a bit. ordering = ("author__extra__note", "author__name", "rank") def __str__(self): return "%d: %s" % (self.rank, self.author.name) class Cover(models.Model): title = models.CharField(max_length=50) item = models.ForeignKey(Item, models.CASCADE) class Meta: ordering = ["item"] def __str__(self): return self.title class Number(models.Model): num = models.IntegerField() other_num = models.IntegerField(null=True) another_num = models.IntegerField(null=True) def __str__(self): return str(self.num) # Symmetrical m2m field with a normal field using the reverse accessor name # ("valid"). class Valid(models.Model): valid = models.CharField(max_length=10) parent = models.ManyToManyField("self") class Meta: ordering = ["valid"] # Some funky cross-linked models for testing a couple of infinite recursion # cases. class X(models.Model): y = models.ForeignKey("Y", models.CASCADE) class Y(models.Model): x1 = models.ForeignKey(X, models.CASCADE, related_name="y1") # Some models with a cycle in the default ordering. This would be bad if we # didn't catch the infinite loop. class LoopX(models.Model): y = models.ForeignKey("LoopY", models.CASCADE) class Meta: ordering = ["y"] class LoopY(models.Model): x = models.ForeignKey(LoopX, models.CASCADE) class Meta: ordering = ["x"] class LoopZ(models.Model): z = models.ForeignKey("self", models.CASCADE) class Meta: ordering = ["z"] # A model and custom default manager combination. class CustomManager(models.Manager): def get_queryset(self): qs = super().get_queryset() return qs.filter(public=True, tag__name="t1") class ManagedModel(models.Model): data = models.CharField(max_length=10) tag = models.ForeignKey(Tag, models.CASCADE) public = models.BooleanField(default=True) objects = CustomManager() normal_manager = models.Manager() def __str__(self): return self.data # An inter-related setup with multiple paths from Child to Detail. class Detail(models.Model): data = models.CharField(max_length=10) class MemberManager(models.Manager): def get_queryset(self): return super().get_queryset().select_related("details") class Member(models.Model): name = models.CharField(max_length=10) details = models.OneToOneField(Detail, models.CASCADE, primary_key=True) objects = MemberManager() class Child(models.Model): person = models.OneToOneField(Member, models.CASCADE, primary_key=True) parent = models.ForeignKey(Member, models.CASCADE, related_name="children") # Custom primary keys interfered with ordering in the past. class CustomPk(models.Model): name = models.CharField(max_length=10, primary_key=True) extra = models.CharField(max_length=10) class Meta: ordering = ["name", "extra"] class Related(models.Model): custom = models.ForeignKey(CustomPk, models.CASCADE, null=True) class CustomPkTag(models.Model): id = models.CharField(max_length=20, primary_key=True) custom_pk = models.ManyToManyField(CustomPk) tag = models.CharField(max_length=20) # An inter-related setup with a model subclass that has a nullable # path to another model, and a return path from that model. class Celebrity(models.Model): name = models.CharField("Name", max_length=20) greatest_fan = models.ForeignKey("Fan", models.SET_NULL, null=True, unique=True) def __str__(self): return self.name class TvChef(Celebrity): pass class Fan(models.Model): fan_of = models.ForeignKey(Celebrity, models.CASCADE) # Multiple foreign keys class LeafA(models.Model): data = models.CharField(max_length=10) def __str__(self): return self.data class LeafB(models.Model): data = models.CharField(max_length=10) class Join(models.Model): a = models.ForeignKey(LeafA, models.CASCADE) b = models.ForeignKey(LeafB, models.CASCADE) class ReservedName(models.Model): name = models.CharField(max_length=20) order = models.IntegerField() def __str__(self): return self.name # A simpler shared-foreign-key setup that can expose some problems. class SharedConnection(models.Model): data = models.CharField(max_length=10) def __str__(self): return self.data class PointerA(models.Model): connection = models.ForeignKey(SharedConnection, models.CASCADE) class PointerB(models.Model): connection = models.ForeignKey(SharedConnection, models.CASCADE) # Multi-layer ordering class SingleObject(models.Model): name = models.CharField(max_length=10) class Meta: ordering = ["name"] def __str__(self): return self.name class RelatedObject(models.Model): single = models.ForeignKey(SingleObject, models.SET_NULL, null=True) f = models.IntegerField(null=True) class Meta: ordering = ["single"] class Plaything(models.Model): name = models.CharField(max_length=10) others = models.ForeignKey(RelatedObject, models.SET_NULL, null=True) class Meta: ordering = ["others"] def __str__(self): return self.name class Article(models.Model): name = models.CharField(max_length=20) created = models.DateTimeField() def __str__(self): return self.name class Food(models.Model): name = models.CharField(max_length=20, unique=True) def __str__(self): return self.name class Eaten(models.Model): food = models.ForeignKey(Food, models.SET_NULL, to_field="name", null=True) meal = models.CharField(max_length=20) def __str__(self): return "%s at %s" % (self.food, self.meal) class Node(models.Model): num = models.IntegerField(unique=True) parent = models.ForeignKey("self", models.SET_NULL, to_field="num", null=True) def __str__(self): return str(self.num) # Bug #12252 class ObjectA(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name def __iter__(self): # Ticket #23721 assert False, "type checking should happen without calling model __iter__" class ProxyObjectA(ObjectA): class Meta: proxy = True class ChildObjectA(ObjectA): pass class ObjectB(models.Model): name = models.CharField(max_length=50) objecta = models.ForeignKey(ObjectA, models.CASCADE) num = models.PositiveIntegerField() def __str__(self): return self.name class ProxyObjectB(ObjectB): class Meta: proxy = True class ObjectC(models.Model): name = models.CharField(max_length=50) objecta = models.ForeignKey(ObjectA, models.SET_NULL, null=True) objectb = models.ForeignKey(ObjectB, models.SET_NULL, null=True) childobjecta = models.ForeignKey( ChildObjectA, models.SET_NULL, null=True, related_name="ca_pk" ) def __str__(self): return self.name class SimpleCategory(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class SpecialCategory(SimpleCategory): special_name = models.CharField(max_length=35) def __str__(self): return self.name + " " + self.special_name class CategoryItem(models.Model): category = models.ForeignKey(SimpleCategory, models.CASCADE) def __str__(self): return "category item: " + str(self.category) class MixedCaseFieldCategoryItem(models.Model): CaTeGoRy = models.ForeignKey(SimpleCategory, models.CASCADE) class MixedCaseDbColumnCategoryItem(models.Model): category = models.ForeignKey( SimpleCategory, models.CASCADE, db_column="CaTeGoRy_Id" ) class OneToOneCategory(models.Model): new_name = models.CharField(max_length=15) category = models.OneToOneField(SimpleCategory, models.CASCADE) def __str__(self): return "one2one " + self.new_name class CategoryRelationship(models.Model): first = models.ForeignKey(SimpleCategory, models.CASCADE, related_name="first_rel") second = models.ForeignKey( SimpleCategory, models.CASCADE, related_name="second_rel" ) class CommonMixedCaseForeignKeys(models.Model): category = models.ForeignKey(CategoryItem, models.CASCADE) mixed_case_field_category = models.ForeignKey( MixedCaseFieldCategoryItem, models.CASCADE ) mixed_case_db_column_category = models.ForeignKey( MixedCaseDbColumnCategoryItem, models.CASCADE ) class NullableName(models.Model): name = models.CharField(max_length=20, null=True) class Meta: ordering = ["id"] class ModelD(models.Model): name = models.TextField() class ModelC(models.Model): name = models.TextField() class ModelB(models.Model): name = models.TextField() c = models.ForeignKey(ModelC, models.CASCADE) class ModelA(models.Model): name = models.TextField() b = models.ForeignKey(ModelB, models.SET_NULL, null=True) d = models.ForeignKey(ModelD, models.CASCADE) class Job(models.Model): name = models.CharField(max_length=20, unique=True) def __str__(self): return self.name class JobResponsibilities(models.Model): job = models.ForeignKey(Job, models.CASCADE, to_field="name") responsibility = models.ForeignKey( "Responsibility", models.CASCADE, to_field="description" ) class Responsibility(models.Model): description = models.CharField(max_length=20, unique=True) jobs = models.ManyToManyField( Job, through=JobResponsibilities, related_name="responsibilities" ) def __str__(self): return self.description # Models for disjunction join promotion low level testing. class FK1(models.Model): f1 = models.TextField() f2 = models.TextField() class FK2(models.Model): f1 = models.TextField() f2 = models.TextField() class FK3(models.Model): f1 = models.TextField() f2 = models.TextField() class BaseA(models.Model): a = models.ForeignKey(FK1, models.SET_NULL, null=True) b = models.ForeignKey(FK2, models.SET_NULL, null=True) c = models.ForeignKey(FK3, models.SET_NULL, null=True) class Identifier(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Program(models.Model): identifier = models.OneToOneField(Identifier, models.CASCADE) class Channel(models.Model): programs = models.ManyToManyField(Program) identifier = models.OneToOneField(Identifier, models.CASCADE) class Book(models.Model): title = models.TextField() chapter = models.ForeignKey("Chapter", models.CASCADE) class Chapter(models.Model): title = models.TextField() paragraph = models.ForeignKey("Paragraph", models.CASCADE) class Paragraph(models.Model): text = models.TextField() page = models.ManyToManyField("Page") class Page(models.Model): text = models.TextField() class MyObject(models.Model): parent = models.ForeignKey( "self", models.SET_NULL, null=True, blank=True, related_name="children" ) data = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) # Models for #17600 regressions class Order(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=12, null=True, default="") class Meta: ordering = ("pk",) def __str__(self): return str(self.pk) class OrderItem(models.Model): order = models.ForeignKey(Order, models.CASCADE, related_name="items") status = models.IntegerField() class Meta: ordering = ("pk",) def __str__(self): return str(self.pk) class BaseUser(models.Model): annotation = models.ForeignKey(Annotation, models.CASCADE, null=True, blank=True) class Task(models.Model): title = models.CharField(max_length=10) owner = models.ForeignKey(BaseUser, models.CASCADE, related_name="owner") creator = models.ForeignKey(BaseUser, models.CASCADE, related_name="creator") note = models.ForeignKey(Note, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.title class Staff(models.Model): name = models.CharField(max_length=10) def __str__(self): return self.name class StaffUser(BaseUser): staff = models.OneToOneField(Staff, models.CASCADE, related_name="user") def __str__(self): return str(self.staff) class Ticket21203Parent(models.Model): parentid = models.AutoField(primary_key=True) parent_bool = models.BooleanField(default=True) created = models.DateTimeField(auto_now=True) class Ticket21203Child(models.Model): childid = models.AutoField(primary_key=True) parent = models.ForeignKey(Ticket21203Parent, models.CASCADE) class Person(models.Model): name = models.CharField(max_length=128) class Company(models.Model): name = models.CharField(max_length=128) employees = models.ManyToManyField( Person, related_name="employers", through="Employment" ) def __str__(self): return self.name class Employment(models.Model): employer = models.ForeignKey(Company, models.CASCADE) employee = models.ForeignKey(Person, models.CASCADE) title = models.CharField(max_length=128) class School(models.Model): pass class Student(models.Model): school = models.ForeignKey(School, models.CASCADE) class Classroom(models.Model): name = models.CharField(max_length=20) has_blackboard = models.BooleanField(null=True) school = models.ForeignKey(School, models.CASCADE) students = models.ManyToManyField(Student, related_name="classroom") class Teacher(models.Model): schools = models.ManyToManyField(School) friends = models.ManyToManyField("self") class Ticket23605AParent(models.Model): pass class Ticket23605A(Ticket23605AParent): pass class Ticket23605B(models.Model): modela_fk = models.ForeignKey(Ticket23605A, models.CASCADE) modelc_fk = models.ForeignKey("Ticket23605C", models.CASCADE) field_b0 = models.IntegerField(null=True) field_b1 = models.BooleanField(default=False) class Ticket23605C(models.Model): field_c0 = models.FloatField() # db_table names have capital letters to ensure they are quoted in queries. class Individual(models.Model): alive = models.BooleanField() class Meta: db_table = "Individual" class RelatedIndividual(models.Model): related = models.ForeignKey( Individual, models.CASCADE, related_name="related_individual" ) class Meta: db_table = "RelatedIndividual" class CustomDbColumn(models.Model): custom_column = models.IntegerField(db_column="custom_name", null=True) ip_address = models.GenericIPAddressField(null=True) class CreatedField(models.DateTimeField): db_returning = True def __init__(self, *args, **kwargs): kwargs.setdefault("default", Now) super().__init__(*args, **kwargs) class ReturningModel(models.Model): created = CreatedField(editable=False) class NonIntegerPKReturningModel(models.Model): created = CreatedField(editable=False, primary_key=True) class JSONFieldNullable(models.Model): json_field = models.JSONField(blank=True, null=True) class Meta: required_db_features = {"supports_json_field"}
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/queries/test_iterator.py
tests/queries/test_iterator.py
import datetime from unittest import mock from django.db import connections from django.db.models.sql.compiler import cursor_iter from django.test import TestCase from .models import Article class QuerySetIteratorTests(TestCase): itersize_index_in_mock_args = 3 @classmethod def setUpTestData(cls): Article.objects.create(name="Article 1", created=datetime.datetime.now()) Article.objects.create(name="Article 2", created=datetime.datetime.now()) def test_iterator_invalid_chunk_size(self): for size in (0, -1): with self.subTest(size=size): with self.assertRaisesMessage( ValueError, "Chunk size must be strictly positive." ): Article.objects.iterator(chunk_size=size) def test_default_iterator_chunk_size(self): qs = Article.objects.iterator() with mock.patch( "django.db.models.sql.compiler.cursor_iter", side_effect=cursor_iter ) as cursor_iter_mock: next(qs) self.assertEqual(cursor_iter_mock.call_count, 1) mock_args, _mock_kwargs = cursor_iter_mock.call_args self.assertEqual(mock_args[self.itersize_index_in_mock_args], 2000) def test_iterator_chunk_size(self): batch_size = 3 qs = Article.objects.iterator(chunk_size=batch_size) with mock.patch( "django.db.models.sql.compiler.cursor_iter", side_effect=cursor_iter ) as cursor_iter_mock: next(qs) self.assertEqual(cursor_iter_mock.call_count, 1) mock_args, _mock_kwargs = cursor_iter_mock.call_args self.assertEqual(mock_args[self.itersize_index_in_mock_args], batch_size) def test_no_chunked_reads(self): """ If the database backend doesn't support chunked reads, then the result of SQLCompiler.execute_sql() is a list. """ qs = Article.objects.all() compiler = qs.query.get_compiler(using=qs.db) features = connections[qs.db].features with mock.patch.object(features, "can_use_chunked_reads", False): result = compiler.execute_sql(chunked_fetch=True) self.assertIsInstance(result, list)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/queries/test_qs_combinators.py
tests/queries/test_qs_combinators.py
import operator from datetime import datetime from django.db import DatabaseError, NotSupportedError, connection from django.db.models import ( DateTimeField, Exists, F, IntegerField, OuterRef, Subquery, Transform, Value, ) from django.db.models.functions import Cast, Mod from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from .models import ( Annotation, Article, Author, Celebrity, ExtraInfo, Note, Number, ReservedName, Tag, ) @skipUnlessDBFeature("supports_select_union") class QuerySetSetOperationTests(TestCase): @classmethod def setUpTestData(cls): Number.objects.bulk_create(Number(num=i, other_num=10 - i) for i in range(10)) def assertNumbersEqual(self, queryset, expected_numbers, ordered=True): self.assertQuerySetEqual( queryset, expected_numbers, operator.attrgetter("num"), ordered ) def test_simple_union(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=8) qs3 = Number.objects.filter(num=5) self.assertNumbersEqual(qs1.union(qs2, qs3), [0, 1, 5, 8, 9], ordered=False) @skipUnlessDBFeature("supports_select_intersection") def test_simple_intersection(self): qs1 = Number.objects.filter(num__lte=5) qs2 = Number.objects.filter(num__gte=5) qs3 = Number.objects.filter(num__gte=4, num__lte=6) self.assertNumbersEqual(qs1.intersection(qs2, qs3), [5], ordered=False) @skipUnlessDBFeature("supports_select_intersection") def test_intersection_with_values(self): ReservedName.objects.create(name="a", order=2) qs1 = ReservedName.objects.all() reserved_name = qs1.intersection(qs1).values("name", "order", "id").get() self.assertEqual(reserved_name["name"], "a") self.assertEqual(reserved_name["order"], 2) reserved_name = qs1.intersection(qs1).values_list("name", "order", "id").get() self.assertEqual(reserved_name[:2], ("a", 2)) @skipUnlessDBFeature("supports_select_difference") def test_simple_difference(self): qs1 = Number.objects.filter(num__lte=5) qs2 = Number.objects.filter(num__lte=4) self.assertNumbersEqual(qs1.difference(qs2), [5], ordered=False) def test_union_distinct(self): qs1 = Number.objects.all() qs2 = Number.objects.all() self.assertEqual(len(list(qs1.union(qs2, all=True))), 20) self.assertEqual(len(list(qs1.union(qs2))), 10) def test_union_none(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=8) qs3 = qs1.union(qs2) self.assertSequenceEqual(qs3.none(), []) self.assertNumbersEqual(qs3, [0, 1, 8, 9], ordered=False) def test_union_none_slice(self): qs1 = Number.objects.filter(num__lte=0) qs2 = Number.objects.none() qs3 = qs1.union(qs2) self.assertNumbersEqual(qs3[:1], [0]) def test_union_empty_slice(self): qs = Number.objects.union() self.assertNumbersEqual(qs[:1], [0]) qs = Number.objects.union(all=True) self.assertNumbersEqual(qs[:1], [0]) self.assertNumbersEqual(qs.order_by("num")[0:], list(range(0, 10))) def test_union_all_none_slice(self): qs = Number.objects.filter(id__in=[]) with self.assertNumQueries(0): self.assertSequenceEqual(qs.union(qs), []) self.assertSequenceEqual(qs.union(qs)[0:0], []) def test_union_empty_filter_slice(self): qs1 = Number.objects.filter(num__lte=0) qs2 = Number.objects.filter(pk__in=[]) qs3 = qs1.union(qs2) self.assertNumbersEqual(qs3[:1], [0]) @skipUnlessDBFeature("supports_slicing_ordering_in_compound") def test_union_slice_compound_empty(self): qs1 = Number.objects.filter(num__lte=0)[:1] qs2 = Number.objects.none() qs3 = qs1.union(qs2) self.assertNumbersEqual(qs3[:1], [0]) @skipUnlessDBFeature("supports_slicing_ordering_in_compound") def test_union_combined_slice_compound_empty(self): qs1 = Number.objects.filter(num__lte=2)[:3] qs2 = Number.objects.none() qs3 = qs1.union(qs2) self.assertNumbersEqual(qs3.order_by("num")[2:3], [2]) def test_union_slice_index(self): Celebrity.objects.create(name="Famous") c1 = Celebrity.objects.create(name="Very famous") qs1 = Celebrity.objects.filter(name="nonexistent") qs2 = Celebrity.objects.all() combined_qs = qs1.union(qs2).order_by("name") self.assertEqual(combined_qs[1], c1) def test_union_order_with_null_first_last(self): Number.objects.filter(other_num=5).update(other_num=None) qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=2) qs3 = qs1.union(qs2) self.assertSequenceEqual( qs3.order_by( F("other_num").asc(nulls_first=True), ).values_list("other_num", flat=True), [None, 1, 2, 3, 4, 6, 7, 8, 9, 10], ) self.assertSequenceEqual( qs3.order_by( F("other_num").asc(nulls_last=True), ).values_list("other_num", flat=True), [1, 2, 3, 4, 6, 7, 8, 9, 10, None], ) def test_union_nested(self): qs1 = Number.objects.all() qs2 = qs1.union(qs1) self.assertNumbersEqual( qs1.union(qs2), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], ordered=False, ) @skipUnlessDBFeature("supports_select_intersection") def test_intersection_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.intersection(qs2)), 0) self.assertEqual(len(qs1.intersection(qs3)), 0) self.assertEqual(len(qs2.intersection(qs1)), 0) self.assertEqual(len(qs3.intersection(qs1)), 0) self.assertEqual(len(qs2.intersection(qs2)), 0) self.assertEqual(len(qs3.intersection(qs3)), 0) @skipUnlessDBFeature("supports_select_difference") def test_difference_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.difference(qs2)), 10) self.assertEqual(len(qs1.difference(qs3)), 10) self.assertEqual(len(qs2.difference(qs1)), 0) self.assertEqual(len(qs3.difference(qs1)), 0) self.assertEqual(len(qs2.difference(qs2)), 0) self.assertEqual(len(qs3.difference(qs3)), 0) @skipUnlessDBFeature("supports_select_difference") def test_difference_with_values(self): ReservedName.objects.create(name="a", order=2) qs1 = ReservedName.objects.all() qs2 = ReservedName.objects.none() reserved_name = qs1.difference(qs2).values("name", "order", "id").get() self.assertEqual(reserved_name["name"], "a") self.assertEqual(reserved_name["order"], 2) reserved_name = qs1.difference(qs2).values_list("name", "order", "id").get() self.assertEqual(reserved_name[:2], ("a", 2)) def test_union_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.union(qs2)), 10) self.assertEqual(len(qs2.union(qs1)), 10) self.assertEqual(len(qs1.union(qs3)), 10) self.assertEqual(len(qs3.union(qs1)), 10) self.assertEqual(len(qs2.union(qs1, qs1, qs1)), 10) self.assertEqual(len(qs2.union(qs1, qs1, all=True)), 20) self.assertEqual(len(qs2.union(qs2)), 0) self.assertEqual(len(qs3.union(qs3)), 0) def test_empty_qs_union_with_ordered_qs(self): qs1 = Number.objects.order_by("num") qs2 = Number.objects.none().union(qs1).order_by("num") self.assertEqual(list(qs1), list(qs2)) def test_limits(self): qs1 = Number.objects.all() qs2 = Number.objects.all() self.assertEqual(len(list(qs1.union(qs2)[:2])), 2) def test_ordering(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=2, num__lte=3) self.assertNumbersEqual(qs1.union(qs2).order_by("-num"), [3, 2, 1, 0]) def test_ordering_by_alias(self): qs1 = Number.objects.filter(num__lte=1).values(alias=F("num")) qs2 = Number.objects.filter(num__gte=2, num__lte=3).values(alias=F("num")) self.assertQuerySetEqual( qs1.union(qs2).order_by("-alias"), [3, 2, 1, 0], operator.itemgetter("alias"), ) def test_ordering_by_f_expression(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=2, num__lte=3) self.assertNumbersEqual(qs1.union(qs2).order_by(F("num").desc()), [3, 2, 1, 0]) def test_ordering_by_f_expression_and_alias(self): qs1 = Number.objects.filter(num__lte=1).values(alias=F("other_num")) qs2 = Number.objects.filter(num__gte=2, num__lte=3).values(alias=F("other_num")) self.assertQuerySetEqual( qs1.union(qs2).order_by(F("alias").desc()), [10, 9, 8, 7], operator.itemgetter("alias"), ) Number.objects.create(num=-1) self.assertQuerySetEqual( qs1.union(qs2).order_by(F("alias").desc(nulls_last=True)), [10, 9, 8, 7, None], operator.itemgetter("alias"), ) def test_union_with_values(self): ReservedName.objects.create(name="a", order=2) qs1 = ReservedName.objects.all() reserved_name = qs1.union(qs1).values("name", "order", "id").get() self.assertEqual(reserved_name["name"], "a") self.assertEqual(reserved_name["order"], 2) reserved_name = qs1.union(qs1).values_list("name", "order", "id").get() self.assertEqual(reserved_name[:2], ("a", 2)) # List of columns can be changed. reserved_name = qs1.union(qs1).values_list("order").get() self.assertEqual(reserved_name, (2,)) def test_union_with_two_annotated_values_list(self): qs1 = ( Number.objects.filter(num=1) .annotate( count=Value(0, IntegerField()), ) .values_list("num", "count") ) qs2 = ( Number.objects.filter(num=2) .values("pk") .annotate( count=F("num"), ) .annotate( num=Value(1, IntegerField()), ) .values_list("num", "count") ) self.assertCountEqual(qs1.union(qs2), [(1, 0), (1, 2)]) def test_union_with_field_and_annotation_values(self): qs1 = ( Number.objects.filter(num=1) .annotate( zero=Value(0, IntegerField()), ) .values_list("num", "zero") ) qs2 = ( Number.objects.filter(num=2) .annotate( zero=Value(0, IntegerField()), ) .values_list("zero", "num") ) self.assertCountEqual(qs1.union(qs2), [(1, 0), (0, 2)]) def test_union_with_extra_and_values_list(self): qs1 = ( Number.objects.filter(num=1) .extra( select={"count": 0}, ) .values_list("num", "count") ) qs2 = Number.objects.filter(num=2).extra(select={"count": 1}) self.assertCountEqual(qs1.union(qs2), [(1, 0), (2, 1)]) def test_union_with_values_list_on_annotated_and_unannotated(self): ReservedName.objects.create(name="rn1", order=1) qs1 = Number.objects.annotate( has_reserved_name=Exists(ReservedName.objects.filter(order=OuterRef("num"))) ).filter(has_reserved_name=True) qs2 = Number.objects.filter(num=9) self.assertCountEqual(qs1.union(qs2).values_list("num", flat=True), [1, 9]) def test_union_with_values_list_and_order(self): ReservedName.objects.bulk_create( [ ReservedName(name="rn1", order=7), ReservedName(name="rn2", order=5), ReservedName(name="rn0", order=6), ReservedName(name="rn9", order=-1), ] ) qs1 = ReservedName.objects.filter(order__gte=6) qs2 = ReservedName.objects.filter(order__lte=5) union_qs = qs1.union(qs2) for qs, expected_result in ( # Order by a single column. (union_qs.order_by("-pk").values_list("order", flat=True), [-1, 6, 5, 7]), (union_qs.order_by("pk").values_list("order", flat=True), [7, 5, 6, -1]), (union_qs.values_list("order", flat=True).order_by("-pk"), [-1, 6, 5, 7]), (union_qs.values_list("order", flat=True).order_by("pk"), [7, 5, 6, -1]), # Order by multiple columns. ( union_qs.order_by("-name", "pk").values_list("order", flat=True), [-1, 5, 7, 6], ), ( union_qs.values_list("order", flat=True).order_by("-name", "pk"), [-1, 5, 7, 6], ), ): with self.subTest(qs=qs): self.assertEqual(list(qs), expected_result) def test_union_with_values_list_and_order_on_annotation(self): qs1 = Number.objects.annotate( annotation=Value(-1), multiplier=F("annotation"), ).filter(num__gte=6) qs2 = Number.objects.annotate( annotation=Value(2), multiplier=F("annotation"), ).filter(num__lte=5) self.assertSequenceEqual( qs1.union(qs2).order_by("annotation", "num").values_list("num", flat=True), [6, 7, 8, 9, 0, 1, 2, 3, 4, 5], ) self.assertQuerySetEqual( qs1.union(qs2) .order_by( F("annotation") * F("multiplier"), "num", ) .values("num"), [6, 7, 8, 9, 0, 1, 2, 3, 4, 5], operator.itemgetter("num"), ) def test_order_by_annotation_transform(self): class Mod2(Mod, Transform): def __init__(self, expr): super().__init__(expr, 2) output_field = IntegerField() output_field.register_lookup(Mod2, "mod2") qs1 = Number.objects.annotate( annotation=Value(1, output_field=output_field), ) qs2 = Number.objects.annotate( annotation=Value(2, output_field=output_field), ) msg = "Ordering combined queries by transforms is not implemented." with self.assertRaisesMessage(NotImplementedError, msg): list(qs1.union(qs2).order_by("annotation__mod2")) def test_union_with_select_related_and_order(self): e1 = ExtraInfo.objects.create(value=7, info="e1") a1 = Author.objects.create(name="a1", num=1, extra=e1) a2 = Author.objects.create(name="a2", num=3, extra=e1) Author.objects.create(name="a3", num=2, extra=e1) base_qs = Author.objects.select_related("extra").order_by() qs1 = base_qs.filter(name="a1") qs2 = base_qs.filter(name="a2") self.assertSequenceEqual(qs1.union(qs2).order_by("pk"), [a1, a2]) @skipUnlessDBFeature("supports_slicing_ordering_in_compound") def test_union_with_select_related_and_first(self): e1 = ExtraInfo.objects.create(value=7, info="e1") a1 = Author.objects.create(name="a1", num=1, extra=e1) Author.objects.create(name="a2", num=3, extra=e1) base_qs = Author.objects.select_related("extra").order_by() qs1 = base_qs.filter(name="a1") qs2 = base_qs.filter(name="a2") self.assertEqual(qs1.union(qs2).order_by("name").first(), a1) def test_union_with_first(self): e1 = ExtraInfo.objects.create(value=7, info="e1") a1 = Author.objects.create(name="a1", num=1, extra=e1) base_qs = Author.objects.order_by() qs1 = base_qs.filter(name="a1") qs2 = base_qs.filter(name="a2") self.assertEqual(qs1.union(qs2).first(), a1) def test_union_multiple_models_with_values_list_and_order(self): reserved_name = ReservedName.objects.create(name="rn1", order=0) qs1 = Celebrity.objects.all() qs2 = ReservedName.objects.all() self.assertSequenceEqual( qs1.union(qs2).order_by("name").values_list("pk", flat=True), [reserved_name.pk], ) def test_union_multiple_models_with_values_list_and_order_by_extra_select(self): reserved_name = ReservedName.objects.create(name="rn1", order=0) qs1 = Celebrity.objects.extra(select={"extra_name": "name"}) qs2 = ReservedName.objects.extra(select={"extra_name": "name"}) self.assertSequenceEqual( qs1.union(qs2).order_by("extra_name").values_list("pk", flat=True), [reserved_name.pk], ) def test_union_multiple_models_with_values_list_and_annotations(self): ReservedName.objects.create(name="rn1", order=10) Celebrity.objects.create(name="c1") qs1 = ReservedName.objects.annotate(row_type=Value("rn")).values_list( "name", "order", "row_type" ) qs2 = Celebrity.objects.annotate( row_type=Value("cb"), order=Value(-10) ).values_list("name", "order", "row_type") self.assertSequenceEqual( qs1.union(qs2).order_by("order"), [("c1", -10, "cb"), ("rn1", 10, "rn")], ) def test_union_multiple_models_with_values_list_and_datetime_annotations(self): gen_x = datetime(1966, 6, 6) Article.objects.create(name="Bellatrix", created=gen_x) column_names = ["name", "created", "order"] qs1 = Article.objects.annotate(order=Value(1)).values_list(*column_names) gen_y = datetime(1991, 10, 10) ReservedName.objects.create(name="Rigel", order=2) qs2 = ReservedName.objects.annotate( created=Cast(Value(gen_y), DateTimeField()) ).values_list(*column_names) expected_result = [("Bellatrix", gen_x, 1), ("Rigel", gen_y, 2)] self.assertEqual(list(qs1.union(qs2).order_by("order")), expected_result) def test_union_multiple_models_with_values_and_datetime_annotations(self): gen_x = datetime(1966, 6, 6) Article.objects.create(name="Bellatrix", created=gen_x) column_names = ["name", "created", "order"] qs1 = Article.objects.values(*column_names, order=Value(1)) gen_y = datetime(1991, 10, 10) ReservedName.objects.create(name="Rigel", order=2) qs2 = ReservedName.objects.values( *column_names, created=Cast(Value(gen_y), DateTimeField()) ) expected_result = [ {"name": "Bellatrix", "created": gen_x, "order": 1}, {"name": "Rigel", "created": gen_y, "order": 2}, ] self.assertEqual(list(qs1.union(qs2).order_by("order")), expected_result) def test_union_in_subquery(self): ReservedName.objects.bulk_create( [ ReservedName(name="rn1", order=8), ReservedName(name="rn2", order=1), ReservedName(name="rn3", order=5), ] ) qs1 = Number.objects.filter(num__gt=7, num=OuterRef("order")) qs2 = Number.objects.filter(num__lt=2, num=OuterRef("order")) self.assertCountEqual( ReservedName.objects.annotate( number=Subquery(qs1.union(qs2).values("num")), ) .filter(number__isnull=False) .values_list("order", flat=True), [8, 1], ) @skipUnlessDBFeature("supports_select_intersection") def test_intersection_in_nested_subquery(self): tag = Tag.objects.create(name="tag") note = Note.objects.create(tag=tag) annotation = Annotation.objects.create(tag=tag) tags = Tag.objects.order_by() tags = tags.filter(id=OuterRef("tag_id")).intersection( tags.filter(id=OuterRef(OuterRef("tag_id"))) ) qs = Note.objects.filter( Exists( Annotation.objects.filter( Exists(tags), notes__in=OuterRef("pk"), ) ) ) self.assertIsNone(qs.first()) annotation.notes.add(note) self.assertEqual(qs.first(), note) def test_union_in_subquery_related_outerref(self): e1 = ExtraInfo.objects.create(value=7, info="e3") e2 = ExtraInfo.objects.create(value=5, info="e2") e3 = ExtraInfo.objects.create(value=1, info="e1") Author.objects.bulk_create( [ Author(name="a1", num=1, extra=e1), Author(name="a2", num=3, extra=e2), Author(name="a3", num=2, extra=e3), ] ) qs1 = ExtraInfo.objects.order_by().filter(value=OuterRef("num")) qs2 = ExtraInfo.objects.order_by().filter(value__lt=OuterRef("extra__value")) qs = ( Author.objects.annotate( info=Subquery(qs1.union(qs2).values("info")[:1]), ) .filter(info__isnull=False) .values_list("name", flat=True) ) self.assertCountEqual(qs, ["a1", "a2"]) # Combined queries don't mutate. self.assertCountEqual(qs, ["a1", "a2"]) @skipUnlessDBFeature("supports_slicing_ordering_in_compound") def test_union_in_with_ordering(self): qs1 = Number.objects.filter(num__gt=7).order_by("num") qs2 = Number.objects.filter(num__lt=2).order_by("num") self.assertNumbersEqual( Number.objects.exclude(id__in=qs1.union(qs2).values("id")), [2, 3, 4, 5, 6, 7], ordered=False, ) @skipUnlessDBFeature( "supports_slicing_ordering_in_compound", "allow_sliced_subqueries_with_in" ) def test_union_in_with_ordering_and_slice(self): qs1 = Number.objects.filter(num__gt=7).order_by("num")[:1] qs2 = Number.objects.filter(num__lt=2).order_by("-num")[:1] self.assertNumbersEqual( Number.objects.exclude(id__in=qs1.union(qs2).values("id")), [0, 2, 3, 4, 5, 6, 7, 9], ordered=False, ) def test_count_union(self): qs1 = Number.objects.filter(num__lte=1).values("num") qs2 = Number.objects.filter(num__gte=2, num__lte=3).values("num") self.assertEqual(qs1.union(qs2).count(), 4) def test_count_union_empty_result(self): qs = Number.objects.filter(pk__in=[]) self.assertEqual(qs.union(qs).count(), 0) def test_count_union_with_select_related(self): e1 = ExtraInfo.objects.create(value=1, info="e1") Author.objects.create(name="a1", num=1, extra=e1) qs = Author.objects.select_related("extra").order_by() self.assertEqual(qs.union(qs).count(), 1) @skipUnlessDBFeature("supports_select_difference") def test_count_difference(self): qs1 = Number.objects.filter(num__lt=10) qs2 = Number.objects.filter(num__lt=9) self.assertEqual(qs1.difference(qs2).count(), 1) @skipUnlessDBFeature("supports_select_intersection") def test_count_intersection(self): qs1 = Number.objects.filter(num__gte=5) qs2 = Number.objects.filter(num__lte=5) self.assertEqual(qs1.intersection(qs2).count(), 1) def test_exists_union(self): qs1 = Number.objects.filter(num__gte=5) qs2 = Number.objects.filter(num__lte=5) with CaptureQueriesContext(connection) as context: self.assertIs(qs1.union(qs2).exists(), True) captured_queries = context.captured_queries self.assertEqual(len(captured_queries), 1) captured_sql = captured_queries[0]["sql"] self.assertNotIn( connection.ops.quote_name(Number._meta.pk.column), captured_sql, ) self.assertEqual( captured_sql.count(connection.ops.limit_offset_sql(None, 1)), 1 ) def test_exists_union_empty_result(self): qs = Number.objects.filter(pk__in=[]) self.assertIs(qs.union(qs).exists(), False) @skipUnlessDBFeature("supports_select_intersection") def test_exists_intersection(self): qs1 = Number.objects.filter(num__gt=5) qs2 = Number.objects.filter(num__lt=5) self.assertIs(qs1.intersection(qs1).exists(), True) self.assertIs(qs1.intersection(qs2).exists(), False) @skipUnlessDBFeature("supports_select_difference") def test_exists_difference(self): qs1 = Number.objects.filter(num__gte=5) qs2 = Number.objects.filter(num__gte=3) self.assertIs(qs1.difference(qs2).exists(), False) self.assertIs(qs2.difference(qs1).exists(), True) def test_get_union(self): qs = Number.objects.filter(num=2) self.assertEqual(qs.union(qs).get().num, 2) @skipUnlessDBFeature("supports_select_difference") def test_get_difference(self): qs1 = Number.objects.all() qs2 = Number.objects.exclude(num=2) self.assertEqual(qs1.difference(qs2).get().num, 2) @skipUnlessDBFeature("supports_select_intersection") def test_get_intersection(self): qs1 = Number.objects.all() qs2 = Number.objects.filter(num=2) self.assertEqual(qs1.intersection(qs2).get().num, 2) @skipUnlessDBFeature("supports_slicing_ordering_in_compound") def test_ordering_subqueries(self): qs1 = Number.objects.order_by("num")[:2] qs2 = Number.objects.order_by("-num")[:2] self.assertNumbersEqual(qs1.union(qs2).order_by("-num")[:4], [9, 8, 1, 0]) @skipIfDBFeature("supports_slicing_ordering_in_compound") def test_unsupported_ordering_slicing_raises_db_error(self): qs1 = Number.objects.all() qs2 = Number.objects.all() qs3 = Number.objects.all() msg = "LIMIT/OFFSET not allowed in subqueries of compound statements" with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2[:10])) msg = "ORDER BY not allowed in subqueries of compound statements" with self.assertRaisesMessage(DatabaseError, msg): list(qs1.order_by("id").union(qs2)) with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by("id").union(qs3)) @skipIfDBFeature("supports_select_intersection") def test_unsupported_intersection_raises_db_error(self): qs1 = Number.objects.all() qs2 = Number.objects.all() msg = "intersection is not supported on this database backend" with self.assertRaisesMessage(NotSupportedError, msg): list(qs1.intersection(qs2)) def test_combining_multiple_models(self): ReservedName.objects.create(name="99 little bugs", order=99) qs1 = Number.objects.filter(num=1).values_list("num", flat=True) qs2 = ReservedName.objects.values_list("order") self.assertEqual(list(qs1.union(qs2).order_by("num")), [1, 99]) def test_order_raises_on_non_selected_column(self): qs1 = ( Number.objects.filter() .annotate( annotation=Value(1, IntegerField()), ) .values("annotation", num2=F("num")) ) qs2 = Number.objects.filter().values("id", "num") # Should not raise list(qs1.union(qs2).order_by("annotation")) list(qs1.union(qs2).order_by("num2")) msg = "ORDER BY term does not match any column in the result set" # 'id' is not part of the select with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by("id")) # 'num' got realiased to num2 with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by("num")) with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by(F("num"))) with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by(F("num").desc())) # switched order, now 'exists' again: list(qs2.union(qs1).order_by("num")) @skipUnlessDBFeature("supports_select_difference", "supports_select_intersection") def test_qs_with_subcompound_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.intersection(Number.objects.filter(num__gt=1)) self.assertEqual(qs1.difference(qs2).count(), 2) def test_order_by_same_type(self): qs = Number.objects.all() union = qs.union(qs) numbers = list(range(10)) self.assertNumbersEqual(union.order_by("num"), numbers) self.assertNumbersEqual(union.order_by("other_num"), reversed(numbers)) def test_unsupported_operations_on_combined_qs(self): qs = Number.objects.all() msg = "Calling QuerySet.%s() after %s() is not supported." combinators = ["union"] if connection.features.supports_select_difference: combinators.append("difference") if connection.features.supports_select_intersection: combinators.append("intersection") for combinator in combinators: for operation in ( "alias", "annotate", "defer", "delete", "distinct", "exclude", "extra", "filter", "only", "prefetch_related", "select_related", "update", ): with self.subTest(combinator=combinator, operation=operation): with self.assertRaisesMessage( NotSupportedError, msg % (operation, combinator), ): getattr(getattr(qs, combinator)(qs), operation)() with self.assertRaisesMessage( NotSupportedError, msg % ("contains", combinator), ): obj = Number.objects.first() getattr(qs, combinator)(qs).contains(obj) def test_get_with_filters_unsupported_on_combined_qs(self): qs = Number.objects.all() msg = "Calling QuerySet.get(...) with filters after %s() is not supported." combinators = ["union"] if connection.features.supports_select_difference: combinators.append("difference") if connection.features.supports_select_intersection: combinators.append("intersection") for combinator in combinators: with self.subTest(combinator=combinator): with self.assertRaisesMessage(NotSupportedError, msg % combinator): getattr(qs, combinator)(qs).get(num=2) def test_operator_on_combined_qs_error(self): qs = Number.objects.all() msg = "Cannot use %s operator with combined queryset." combinators = ["union"] if connection.features.supports_select_difference: combinators.append("difference") if connection.features.supports_select_intersection: combinators.append("intersection") operators = [ ("|", operator.or_), ("&", operator.and_), ("^", operator.xor), ] for combinator in combinators: combined_qs = getattr(qs, combinator)(qs) for operator_, operator_func in operators: with self.subTest(combinator=combinator): with self.assertRaisesMessage(TypeError, msg % operator_): operator_func(qs, combined_qs) with self.assertRaisesMessage(TypeError, msg % operator_): operator_func(combined_qs, qs)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/queries/test_db_returning.py
tests/queries/test_db_returning.py
import datetime from django.db import connection from django.test import TestCase, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from .models import DumbCategory, NonIntegerPKReturningModel, ReturningModel @skipUnlessDBFeature("can_return_columns_from_insert") class ReturningValuesTests(TestCase): def test_insert_returning(self): with CaptureQueriesContext(connection) as captured_queries: DumbCategory.objects.create() self.assertIn( "RETURNING %s.%s" % ( connection.ops.quote_name(DumbCategory._meta.db_table), connection.ops.quote_name(DumbCategory._meta.get_field("id").column), ), captured_queries[-1]["sql"], ) def test_insert_returning_non_integer(self): obj = NonIntegerPKReturningModel.objects.create() self.assertTrue(obj.created) self.assertIsInstance(obj.created, datetime.datetime) def test_insert_returning_non_integer_from_literal_value(self): obj = NonIntegerPKReturningModel.objects.create(pk="2025-01-01") self.assertTrue(obj.created) self.assertIsInstance(obj.created, datetime.datetime) def test_insert_returning_multiple(self): with CaptureQueriesContext(connection) as captured_queries: obj = ReturningModel.objects.create() table_name = connection.ops.quote_name(ReturningModel._meta.db_table) self.assertIn( "RETURNING %s.%s, %s.%s" % ( table_name, connection.ops.quote_name(ReturningModel._meta.get_field("id").column), table_name, connection.ops.quote_name( ReturningModel._meta.get_field("created").column ), ), captured_queries[-1]["sql"], ) self.assertEqual( captured_queries[-1]["sql"] .split("RETURNING ")[1] .count( connection.ops.quote_name( ReturningModel._meta.get_field("created").column ), ), 1, ) self.assertTrue(obj.pk) self.assertIsInstance(obj.created, datetime.datetime) @skipUnlessDBFeature("can_return_rows_from_bulk_insert") def test_bulk_insert(self): objs = [ReturningModel(), ReturningModel(pk=2**11), ReturningModel()] ReturningModel.objects.bulk_create(objs) for obj in objs: with self.subTest(obj=obj): self.assertTrue(obj.pk) self.assertIsInstance(obj.created, datetime.datetime)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/queries/test_explain.py
tests/queries/test_explain.py
import json import unittest import xml.etree.ElementTree from django.db import NotSupportedError, connection, transaction from django.db.models import Count from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from .models import Tag @skipUnlessDBFeature("supports_explaining_query_execution") class ExplainTests(TestCase): def test_basic(self): querysets = [ Tag.objects.filter(name="test"), Tag.objects.filter(name="test").select_related("parent"), Tag.objects.filter(name="test").prefetch_related("children"), Tag.objects.filter(name="test").annotate(Count("children")), Tag.objects.filter(name="test").values_list("name"), ] if connection.features.supports_select_union: querysets.append( Tag.objects.order_by().union(Tag.objects.order_by().filter(name="test")) ) if connection.features.has_select_for_update: querysets.append(Tag.objects.select_for_update().filter(name="test")) supported_formats = connection.features.supported_explain_formats all_formats = ( (None,) + tuple(supported_formats) + tuple(f.lower() for f in supported_formats) ) for idx, queryset in enumerate(querysets): for format in all_formats: with self.subTest(format=format, queryset=idx): with self.assertNumQueries(1) as captured_queries: result = queryset.explain(format=format) self.assertTrue( captured_queries[0]["sql"].startswith( connection.ops.explain_prefix ) ) self.assertIsInstance(result, str) self.assertTrue(result) if not format: continue if format.lower() == "xml": try: xml.etree.ElementTree.fromstring(result) except xml.etree.ElementTree.ParseError as e: self.fail( f"QuerySet.explain() result is not valid XML: {e}" ) elif format.lower() == "json": try: json.loads(result) except json.JSONDecodeError as e: self.fail( f"QuerySet.explain() result is not valid JSON: {e}" ) def test_unknown_options(self): with self.assertRaisesMessage(ValueError, "Unknown options: TEST, TEST2"): Tag.objects.explain(**{"TEST": 1, "TEST2": 1}) def test_unknown_format(self): msg = "DOES NOT EXIST is not a recognized format." if connection.features.supported_explain_formats: msg += " Allowed formats: %s" % ", ".join( sorted(connection.features.supported_explain_formats) ) else: msg += f" {connection.display_name} does not support any formats." with self.assertRaisesMessage(ValueError, msg): Tag.objects.explain(format="does not exist") @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_postgres_options(self): qs = Tag.objects.filter(name="test") test_options = [ {"COSTS": False, "BUFFERS": True, "ANALYZE": True}, {"costs": False, "buffers": True, "analyze": True}, {"verbose": True, "timing": True, "analyze": True}, {"verbose": False, "timing": False, "analyze": True}, {"summary": True}, {"settings": True}, {"analyze": True, "wal": True}, ] if connection.features.is_postgresql_16: test_options.append({"generic_plan": True}) if connection.features.is_postgresql_17: test_options.append({"memory": True}) test_options.append({"serialize": "TEXT", "analyze": True}) test_options.append({"serialize": "text", "analyze": True}) test_options.append({"serialize": "BINARY", "analyze": True}) test_options.append({"serialize": "binary", "analyze": True}) for options in test_options: with self.subTest(**options), transaction.atomic(): with CaptureQueriesContext(connection) as captured_queries: qs.explain(format="text", **options) self.assertEqual(len(captured_queries), 1) for name, value in options.items(): if isinstance(value, str): option = "{} {}".format(name.upper(), value.upper()) else: option = "{} {}".format( name.upper(), "true" if value else "false" ) self.assertIn(option, captured_queries[0]["sql"]) @skipUnlessDBFeature("supports_select_union") def test_multi_page_text_explain(self): if "TEXT" not in connection.features.supported_explain_formats: self.skipTest("This backend does not support TEXT format.") base_qs = Tag.objects.order_by() qs = base_qs.filter(name="test").union(*[base_qs for _ in range(100)]) result = qs.explain(format="text") self.assertGreaterEqual(result.count("\n"), 100) def test_option_sql_injection(self): qs = Tag.objects.filter(name="test") options = {"SUMMARY true) SELECT 1; --": True} msg = "Invalid option name: 'SUMMARY true) SELECT 1; --'" with self.assertRaisesMessage(ValueError, msg): qs.explain(**options) def test_invalid_option_names(self): qs = Tag.objects.filter(name="test") tests = [ 'opt"ion', "o'ption", "op`tion", "opti on", "option--", "optio\tn", "o\nption", "option;", "你 好", # [] are used by MSSQL. "option[", "option]", ] for invalid_option in tests: with self.subTest(invalid_option): msg = f"Invalid option name: {invalid_option!r}" with self.assertRaisesMessage(ValueError, msg): qs.explain(**{invalid_option: True}) @unittest.skipUnless(connection.vendor == "mysql", "MySQL specific") def test_mysql_text_to_traditional(self): # Ensure these cached properties are initialized to prevent queries for # the MariaDB or MySQL version during the QuerySet evaluation. connection.features.supported_explain_formats with CaptureQueriesContext(connection) as captured_queries: Tag.objects.filter(name="test").explain(format="text") self.assertEqual(len(captured_queries), 1) self.assertIn("FORMAT=TRADITIONAL", captured_queries[0]["sql"]) @unittest.skipUnless(connection.vendor == "mysql", "MySQL specific") def test_mysql_analyze(self): qs = Tag.objects.filter(name="test") with CaptureQueriesContext(connection) as captured_queries: qs.explain(analyze=True) self.assertEqual(len(captured_queries), 1) prefix = "ANALYZE " if connection.mysql_is_mariadb else "EXPLAIN ANALYZE " self.assertTrue(captured_queries[0]["sql"].startswith(prefix)) with CaptureQueriesContext(connection) as captured_queries: qs.explain(analyze=True, format="JSON") self.assertEqual(len(captured_queries), 1) if connection.mysql_is_mariadb: self.assertIn("FORMAT=JSON", captured_queries[0]["sql"]) else: self.assertNotIn("FORMAT=JSON", captured_queries[0]["sql"]) @skipIfDBFeature("supports_explaining_query_execution") class ExplainUnsupportedTests(TestCase): def test_message(self): msg = "This backend does not support explaining query execution." with self.assertRaisesMessage(NotSupportedError, msg): Tag.objects.filter(name="test").explain()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/queries/__init__.py
tests/queries/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/queries/tests.py
tests/queries/tests.py
import datetime import pickle import sys import unittest from operator import attrgetter from django.core.exceptions import EmptyResultSet, FieldError, FullResultSet from django.db import DEFAULT_DB_ALIAS, connection from django.db.models import CharField, Count, Exists, F, Max, OuterRef, Q from django.db.models.expressions import RawSQL from django.db.models.functions import ExtractYear, Length, LTrim from django.db.models.sql.constants import LOUTER from django.db.models.sql.where import AND, OR, NothingNode, WhereNode from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext, register_lookup from .models import ( FK1, Annotation, Article, Author, BaseA, BaseUser, Book, CategoryItem, CategoryRelationship, Celebrity, Channel, Chapter, Child, ChildObjectA, Classroom, CommonMixedCaseForeignKeys, Company, Cover, CustomPk, CustomPkTag, DateTimePK, Detail, DumbCategory, Eaten, Employment, ExtraInfo, Fan, Food, Identifier, Individual, Item, Job, JobResponsibilities, Join, LeafA, LeafB, LoopX, LoopZ, ManagedModel, Member, MixedCaseDbColumnCategoryItem, MixedCaseFieldCategoryItem, ModelA, ModelB, ModelC, ModelD, MyObject, NamedCategory, Node, Note, NullableName, Number, ObjectA, ObjectB, ObjectC, OneToOneCategory, Order, OrderItem, Page, Paragraph, Person, Plaything, PointerA, Program, ProxyCategory, ProxyObjectA, ProxyObjectB, Ranking, Related, RelatedIndividual, RelatedObject, Report, ReportComment, ReservedName, Responsibility, School, SharedConnection, SimpleCategory, SingleObject, SpecialCategory, Staff, StaffUser, Student, Tag, Task, Teacher, Ticket21203Child, Ticket21203Parent, Ticket23605A, Ticket23605B, Ticket23605C, TvChef, Valid, X, ) class UnpickleableError(Exception): def __reduce__(self): raise type(self)("Cannot pickle.") class Queries1Tests(TestCase): @classmethod def setUpTestData(cls): cls.nc1 = generic = NamedCategory.objects.create(name="Generic") cls.t1 = Tag.objects.create(name="t1", category=generic) cls.t2 = Tag.objects.create(name="t2", parent=cls.t1, category=generic) cls.t3 = Tag.objects.create(name="t3", parent=cls.t1) cls.t4 = Tag.objects.create(name="t4", parent=cls.t3) cls.t5 = Tag.objects.create(name="t5", parent=cls.t3) cls.n1 = Note.objects.create(note="n1", misc="foo", id=1) cls.n2 = Note.objects.create(note="n2", misc="bar", id=2) cls.n3 = Note.objects.create(note="n3", misc="foo", id=3, negate=False) cls.ann1 = Annotation.objects.create(name="a1", tag=cls.t1) cls.ann1.notes.add(cls.n1) ann2 = Annotation.objects.create(name="a2", tag=cls.t4) ann2.notes.add(cls.n2, cls.n3) # Create these out of order so that sorting by 'id' will be different # to sorting by 'info'. Helps detect some problems later. cls.e2 = ExtraInfo.objects.create( info="e2", note=cls.n2, value=41, filterable=False ) e1 = ExtraInfo.objects.create(info="e1", note=cls.n1, value=42) cls.a1 = Author.objects.create(name="a1", num=1001, extra=e1) cls.a2 = Author.objects.create(name="a2", num=2002, extra=e1) cls.a3 = Author.objects.create(name="a3", num=3003, extra=cls.e2) cls.a4 = Author.objects.create(name="a4", num=4004, extra=cls.e2) cls.time1 = datetime.datetime(2007, 12, 19, 22, 25, 0) cls.time2 = datetime.datetime(2007, 12, 19, 21, 0, 0) time3 = datetime.datetime(2007, 12, 20, 22, 25, 0) time4 = datetime.datetime(2007, 12, 20, 21, 0, 0) cls.i1 = Item.objects.create( name="one", created=cls.time1, modified=cls.time1, creator=cls.a1, note=cls.n3, ) cls.i1.tags.set([cls.t1, cls.t2]) cls.i2 = Item.objects.create( name="two", created=cls.time2, creator=cls.a2, note=cls.n2 ) cls.i2.tags.set([cls.t1, cls.t3]) cls.i3 = Item.objects.create( name="three", created=time3, creator=cls.a2, note=cls.n3 ) cls.i4 = Item.objects.create( name="four", created=time4, creator=cls.a4, note=cls.n3 ) cls.i4.tags.set([cls.t4]) cls.r1 = Report.objects.create(name="r1", creator=cls.a1) cls.r2 = Report.objects.create(name="r2", creator=cls.a3) cls.r3 = Report.objects.create(name="r3") # Ordering by 'rank' gives us rank2, rank1, rank3. Ordering by the # Meta.ordering will be rank3, rank2, rank1. cls.rank1 = Ranking.objects.create(rank=2, author=cls.a2) cls.c1 = Cover.objects.create(title="first", item=cls.i4) cls.c2 = Cover.objects.create(title="second", item=cls.i2) def test_subquery_condition(self): qs1 = Tag.objects.filter(pk__lte=0) qs2 = Tag.objects.filter(parent__in=qs1) qs3 = Tag.objects.filter(parent__in=qs2) self.assertEqual(qs3.query.subq_aliases, {"T", "U", "V"}) self.assertIn("v0", str(qs3.query).lower()) qs4 = qs3.filter(parent__in=qs1) self.assertEqual(qs4.query.subq_aliases, {"T", "U", "V"}) # It is possible to reuse U for the second subquery, no need to use W. self.assertNotIn("w0", str(qs4.query).lower()) # So, 'U0."id"' is referenced in SELECT and WHERE twice. self.assertEqual(str(qs4.query).lower().count("u0."), 4) def test_ticket1050(self): self.assertSequenceEqual( Item.objects.filter(tags__isnull=True), [self.i3], ) self.assertSequenceEqual( Item.objects.filter(tags__id__isnull=True), [self.i3], ) def test_ticket1801(self): self.assertSequenceEqual( Author.objects.filter(item=self.i2), [self.a2], ) self.assertSequenceEqual( Author.objects.filter(item=self.i3), [self.a2], ) self.assertSequenceEqual( Author.objects.filter(item=self.i2) & Author.objects.filter(item=self.i3), [self.a2], ) def test_ticket2306(self): # Checking that no join types are "left outer" joins. query = Item.objects.filter(tags=self.t2).query self.assertNotIn(LOUTER, [x.join_type for x in query.alias_map.values()]) self.assertSequenceEqual( Item.objects.filter(Q(tags=self.t1)).order_by("name"), [self.i1, self.i2], ) self.assertSequenceEqual( Item.objects.filter(Q(tags=self.t1)).filter(Q(tags=self.t2)), [self.i1], ) self.assertSequenceEqual( Item.objects.filter(Q(tags=self.t1)).filter( Q(creator__name="fred") | Q(tags=self.t2) ), [self.i1], ) # Each filter call is processed "at once" against a single table, so # this is different from the previous example as it tries to find tags # that are two things at once (rather than two tags). self.assertSequenceEqual( Item.objects.filter(Q(tags=self.t1) & Q(tags=self.t2)), [] ) self.assertSequenceEqual( Item.objects.filter( Q(tags=self.t1), Q(creator__name="fred") | Q(tags=self.t2) ), [], ) qs = Author.objects.filter(ranking__rank=2, ranking__id=self.rank1.id) self.assertSequenceEqual(list(qs), [self.a2]) self.assertEqual(2, qs.query.count_active_tables(), 2) qs = Author.objects.filter(ranking__rank=2).filter(ranking__id=self.rank1.id) self.assertEqual(qs.query.count_active_tables(), 3) def test_ticket4464(self): self.assertSequenceEqual( Item.objects.filter(tags=self.t1).filter(tags=self.t2), [self.i1], ) self.assertSequenceEqual( Item.objects.filter(tags__in=[self.t1, self.t2]) .distinct() .order_by("name"), [self.i1, self.i2], ) self.assertSequenceEqual( Item.objects.filter(tags__in=[self.t1, self.t2]).filter(tags=self.t3), [self.i2], ) # Make sure .distinct() works with slicing (this was broken in Oracle). self.assertSequenceEqual( Item.objects.filter(tags__in=[self.t1, self.t2]).order_by("name")[:3], [self.i1, self.i1, self.i2], ) self.assertSequenceEqual( Item.objects.filter(tags__in=[self.t1, self.t2]) .distinct() .order_by("name")[:3], [self.i1, self.i2], ) def test_tickets_2080_3592(self): self.assertSequenceEqual( Author.objects.filter(item__name="one") | Author.objects.filter(name="a3"), [self.a1, self.a3], ) self.assertSequenceEqual( Author.objects.filter(Q(item__name="one") | Q(name="a3")), [self.a1, self.a3], ) self.assertSequenceEqual( Author.objects.filter(Q(name="a3") | Q(item__name="one")), [self.a1, self.a3], ) self.assertSequenceEqual( Author.objects.filter(Q(item__name="three") | Q(report__name="r3")), [self.a2], ) def test_ticket6074(self): # Merging two empty result sets shouldn't leave a queryset with no # constraints (which would match everything). self.assertSequenceEqual(Author.objects.filter(Q(id__in=[])), []) self.assertSequenceEqual(Author.objects.filter(Q(id__in=[]) | Q(id__in=[])), []) def test_tickets_1878_2939(self): self.assertEqual(Item.objects.values("creator").distinct().count(), 3) # Create something with a duplicate 'name' so that we can test # multi-column cases (which require some tricky SQL transformations # under the covers). xx = Item(name="four", created=self.time1, creator=self.a2, note=self.n1) xx.save() self.assertEqual( Item.objects.exclude(name="two") .values("creator", "name") .distinct() .count(), 4, ) self.assertEqual( ( Item.objects.exclude(name="two") .extra(select={"foo": "%s"}, select_params=(1,)) .values("creator", "name", "foo") .distinct() .count() ), 4, ) self.assertEqual( ( Item.objects.exclude(name="two") .extra(select={"foo": "%s"}, select_params=(1,)) .values("creator", "name") .distinct() .count() ), 4, ) xx.delete() def test_ticket7323(self): self.assertEqual(Item.objects.values("creator", "name").count(), 4) def test_ticket2253(self): q1 = Item.objects.order_by("name") q2 = Item.objects.filter(id=self.i1.id) self.assertSequenceEqual(q1, [self.i4, self.i1, self.i3, self.i2]) self.assertSequenceEqual(q2, [self.i1]) self.assertSequenceEqual( (q1 | q2).order_by("name"), [self.i4, self.i1, self.i3, self.i2], ) self.assertSequenceEqual((q1 & q2).order_by("name"), [self.i1]) q1 = Item.objects.filter(tags=self.t1) q2 = Item.objects.filter(note=self.n3, tags=self.t2) q3 = Item.objects.filter(creator=self.a4) self.assertSequenceEqual( ((q1 & q2) | q3).order_by("name"), [self.i4, self.i1], ) def test_order_by_tables(self): q1 = Item.objects.order_by("name") q2 = Item.objects.filter(id=self.i1.id) list(q2) combined_query = (q1 & q2).order_by("name").query self.assertEqual( len( [ t for t in combined_query.alias_map if combined_query.alias_refcount[t] ] ), 1, ) def test_order_by_join_unref(self): """ This test is related to the above one, testing that there aren't old JOINs in the query. """ qs = Celebrity.objects.order_by("greatest_fan__fan_of") self.assertIn("OUTER JOIN", str(qs.query)) qs = qs.order_by("id") self.assertNotIn("OUTER JOIN", str(qs.query)) def test_order_by_related_field_transform(self): extra_12 = ExtraInfo.objects.create( info="extra 12", date=DateTimePK.objects.create(date=datetime.datetime(2021, 12, 10)), ) extra_11 = ExtraInfo.objects.create( info="extra 11", date=DateTimePK.objects.create(date=datetime.datetime(2022, 11, 10)), ) self.assertSequenceEqual( ExtraInfo.objects.filter(date__isnull=False).order_by("date__month"), [extra_11, extra_12], ) def test_filter_by_related_field_transform(self): extra_old = ExtraInfo.objects.create( info="extra 12", date=DateTimePK.objects.create(date=datetime.datetime(2020, 12, 10)), ) ExtraInfo.objects.create(info="extra 11", date=DateTimePK.objects.create()) a5 = Author.objects.create(name="a5", num=5005, extra=extra_old) fk_field = ExtraInfo._meta.get_field("date") with register_lookup(fk_field, ExtractYear): self.assertSequenceEqual( ExtraInfo.objects.filter(date__year=2020), [extra_old], ) self.assertSequenceEqual( Author.objects.filter(extra__date__year=2020), [a5] ) def test_filter_by_related_field_nested_transforms(self): extra = ExtraInfo.objects.create(info=" extra") a5 = Author.objects.create(name="a5", num=5005, extra=extra) info_field = ExtraInfo._meta.get_field("info") with register_lookup(info_field, Length), register_lookup(CharField, LTrim): self.assertSequenceEqual( Author.objects.filter(extra__info__ltrim__length=5), [a5] ) def test_get_clears_ordering(self): """ get() should clear ordering for optimization purposes. """ with CaptureQueriesContext(connection) as captured_queries: Author.objects.order_by("name").get(pk=self.a1.pk) self.assertNotIn("order by", captured_queries[0]["sql"].lower()) def test_tickets_4088_4306(self): self.assertSequenceEqual(Report.objects.filter(creator=1001), [self.r1]) self.assertSequenceEqual(Report.objects.filter(creator__num=1001), [self.r1]) self.assertSequenceEqual(Report.objects.filter(creator__id=1001), []) self.assertSequenceEqual( Report.objects.filter(creator__id=self.a1.id), [self.r1] ) self.assertSequenceEqual(Report.objects.filter(creator__name="a1"), [self.r1]) def test_ticket4510(self): self.assertSequenceEqual( Author.objects.filter(report__name="r1"), [self.a1], ) def test_ticket7378(self): self.assertSequenceEqual(self.a1.report_set.all(), [self.r1]) def test_tickets_5324_6704(self): self.assertSequenceEqual( Item.objects.filter(tags__name="t4"), [self.i4], ) self.assertSequenceEqual( Item.objects.exclude(tags__name="t4").order_by("name").distinct(), [self.i1, self.i3, self.i2], ) self.assertSequenceEqual( Item.objects.exclude(tags__name="t4").order_by("name").distinct().reverse(), [self.i2, self.i3, self.i1], ) self.assertSequenceEqual( Author.objects.exclude(item__name="one").distinct().order_by("name"), [self.a2, self.a3, self.a4], ) # Excluding across a m2m relation when there is more than one related # object associated was problematic. self.assertSequenceEqual( Item.objects.exclude(tags__name="t1").order_by("name"), [self.i4, self.i3], ) self.assertSequenceEqual( Item.objects.exclude(tags__name="t1").exclude(tags__name="t4"), [self.i3], ) # Excluding from a relation that cannot be NULL should not use outer # joins. query = Item.objects.exclude(creator__in=[self.a1, self.a2]).query self.assertNotIn(LOUTER, [x.join_type for x in query.alias_map.values()]) # Similarly, when one of the joins cannot possibly, ever, involve NULL # values (Author -> ExtraInfo, in the following), it should never be # promoted to a left outer join. So the following query should only # involve one "left outer" join (Author -> Item is 0-to-many). qs = Author.objects.filter(id=self.a1.id).filter( Q(extra__note=self.n1) | Q(item__note=self.n3) ) self.assertEqual( len( [ x for x in qs.query.alias_map.values() if x.join_type == LOUTER and qs.query.alias_refcount[x.table_alias] ] ), 1, ) # The previous changes shouldn't affect nullable foreign key joins. self.assertSequenceEqual( Tag.objects.filter(parent__isnull=True).order_by("name"), [self.t1] ) self.assertSequenceEqual( Tag.objects.exclude(parent__isnull=True).order_by("name"), [self.t2, self.t3, self.t4, self.t5], ) self.assertSequenceEqual( Tag.objects.exclude(Q(parent__name="t1") | Q(parent__isnull=True)).order_by( "name" ), [self.t4, self.t5], ) self.assertSequenceEqual( Tag.objects.exclude(Q(parent__isnull=True) | Q(parent__name="t1")).order_by( "name" ), [self.t4, self.t5], ) self.assertSequenceEqual( Tag.objects.exclude(Q(parent__parent__isnull=True)).order_by("name"), [self.t4, self.t5], ) self.assertSequenceEqual( Tag.objects.filter(~Q(parent__parent__isnull=True)).order_by("name"), [self.t4, self.t5], ) def test_ticket2091(self): t = Tag.objects.get(name="t4") self.assertSequenceEqual(Item.objects.filter(tags__in=[t]), [self.i4]) def test_avoid_infinite_loop_on_too_many_subqueries(self): x = Tag.objects.filter(pk=1) local_recursion_limit = sys.getrecursionlimit() // 16 msg = "Maximum recursion depth exceeded: too many subqueries." with self.assertRaisesMessage(RecursionError, msg): for i in range(local_recursion_limit + 2): x = Tag.objects.filter(pk__in=x) def test_reasonable_number_of_subq_aliases(self): x = Tag.objects.filter(pk=1) for _ in range(20): x = Tag.objects.filter(pk__in=x) self.assertEqual( x.query.subq_aliases, { "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", }, ) def test_heterogeneous_qs_combination(self): # Combining querysets built on different models should behave in a # well-defined fashion. We raise an error. msg = "Cannot combine queries on two different base models." with self.assertRaisesMessage(TypeError, msg): Author.objects.all() & Tag.objects.all() with self.assertRaisesMessage(TypeError, msg): Author.objects.all() | Tag.objects.all() def test_ticket3141(self): self.assertEqual(Author.objects.extra(select={"foo": "1"}).count(), 4) self.assertEqual( Author.objects.extra(select={"foo": "%s"}, select_params=(1,)).count(), 4 ) def test_ticket2400(self): self.assertSequenceEqual( Author.objects.filter(item__isnull=True), [self.a3], ) self.assertSequenceEqual( Tag.objects.filter(item__isnull=True), [self.t5], ) def test_ticket2496(self): self.assertSequenceEqual( Item.objects.extra(tables=["queries_author"]) .select_related() .order_by("name")[:1], [self.i4], ) def test_error_raised_on_filter_with_dictionary(self): with self.assertRaisesMessage(FieldError, "Cannot parse keyword query as dict"): Note.objects.filter({"note": "n1", "misc": "foo"}) def test_tickets_2076_7256(self): # Ordering on related tables should be possible, even if the table is # not otherwise involved. self.assertSequenceEqual( Item.objects.order_by("note__note", "name"), [self.i2, self.i4, self.i1, self.i3], ) # Ordering on a related field should use the remote model's default # ordering as a final step. self.assertSequenceEqual( Author.objects.order_by("extra", "-name"), [self.a2, self.a1, self.a4, self.a3], ) # Using remote model default ordering can span multiple models (in this # case, Cover is ordered by Item's default, which uses Note's default). self.assertSequenceEqual(Cover.objects.all(), [self.c1, self.c2]) # If the remote model does not have a default ordering, we order by its # 'id' field. self.assertSequenceEqual( Item.objects.order_by("creator", "name"), [self.i1, self.i3, self.i2, self.i4], ) # Ordering by a many-valued attribute (e.g. a many-to-many or reverse # ForeignKey) is legal, but the results might not make sense. That # isn't Django's problem. Garbage in, garbage out. self.assertSequenceEqual( Item.objects.filter(tags__isnull=False).order_by("tags", "id"), [self.i1, self.i2, self.i1, self.i2, self.i4], ) # If we replace the default ordering, Django adjusts the required # tables automatically. Item normally requires a join with Note to do # the default ordering, but that isn't needed here. qs = Item.objects.order_by("name") self.assertSequenceEqual(qs, [self.i4, self.i1, self.i3, self.i2]) self.assertEqual(len(qs.query.alias_map), 1) def test_tickets_2874_3002(self): qs = Item.objects.select_related().order_by("note__note", "name") self.assertQuerySetEqual(qs, [self.i2, self.i4, self.i1, self.i3]) # This is also a good select_related() test because there are multiple # Note entries in the SQL. The two Note items should be different. self.assertEqual(repr(qs[0].note), "<Note: n2>") self.assertEqual(repr(qs[0].creator.extra.note), "<Note: n1>") def test_ticket3037(self): self.assertSequenceEqual( Item.objects.filter( Q(creator__name="a3", name="two") | Q(creator__name="a4", name="four") ), [self.i4], ) def test_tickets_5321_7070(self): # Ordering columns must be included in the output columns. Note that # this means results that might otherwise be distinct are not (if there # are multiple values in the ordering cols), as in this example. This # isn't a bug; it's a warning to be careful with the selection of # ordering columns. self.assertSequenceEqual( Note.objects.values("misc").distinct().order_by("note", "-misc"), [{"misc": "foo"}, {"misc": "bar"}, {"misc": "foo"}], ) def test_ticket4358(self): # If you don't pass any fields to values(), relation fields are # returned as "foo_id" keys, not "foo". For consistency, you should be # able to pass "foo_id" in the fields list and have it work, too. We # actually allow both "foo" and "foo_id". # The *_id version is returned by default. self.assertIn("note_id", ExtraInfo.objects.values()[0]) # You can also pass it in explicitly. self.assertSequenceEqual( ExtraInfo.objects.values("note_id"), [{"note_id": 1}, {"note_id": 2}] ) # ...or use the field name. self.assertSequenceEqual( ExtraInfo.objects.values("note"), [{"note": 1}, {"note": 2}] ) def test_ticket6154(self): # Multiple filter statements are joined using "AND" all the time. self.assertSequenceEqual( Author.objects.filter(id=self.a1.id).filter( Q(extra__note=self.n1) | Q(item__note=self.n3) ), [self.a1], ) self.assertSequenceEqual( Author.objects.filter( Q(extra__note=self.n1) | Q(item__note=self.n3) ).filter(id=self.a1.id), [self.a1], ) def test_ticket6981(self): self.assertSequenceEqual( Tag.objects.select_related("parent").order_by("name"), [self.t1, self.t2, self.t3, self.t4, self.t5], ) def test_ticket9926(self): self.assertSequenceEqual( Tag.objects.select_related("parent", "category").order_by("name"), [self.t1, self.t2, self.t3, self.t4, self.t5], ) self.assertSequenceEqual( Tag.objects.select_related("parent", "parent__category").order_by("name"), [self.t1, self.t2, self.t3, self.t4, self.t5], ) def test_tickets_6180_6203(self): # Dates with limits and/or counts self.assertEqual(Item.objects.count(), 4) self.assertEqual(Item.objects.datetimes("created", "month").count(), 1) self.assertEqual(Item.objects.datetimes("created", "day").count(), 2) self.assertEqual(len(Item.objects.datetimes("created", "day")), 2) self.assertEqual( Item.objects.datetimes("created", "day")[0], datetime.datetime(2007, 12, 19, 0, 0), ) def test_tickets_7087_12242(self): # Dates with extra select columns self.assertSequenceEqual( Item.objects.datetimes("created", "day").extra(select={"a": 1}), [ datetime.datetime(2007, 12, 19, 0, 0), datetime.datetime(2007, 12, 20, 0, 0), ], ) self.assertSequenceEqual( Item.objects.extra(select={"a": 1}).datetimes("created", "day"), [ datetime.datetime(2007, 12, 19, 0, 0), datetime.datetime(2007, 12, 20, 0, 0), ], ) name = "one" self.assertSequenceEqual( Item.objects.datetimes("created", "day").extra( where=["name=%s"], params=[name] ), [datetime.datetime(2007, 12, 19, 0, 0)], ) self.assertSequenceEqual( Item.objects.extra(where=["name=%s"], params=[name]).datetimes( "created", "day" ), [datetime.datetime(2007, 12, 19, 0, 0)], ) def test_ticket7155(self): # Nullable dates self.assertSequenceEqual( Item.objects.datetimes("modified", "day"), [datetime.datetime(2007, 12, 19, 0, 0)], ) def test_order_by_rawsql(self): self.assertSequenceEqual( Item.objects.values("note__note").order_by( RawSQL("queries_note.note", ()), "id", ), [ {"note__note": "n2"}, {"note__note": "n3"}, {"note__note": "n3"}, {"note__note": "n3"}, ], ) def test_ticket7096(self): # Make sure exclude() with multiple conditions continues to work. self.assertSequenceEqual( Tag.objects.filter(parent=self.t1, name="t3").order_by("name"), [self.t3], ) self.assertSequenceEqual( Tag.objects.exclude(parent=self.t1, name="t3").order_by("name"), [self.t1, self.t2, self.t4, self.t5], ) self.assertSequenceEqual( Item.objects.exclude(tags__name="t1", name="one") .order_by("name") .distinct(), [self.i4, self.i3, self.i2], ) self.assertSequenceEqual( Item.objects.filter(name__in=["three", "four"]) .exclude(tags__name="t1") .order_by("name"), [self.i4, self.i3], ) # More twisted cases, involving nested negations. self.assertSequenceEqual( Item.objects.exclude(~Q(tags__name="t1", name="one")), [self.i1], ) self.assertSequenceEqual( Item.objects.filter(~Q(tags__name="t1", name="one"), name="two"), [self.i2], ) self.assertSequenceEqual( Item.objects.exclude(~Q(tags__name="t1", name="one"), name="two"), [self.i4, self.i1, self.i3], ) def test_tickets_7204_7506(self): # Make sure querysets with related fields can be pickled. If this # doesn't crash, it's a Good Thing. pickle.dumps(Item.objects.all()) def test_ticket7813(self): # We should also be able to pickle things that use select_related(). # The only tricky thing here is to ensure that we do the related # selections properly after unpickling. qs = Item.objects.select_related() query = qs.query.get_compiler(qs.db).as_sql()[0] query2 = pickle.loads(pickle.dumps(qs.query)) self.assertEqual(query2.get_compiler(qs.db).as_sql()[0], query) def test_deferred_load_qs_pickling(self): # Check pickling of deferred-loading querysets qs = Item.objects.defer("name", "creator") q2 = pickle.loads(pickle.dumps(qs)) self.assertEqual(list(qs), list(q2)) q3 = pickle.loads(pickle.dumps(qs, pickle.HIGHEST_PROTOCOL)) self.assertEqual(list(qs), list(q3)) def test_ticket7277(self): self.assertSequenceEqual( self.n1.annotation_set.filter( Q(tag=self.t5) | Q(tag__children=self.t5) | Q(tag__children__children=self.t5) ), [self.ann1], ) def test_tickets_7448_7707(self): # Complex objects should be converted to strings before being used in # lookups. self.assertSequenceEqual( Item.objects.filter(created__in=[self.time1, self.time2]), [self.i1, self.i2], ) def test_ticket7235(self): # An EmptyQuerySet should not raise exceptions if it is filtered. Eaten.objects.create(meal="m") q = Eaten.objects.none() with self.assertNumQueries(0): self.assertSequenceEqual(q.all(), []) self.assertSequenceEqual(q.filter(meal="m"), []) self.assertSequenceEqual(q.exclude(meal="m"), []) self.assertSequenceEqual(q.complex_filter({"pk": 1}), []) self.assertSequenceEqual(q.select_related("food"), []) self.assertSequenceEqual(q.annotate(Count("food")), []) self.assertSequenceEqual(q.order_by("meal", "food"), []) self.assertSequenceEqual(q.distinct(), []) self.assertSequenceEqual(q.extra(select={"foo": "1"}), []) self.assertSequenceEqual(q.reverse(), []) q.query.low_mark = 1 msg = "Cannot change a query once a slice has been taken." with self.assertRaisesMessage(TypeError, msg): q.extra(select={"foo": "1"}) self.assertSequenceEqual(q.defer("meal"), []) self.assertSequenceEqual(q.only("meal"), []) def test_ticket7791(self):
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/queries/test_bulk_update.py
tests/queries/test_bulk_update.py
import datetime from math import ceil from django.core.exceptions import FieldDoesNotExist from django.db import connection from django.db.models import F, IntegerField, Value from django.db.models.functions import Coalesce, Lower from django.db.utils import IntegrityError from django.test import TestCase, override_settings, skipUnlessDBFeature from .models import ( Article, CustomDbColumn, CustomPk, Detail, Food, Individual, JSONFieldNullable, Member, Note, Number, Order, Paragraph, RelatedObject, SingleObject, SpecialCategory, Tag, Valid, ) class WriteToOtherRouter: def db_for_write(self, model, **hints): return "other" class BulkUpdateNoteTests(TestCase): @classmethod def setUpTestData(cls): cls.notes = [Note.objects.create(note=str(i), misc=str(i)) for i in range(10)] def create_tags(self): self.tags = [Tag.objects.create(name=str(i)) for i in range(10)] def test_simple(self): for note in self.notes: note.note = "test-%s" % note.id with self.assertNumQueries(1): Note.objects.bulk_update(self.notes, ["note"]) self.assertCountEqual( Note.objects.values_list("note", flat=True), [cat.note for cat in self.notes], ) def test_multiple_fields(self): for note in self.notes: note.note = "test-%s" % note.id note.misc = "misc-%s" % note.id with self.assertNumQueries(1): Note.objects.bulk_update(self.notes, ["note", "misc"]) self.assertCountEqual( Note.objects.values_list("note", flat=True), [cat.note for cat in self.notes], ) self.assertCountEqual( Note.objects.values_list("misc", flat=True), [cat.misc for cat in self.notes], ) def test_batch_size(self): with self.assertNumQueries(len(self.notes)): Note.objects.bulk_update(self.notes, fields=["note"], batch_size=1) def test_max_batch_size(self): max_batch_size = connection.ops.bulk_batch_size( # PK is used twice, see comment in bulk_update(). [Note._meta.pk, Note._meta.pk, Note._meta.get_field("note")], self.notes, ) with self.assertNumQueries(ceil(len(self.notes) / max_batch_size)): Note.objects.bulk_update(self.notes, fields=["note"]) def test_unsaved_models(self): objs = self.notes + [Note(note="test", misc="test")] msg = "All bulk_update() objects must have a primary key set." with self.assertRaisesMessage(ValueError, msg): Note.objects.bulk_update(objs, fields=["note"]) def test_foreign_keys_do_not_lookup(self): self.create_tags() for note, tag in zip(self.notes, self.tags): note.tag = tag with self.assertNumQueries(1): Note.objects.bulk_update(self.notes, ["tag"]) self.assertSequenceEqual(Note.objects.filter(tag__isnull=False), self.notes) def test_set_field_to_null(self): self.create_tags() Note.objects.update(tag=self.tags[0]) for note in self.notes: note.tag = None Note.objects.bulk_update(self.notes, ["tag"]) self.assertCountEqual(Note.objects.filter(tag__isnull=True), self.notes) def test_set_mixed_fields_to_null(self): self.create_tags() midpoint = len(self.notes) // 2 top, bottom = self.notes[:midpoint], self.notes[midpoint:] for note in top: note.tag = None for note in bottom: note.tag = self.tags[0] Note.objects.bulk_update(self.notes, ["tag"]) self.assertCountEqual(Note.objects.filter(tag__isnull=True), top) self.assertCountEqual(Note.objects.filter(tag__isnull=False), bottom) def test_functions(self): Note.objects.update(note="TEST") for note in self.notes: note.note = Lower("note") Note.objects.bulk_update(self.notes, ["note"]) self.assertEqual(set(Note.objects.values_list("note", flat=True)), {"test"}) # Tests that use self.notes go here, otherwise put them in another class. class BulkUpdateTests(TestCase): databases = {"default", "other"} def test_no_fields(self): msg = "Field names must be given to bulk_update()." with self.assertRaisesMessage(ValueError, msg): Note.objects.bulk_update([], fields=[]) def test_invalid_batch_size(self): msg = "Batch size must be a positive integer." with self.assertRaisesMessage(ValueError, msg): Note.objects.bulk_update([], fields=["note"], batch_size=-1) with self.assertRaisesMessage(ValueError, msg): Note.objects.bulk_update([], fields=["note"], batch_size=0) def test_nonexistent_field(self): with self.assertRaisesMessage( FieldDoesNotExist, "Note has no field named 'nonexistent'" ): Note.objects.bulk_update([], ["nonexistent"]) pk_fields_error = "bulk_update() cannot be used with primary key fields." def test_update_primary_key(self): with self.assertRaisesMessage(ValueError, self.pk_fields_error): Note.objects.bulk_update([], ["id"]) def test_update_custom_primary_key(self): with self.assertRaisesMessage(ValueError, self.pk_fields_error): CustomPk.objects.bulk_update([], ["name"]) def test_update_inherited_primary_key(self): with self.assertRaisesMessage(ValueError, self.pk_fields_error): SpecialCategory.objects.bulk_update([], ["id"]) def test_empty_objects(self): with self.assertNumQueries(0): rows_updated = Note.objects.bulk_update([], ["note"]) self.assertEqual(rows_updated, 0) def test_large_batch(self): Note.objects.bulk_create( [Note(note=str(i), misc=str(i)) for i in range(0, 2000)] ) notes = list(Note.objects.all()) rows_updated = Note.objects.bulk_update(notes, ["note"]) self.assertEqual(rows_updated, 2000) def test_updated_rows_when_passing_duplicates(self): note = Note.objects.create(note="test-note", misc="test") rows_updated = Note.objects.bulk_update([note, note], ["note"]) self.assertEqual(rows_updated, 1) # Duplicates in different batches. rows_updated = Note.objects.bulk_update([note, note], ["note"], batch_size=1) self.assertEqual(rows_updated, 2) def test_only_concrete_fields_allowed(self): obj = Valid.objects.create(valid="test") detail = Detail.objects.create(data="test") paragraph = Paragraph.objects.create(text="test") Member.objects.create(name="test", details=detail) msg = "bulk_update() can only be used with concrete fields." with self.assertRaisesMessage(ValueError, msg): Detail.objects.bulk_update([detail], fields=["member"]) with self.assertRaisesMessage(ValueError, msg): Paragraph.objects.bulk_update([paragraph], fields=["page"]) with self.assertRaisesMessage(ValueError, msg): Valid.objects.bulk_update([obj], fields=["parent"]) def test_custom_db_columns(self): model = CustomDbColumn.objects.create(custom_column=1) model.custom_column = 2 CustomDbColumn.objects.bulk_update([model], fields=["custom_column"]) model.refresh_from_db() self.assertEqual(model.custom_column, 2) def test_custom_pk(self): custom_pks = [ CustomPk.objects.create(name="pk-%s" % i, extra="") for i in range(10) ] for model in custom_pks: model.extra = "extra-%s" % model.pk CustomPk.objects.bulk_update(custom_pks, ["extra"]) self.assertCountEqual( CustomPk.objects.values_list("extra", flat=True), [cat.extra for cat in custom_pks], ) def test_falsey_pk_value(self): order = Order.objects.create(pk=0, name="test") order.name = "updated" Order.objects.bulk_update([order], ["name"]) order.refresh_from_db() self.assertEqual(order.name, "updated") def test_inherited_fields(self): special_categories = [ SpecialCategory.objects.create(name=str(i), special_name=str(i)) for i in range(10) ] for category in special_categories: category.name = "test-%s" % category.id category.special_name = "special-test-%s" % category.special_name SpecialCategory.objects.bulk_update( special_categories, ["name", "special_name"] ) self.assertCountEqual( SpecialCategory.objects.values_list("name", flat=True), [cat.name for cat in special_categories], ) self.assertCountEqual( SpecialCategory.objects.values_list("special_name", flat=True), [cat.special_name for cat in special_categories], ) def test_field_references(self): numbers = [Number.objects.create(num=0) for _ in range(10)] for number in numbers: number.num = F("num") + 1 Number.objects.bulk_update(numbers, ["num"]) self.assertCountEqual(Number.objects.filter(num=1), numbers) def test_f_expression(self): notes = [ Note.objects.create(note="test_note", misc="test_misc") for _ in range(10) ] for note in notes: note.misc = F("note") Note.objects.bulk_update(notes, ["misc"]) self.assertCountEqual(Note.objects.filter(misc="test_note"), notes) def test_booleanfield(self): individuals = [Individual.objects.create(alive=False) for _ in range(10)] for individual in individuals: individual.alive = True Individual.objects.bulk_update(individuals, ["alive"]) self.assertCountEqual(Individual.objects.filter(alive=True), individuals) def test_ipaddressfield(self): for ip in ("2001::1", "1.2.3.4"): with self.subTest(ip=ip): models = [ CustomDbColumn.objects.create(ip_address="0.0.0.0") for _ in range(10) ] for model in models: model.ip_address = ip CustomDbColumn.objects.bulk_update(models, ["ip_address"]) self.assertCountEqual( CustomDbColumn.objects.filter(ip_address=ip), models ) def test_datetime_field(self): articles = [ Article.objects.create(name=str(i), created=datetime.datetime.today()) for i in range(10) ] point_in_time = datetime.datetime(1991, 10, 31) for article in articles: article.created = point_in_time Article.objects.bulk_update(articles, ["created"]) self.assertCountEqual(Article.objects.filter(created=point_in_time), articles) @skipUnlessDBFeature("supports_json_field") def test_json_field(self): JSONFieldNullable.objects.bulk_create( [JSONFieldNullable(json_field={"a": i}) for i in range(10)] ) objs = JSONFieldNullable.objects.all() for obj in objs: obj.json_field = {"c": obj.json_field["a"] + 1} JSONFieldNullable.objects.bulk_update(objs, ["json_field"]) self.assertCountEqual( JSONFieldNullable.objects.filter(json_field__has_key="c"), objs ) @skipUnlessDBFeature("supports_json_field") def test_json_field_sql_null(self): obj = JSONFieldNullable.objects.create(json_field={}) test_cases = [ ("direct_none_assignment", None), ("value_none_assignment", Value(None)), ( "expression_none_assignment", Coalesce(None, None, output_field=IntegerField()), ), ] for label, value in test_cases: with self.subTest(case=label): obj.json_field = value JSONFieldNullable.objects.bulk_update([obj], fields=["json_field"]) obj.refresh_from_db() sql_null_qs = JSONFieldNullable.objects.filter(json_field__isnull=True) self.assertSequenceEqual(sql_null_qs, [obj]) def test_nullable_fk_after_related_save(self): parent = RelatedObject.objects.create() child = SingleObject() parent.single = child parent.single.save() RelatedObject.objects.bulk_update([parent], fields=["single"]) self.assertEqual(parent.single_id, parent.single.pk) parent.refresh_from_db() self.assertEqual(parent.single, child) def test_unsaved_parent(self): parent = RelatedObject.objects.create() parent.single = SingleObject() msg = ( "bulk_update() prohibited to prevent data loss due to unsaved " "related object 'single'." ) with self.assertRaisesMessage(ValueError, msg): RelatedObject.objects.bulk_update([parent], fields=["single"]) def test_unspecified_unsaved_parent(self): parent = RelatedObject.objects.create() parent.single = SingleObject() parent.f = 42 RelatedObject.objects.bulk_update([parent], fields=["f"]) parent.refresh_from_db() self.assertEqual(parent.f, 42) self.assertIsNone(parent.single) @override_settings(DATABASE_ROUTERS=[WriteToOtherRouter()]) def test_database_routing(self): note = Note.objects.create(note="create") note.note = "bulk_update" with self.assertNumQueries(1, using="other"): Note.objects.bulk_update([note], fields=["note"]) @override_settings(DATABASE_ROUTERS=[WriteToOtherRouter()]) def test_database_routing_batch_atomicity(self): f1 = Food.objects.create(name="Banana") f2 = Food.objects.create(name="Apple") f1.name = "Kiwi" f2.name = "Kiwi" with self.assertRaises(IntegrityError): Food.objects.bulk_update([f1, f2], fields=["name"], batch_size=1) self.assertIs(Food.objects.filter(name="Kiwi").exists(), False)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/queries/test_contains.py
tests/queries/test_contains.py
from django.test import TestCase from .models import DumbCategory, NamedCategory, ProxyCategory class ContainsTests(TestCase): @classmethod def setUpTestData(cls): cls.category = DumbCategory.objects.create() cls.proxy_category = ProxyCategory.objects.create() def test_unsaved_obj(self): msg = "QuerySet.contains() cannot be used on unsaved objects." with self.assertRaisesMessage(ValueError, msg): DumbCategory.objects.contains(DumbCategory()) def test_obj_type(self): msg = "'obj' must be a model instance." with self.assertRaisesMessage(TypeError, msg): DumbCategory.objects.contains(object()) def test_values(self): msg = "Cannot call QuerySet.contains() after .values() or .values_list()." with self.assertRaisesMessage(TypeError, msg): DumbCategory.objects.values_list("pk").contains(self.category) with self.assertRaisesMessage(TypeError, msg): DumbCategory.objects.values("pk").contains(self.category) def test_basic(self): with self.assertNumQueries(1): self.assertIs(DumbCategory.objects.contains(self.category), True) # QuerySet.contains() doesn't evaluate a queryset. with self.assertNumQueries(1): self.assertIs(DumbCategory.objects.contains(self.category), True) def test_evaluated_queryset(self): qs = DumbCategory.objects.all() proxy_qs = ProxyCategory.objects.all() # Evaluate querysets. list(qs) list(proxy_qs) with self.assertNumQueries(0): self.assertIs(qs.contains(self.category), True) self.assertIs(qs.contains(self.proxy_category), True) self.assertIs(proxy_qs.contains(self.category), True) self.assertIs(proxy_qs.contains(self.proxy_category), True) def test_proxy_model(self): with self.assertNumQueries(1): self.assertIs(DumbCategory.objects.contains(self.proxy_category), True) with self.assertNumQueries(1): self.assertIs(ProxyCategory.objects.contains(self.category), True) def test_wrong_model(self): qs = DumbCategory.objects.all() named_category = NamedCategory(name="category") with self.assertNumQueries(0): self.assertIs(qs.contains(named_category), False) # Evaluate the queryset. list(qs) with self.assertNumQueries(0): self.assertIs(qs.contains(named_category), False)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/wsgi/__init__.py
tests/wsgi/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/wsgi/tests.py
tests/wsgi/tests.py
from django.core.exceptions import ImproperlyConfigured from django.core.servers.basehttp import get_internal_wsgi_application from django.core.signals import request_started from django.core.wsgi import get_wsgi_application from django.db import close_old_connections from django.http import FileResponse from django.test import SimpleTestCase, override_settings from django.test.client import RequestFactory @override_settings(ROOT_URLCONF="wsgi.urls") class WSGITest(SimpleTestCase): request_factory = RequestFactory() def setUp(self): request_started.disconnect(close_old_connections) self.addCleanup(request_started.connect, close_old_connections) def test_get_wsgi_application(self): """ get_wsgi_application() returns a functioning WSGI callable. """ application = get_wsgi_application() environ = self.request_factory._base_environ( PATH_INFO="/", CONTENT_TYPE="text/html; charset=utf-8", REQUEST_METHOD="GET" ) response_data = {} def start_response(status, headers): response_data["status"] = status response_data["headers"] = headers response = application(environ, start_response) self.assertEqual(response_data["status"], "200 OK") self.assertEqual( set(response_data["headers"]), {("Content-Length", "12"), ("Content-Type", "text/html; charset=utf-8")}, ) self.assertIn( bytes(response), [ b"Content-Length: 12\r\nContent-Type: text/html; " b"charset=utf-8\r\n\r\nHello World!", b"Content-Type: text/html; " b"charset=utf-8\r\nContent-Length: 12\r\n\r\nHello World!", ], ) def test_wsgi_cookies(self): response_data = {} def start_response(status, headers): response_data["headers"] = headers application = get_wsgi_application() environ = self.request_factory._base_environ( PATH_INFO="/cookie/", REQUEST_METHOD="GET" ) application(environ, start_response) self.assertIn(("Set-Cookie", "key=value; Path=/"), response_data["headers"]) def test_file_wrapper(self): """ FileResponse uses wsgi.file_wrapper. """ class FileWrapper: def __init__(self, filelike, block_size=None): self.block_size = block_size filelike.close() application = get_wsgi_application() environ = self.request_factory._base_environ( PATH_INFO="/file/", REQUEST_METHOD="GET", **{"wsgi.file_wrapper": FileWrapper}, ) response_data = {} def start_response(status, headers): response_data["status"] = status response_data["headers"] = headers response = application(environ, start_response) self.assertEqual(response_data["status"], "200 OK") self.assertIsInstance(response, FileWrapper) self.assertEqual(response.block_size, FileResponse.block_size) class GetInternalWSGIApplicationTest(SimpleTestCase): @override_settings(WSGI_APPLICATION="wsgi.wsgi.application") def test_success(self): """ If ``WSGI_APPLICATION`` is a dotted path, the referenced object is returned. """ app = get_internal_wsgi_application() from .wsgi import application self.assertIs(app, application) @override_settings(WSGI_APPLICATION=None) def test_default(self): """ If ``WSGI_APPLICATION`` is ``None``, the return value of ``get_wsgi_application`` is returned. """ # Mock out get_wsgi_application so we know its return value is used fake_app = object() def mock_get_wsgi_app(): return fake_app from django.core.servers import basehttp _orig_get_wsgi_app = basehttp.get_wsgi_application basehttp.get_wsgi_application = mock_get_wsgi_app try: app = get_internal_wsgi_application() self.assertIs(app, fake_app) finally: basehttp.get_wsgi_application = _orig_get_wsgi_app @override_settings(WSGI_APPLICATION="wsgi.noexist.app") def test_bad_module(self): msg = "WSGI application 'wsgi.noexist.app' could not be loaded; Error importing" with self.assertRaisesMessage(ImproperlyConfigured, msg): get_internal_wsgi_application() @override_settings(WSGI_APPLICATION="wsgi.wsgi.noexist") def test_bad_name(self): msg = ( "WSGI application 'wsgi.wsgi.noexist' could not be loaded; Error importing" ) with self.assertRaisesMessage(ImproperlyConfigured, msg): get_internal_wsgi_application()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/wsgi/wsgi.py
tests/wsgi/wsgi.py
# This is just to test finding, it doesn't have to be a real WSGI callable application = object()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/wsgi/urls.py
tests/wsgi/urls.py
from django.http import FileResponse, HttpResponse from django.urls import path def helloworld(request): return HttpResponse("Hello World!") def cookie(request): response = HttpResponse("Hello World!") response.set_cookie("key", "value") return response urlpatterns = [ path("", helloworld), path("cookie/", cookie), path("file/", lambda x: FileResponse(open(__file__, "rb"))), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/datatypes/models.py
tests/datatypes/models.py
""" This is a basic model to test saving and loading boolean and date-related types, which in the past were problematic for some database backends. """ from django.db import models class Donut(models.Model): name = models.CharField(max_length=100) is_frosted = models.BooleanField(default=False) has_sprinkles = models.BooleanField(null=True) baked_date = models.DateField(null=True) baked_time = models.TimeField(null=True) consumed_at = models.DateTimeField(null=True) review = models.TextField() class Meta: ordering = ("consumed_at",) class RumBaba(models.Model): baked_date = models.DateField(auto_now_add=True) baked_timestamp = models.DateTimeField(auto_now_add=True)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/datatypes/__init__.py
tests/datatypes/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/datatypes/tests.py
tests/datatypes/tests.py
import datetime from django.test import TestCase, skipIfDBFeature from .models import Donut, RumBaba class DataTypesTestCase(TestCase): def test_boolean_type(self): d = Donut(name="Apple Fritter") self.assertFalse(d.is_frosted) self.assertIsNone(d.has_sprinkles) d.has_sprinkles = True self.assertTrue(d.has_sprinkles) d.save() d2 = Donut.objects.get(name="Apple Fritter") self.assertFalse(d2.is_frosted) self.assertTrue(d2.has_sprinkles) def test_date_type(self): d = Donut(name="Apple Fritter") d.baked_date = datetime.date(year=1938, month=6, day=4) d.baked_time = datetime.time(hour=5, minute=30) d.consumed_at = datetime.datetime( year=2007, month=4, day=20, hour=16, minute=19, second=59 ) d.save() d2 = Donut.objects.get(name="Apple Fritter") self.assertEqual(d2.baked_date, datetime.date(1938, 6, 4)) self.assertEqual(d2.baked_time, datetime.time(5, 30)) self.assertEqual(d2.consumed_at, datetime.datetime(2007, 4, 20, 16, 19, 59)) def test_time_field(self): # Test for ticket #12059: TimeField wrongly handling datetime.datetime # object. d = Donut(name="Apple Fritter") d.baked_time = datetime.datetime( year=2007, month=4, day=20, hour=16, minute=19, second=59 ) d.save() d2 = Donut.objects.get(name="Apple Fritter") self.assertEqual(d2.baked_time, datetime.time(16, 19, 59)) def test_year_boundaries(self): """Year boundary tests (ticket #3689)""" Donut.objects.create( name="Date Test 2007", baked_date=datetime.datetime(year=2007, month=12, day=31), consumed_at=datetime.datetime( year=2007, month=12, day=31, hour=23, minute=59, second=59 ), ) Donut.objects.create( name="Date Test 2006", baked_date=datetime.datetime(year=2006, month=1, day=1), consumed_at=datetime.datetime(year=2006, month=1, day=1), ) self.assertEqual( "Date Test 2007", Donut.objects.filter(baked_date__year=2007)[0].name ) self.assertEqual( "Date Test 2006", Donut.objects.filter(baked_date__year=2006)[0].name ) Donut.objects.create( name="Apple Fritter", consumed_at=datetime.datetime( year=2007, month=4, day=20, hour=16, minute=19, second=59 ), ) self.assertEqual( ["Apple Fritter", "Date Test 2007"], list( Donut.objects.filter(consumed_at__year=2007) .order_by("name") .values_list("name", flat=True) ), ) self.assertEqual(0, Donut.objects.filter(consumed_at__year=2005).count()) self.assertEqual(0, Donut.objects.filter(consumed_at__year=2008).count()) def test_textfields_str(self): """TextField values returned from the database should be str.""" d = Donut.objects.create(name="Jelly Donut", review="Outstanding") newd = Donut.objects.get(id=d.id) self.assertIsInstance(newd.review, str) @skipIfDBFeature("supports_timezones") def test_error_on_timezone(self): """Regression test for #8354: the MySQL and Oracle backends should raise an error if given a timezone-aware datetime object.""" dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=datetime.UTC) d = Donut(name="Bear claw", consumed_at=dt) # MySQL backend does not support timezone-aware datetimes. with self.assertRaises(ValueError): d.save() def test_datefield_auto_now_add(self): """Regression test for #10970, auto_now_add for DateField should store a Python datetime.date, not a datetime.datetime""" b = RumBaba.objects.create() # Verify we didn't break DateTimeField behavior self.assertIsInstance(b.baked_timestamp, datetime.datetime) # We need to test this way because datetime.datetime inherits # from datetime.date: self.assertIsInstance(b.baked_date, datetime.date) self.assertNotIsInstance(b.baked_date, datetime.datetime)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/dates/models.py
tests/dates/models.py
from django.db import models from django.utils import timezone class Article(models.Model): title = models.CharField(max_length=100) pub_date = models.DateField() pub_datetime = models.DateTimeField(default=timezone.now) categories = models.ManyToManyField("Category", related_name="articles") class Comment(models.Model): article = models.ForeignKey(Article, models.CASCADE, related_name="comments") text = models.TextField() pub_date = models.DateField() approval_date = models.DateField(null=True) class Category(models.Model): name = models.CharField(max_length=255)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/dates/__init__.py
tests/dates/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/dates/tests.py
tests/dates/tests.py
import datetime from unittest import skipUnless from django.core.exceptions import FieldError from django.db import connection from django.test import TestCase, override_settings from .models import Article, Category, Comment class DatesTests(TestCase): def test_related_model_traverse(self): a1 = Article.objects.create( title="First one", pub_date=datetime.date(2005, 7, 28), ) a2 = Article.objects.create( title="Another one", pub_date=datetime.date(2010, 7, 28), ) a3 = Article.objects.create( title="Third one, in the first day", pub_date=datetime.date(2005, 7, 28), ) a1.comments.create( text="Im the HULK!", pub_date=datetime.date(2005, 7, 28), ) a1.comments.create( text="HULK SMASH!", pub_date=datetime.date(2005, 7, 29), ) a2.comments.create( text="LMAO", pub_date=datetime.date(2010, 7, 28), ) a3.comments.create( text="+1", pub_date=datetime.date(2005, 8, 29), ) c = Category.objects.create(name="serious-news") c.articles.add(a1, a3) self.assertSequenceEqual( Comment.objects.dates("article__pub_date", "year"), [ datetime.date(2005, 1, 1), datetime.date(2010, 1, 1), ], ) self.assertSequenceEqual( Comment.objects.dates("article__pub_date", "month"), [ datetime.date(2005, 7, 1), datetime.date(2010, 7, 1), ], ) self.assertSequenceEqual( Comment.objects.dates("article__pub_date", "week"), [ datetime.date(2005, 7, 25), datetime.date(2010, 7, 26), ], ) self.assertSequenceEqual( Comment.objects.dates("article__pub_date", "day"), [ datetime.date(2005, 7, 28), datetime.date(2010, 7, 28), ], ) self.assertSequenceEqual( Article.objects.dates("comments__pub_date", "day"), [ datetime.date(2005, 7, 28), datetime.date(2005, 7, 29), datetime.date(2005, 8, 29), datetime.date(2010, 7, 28), ], ) self.assertSequenceEqual( Article.objects.dates("comments__approval_date", "day"), [] ) self.assertSequenceEqual( Category.objects.dates("articles__pub_date", "day"), [ datetime.date(2005, 7, 28), ], ) def test_dates_fails_when_no_arguments_are_provided(self): with self.assertRaises(TypeError): Article.objects.dates() def test_dates_fails_when_given_invalid_field_argument(self): with self.assertRaisesMessage( FieldError, "Cannot resolve keyword 'invalid_field' into field. Choices are: " "categories, comments, id, pub_date, pub_datetime, title", ): Article.objects.dates("invalid_field", "year") def test_dates_fails_when_given_invalid_kind_argument(self): msg = "'kind' must be one of 'year', 'month', 'week', or 'day'." with self.assertRaisesMessage(ValueError, msg): Article.objects.dates("pub_date", "bad_kind") def test_dates_fails_when_given_invalid_order_argument(self): msg = "'order' must be either 'ASC' or 'DESC'." with self.assertRaisesMessage(ValueError, msg): Article.objects.dates("pub_date", "year", order="bad order") @override_settings(USE_TZ=False) def test_dates_trunc_datetime_fields(self): Article.objects.bulk_create( Article(pub_date=pub_datetime.date(), pub_datetime=pub_datetime) for pub_datetime in [ datetime.datetime(2015, 10, 21, 18, 1), datetime.datetime(2015, 10, 21, 18, 2), datetime.datetime(2015, 10, 22, 18, 1), datetime.datetime(2015, 10, 22, 18, 2), ] ) self.assertSequenceEqual( Article.objects.dates("pub_datetime", "day", order="ASC"), [ datetime.date(2015, 10, 21), datetime.date(2015, 10, 22), ], ) @skipUnless(connection.vendor == "mysql", "Test checks MySQL query syntax") def test_dates_avoid_datetime_cast(self): Article.objects.create(pub_date=datetime.date(2015, 10, 21)) for kind in ["day", "month", "year"]: qs = Article.objects.dates("pub_date", kind) if kind == "day": self.assertIn("DATE(", str(qs.query)) else: self.assertIn(" AS DATE)", str(qs.query))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/dispatch/__init__.py
tests/dispatch/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/dispatch/tests.py
tests/dispatch/tests.py
import weakref from types import TracebackType from unittest import mock from django.dispatch import Signal, receiver from django.dispatch.dispatcher import _make_id from django.test import SimpleTestCase from django.test.utils import garbage_collect, override_settings def receiver_1_arg(val, **kwargs): return val class Callable: def __call__(self, val, **kwargs): return val def a(self, val, **kwargs): return val a_signal = Signal() b_signal = Signal() c_signal = Signal() d_signal = Signal(use_caching=True) class DispatcherTests(SimpleTestCase): def assertTestIsClean(self, signal): """Assert that everything has been cleaned up automatically""" # Note that dead weakref cleanup happens as side effect of using # the signal's receivers through the signals API. So, first do a # call to an API method to force cleanup. self.assertFalse(signal.has_listeners()) self.assertEqual(signal.receivers, []) @override_settings(DEBUG=True) def test_cannot_connect_no_kwargs(self): def receiver_no_kwargs(sender): pass msg = "Signal receivers must accept keyword arguments (**kwargs)." with self.assertRaisesMessage(ValueError, msg): a_signal.connect(receiver_no_kwargs) self.assertTestIsClean(a_signal) @override_settings(DEBUG=True) def test_cannot_connect_non_callable(self): msg = "Signal receivers must be callable." with self.assertRaisesMessage(TypeError, msg): a_signal.connect(object()) self.assertTestIsClean(a_signal) def test_send(self): a_signal.connect(receiver_1_arg, sender=self) result = a_signal.send(sender=self, val="test") self.assertEqual(result, [(receiver_1_arg, "test")]) a_signal.disconnect(receiver_1_arg, sender=self) self.assertTestIsClean(a_signal) def test_send_no_receivers(self): result = a_signal.send(sender=self, val="test") self.assertEqual(result, []) def test_send_connected_no_sender(self): a_signal.connect(receiver_1_arg) result = a_signal.send(sender=self, val="test") self.assertEqual(result, [(receiver_1_arg, "test")]) a_signal.disconnect(receiver_1_arg) self.assertTestIsClean(a_signal) def test_send_different_no_sender(self): a_signal.connect(receiver_1_arg, sender=object) result = a_signal.send(sender=self, val="test") self.assertEqual(result, []) a_signal.disconnect(receiver_1_arg, sender=object) self.assertTestIsClean(a_signal) def test_unweakrefable_sender(self): sender = object() a_signal.connect(receiver_1_arg, sender=sender) result = a_signal.send(sender=sender, val="test") self.assertEqual(result, [(receiver_1_arg, "test")]) a_signal.disconnect(receiver_1_arg, sender=sender) self.assertTestIsClean(a_signal) def test_garbage_collected_receiver(self): a = Callable() a_signal.connect(a.a, sender=self) del a garbage_collect() result = a_signal.send(sender=self, val="test") self.assertEqual(result, []) self.assertTestIsClean(a_signal) def test_garbage_collected_sender(self): signal = Signal() class Sender: pass def make_id(target): """ Simulate id() reuse for distinct senders with non-overlapping lifetimes that would require memory contention to reproduce. """ if isinstance(target, Sender): return 0 return _make_id(target) def first_receiver(attempt, **kwargs): return attempt def second_receiver(attempt, **kwargs): return attempt with mock.patch("django.dispatch.dispatcher._make_id", make_id): sender = Sender() signal.connect(first_receiver, sender) result = signal.send(sender, attempt="first") self.assertEqual(result, [(first_receiver, "first")]) del sender garbage_collect() sender = Sender() signal.connect(second_receiver, sender) result = signal.send(sender, attempt="second") self.assertEqual(result, [(second_receiver, "second")]) def test_cached_garbaged_collected(self): """ Make sure signal caching sender receivers don't prevent garbage collection of senders. """ class sender: pass wref = weakref.ref(sender) d_signal.connect(receiver_1_arg) d_signal.send(sender, val="garbage") del sender garbage_collect() try: self.assertIsNone(wref()) finally: # Disconnect after reference check since it flushes the tested # cache. d_signal.disconnect(receiver_1_arg) def test_multiple_registration(self): a = Callable() a_signal.connect(a) a_signal.connect(a) a_signal.connect(a) a_signal.connect(a) a_signal.connect(a) a_signal.connect(a) result = a_signal.send(sender=self, val="test") self.assertEqual(len(result), 1) self.assertEqual(len(a_signal.receivers), 1) del a del result garbage_collect() self.assertTestIsClean(a_signal) def test_uid_registration(self): def uid_based_receiver_1(**kwargs): pass def uid_based_receiver_2(**kwargs): pass a_signal.connect(uid_based_receiver_1, dispatch_uid="uid") a_signal.connect(uid_based_receiver_2, dispatch_uid="uid") self.assertEqual(len(a_signal.receivers), 1) a_signal.disconnect(dispatch_uid="uid") self.assertTestIsClean(a_signal) def test_send_robust_success(self): a_signal.connect(receiver_1_arg) result = a_signal.send_robust(sender=self, val="test") self.assertEqual(result, [(receiver_1_arg, "test")]) a_signal.disconnect(receiver_1_arg) self.assertTestIsClean(a_signal) def test_send_robust_no_receivers(self): result = a_signal.send_robust(sender=self, val="test") self.assertEqual(result, []) def test_send_robust_ignored_sender(self): a_signal.connect(receiver_1_arg) result = a_signal.send_robust(sender=self, val="test") self.assertEqual(result, [(receiver_1_arg, "test")]) a_signal.disconnect(receiver_1_arg) self.assertTestIsClean(a_signal) def test_send_robust_fail(self): def fails(val, **kwargs): raise ValueError("this") a_signal.connect(fails) try: with self.assertLogs("django.dispatch", "ERROR") as cm: result = a_signal.send_robust(sender=self, val="test") err = result[0][1] self.assertIsInstance(err, ValueError) self.assertEqual(err.args, ("this",)) self.assertIs(hasattr(err, "__traceback__"), True) self.assertIsInstance(err.__traceback__, TracebackType) log_record = cm.records[0] self.assertEqual( log_record.getMessage(), "Error calling " "DispatcherTests.test_send_robust_fail.<locals>.fails in " "Signal.send_robust() (this)", ) self.assertIsNotNone(log_record.exc_info) _, exc_value, _ = log_record.exc_info self.assertIsInstance(exc_value, ValueError) self.assertEqual(str(exc_value), "this") finally: a_signal.disconnect(fails) self.assertTestIsClean(a_signal) def test_disconnection(self): receiver_1 = Callable() receiver_2 = Callable() receiver_3 = Callable() a_signal.connect(receiver_1) a_signal.connect(receiver_2) a_signal.connect(receiver_3) a_signal.disconnect(receiver_1) del receiver_2 garbage_collect() a_signal.disconnect(receiver_3) self.assertTestIsClean(a_signal) def test_values_returned_by_disconnection(self): receiver_1 = Callable() receiver_2 = Callable() a_signal.connect(receiver_1) receiver_1_disconnected = a_signal.disconnect(receiver_1) receiver_2_disconnected = a_signal.disconnect(receiver_2) self.assertTrue(receiver_1_disconnected) self.assertFalse(receiver_2_disconnected) self.assertTestIsClean(a_signal) def test_has_listeners(self): self.assertFalse(a_signal.has_listeners()) self.assertFalse(a_signal.has_listeners(sender=object())) receiver_1 = Callable() a_signal.connect(receiver_1) self.assertTrue(a_signal.has_listeners()) self.assertTrue(a_signal.has_listeners(sender=object())) a_signal.disconnect(receiver_1) self.assertFalse(a_signal.has_listeners()) self.assertFalse(a_signal.has_listeners(sender=object())) class ReceiverTestCase(SimpleTestCase): def test_receiver_single_signal(self): @receiver(a_signal) def f(val, **kwargs): self.state = val self.state = False a_signal.send(sender=self, val=True) self.assertTrue(self.state) def test_receiver_signal_list(self): @receiver([a_signal, b_signal, c_signal]) def f(val, **kwargs): self.state.append(val) self.state = [] a_signal.send(sender=self, val="a") c_signal.send(sender=self, val="c") b_signal.send(sender=self, val="b") self.assertIn("a", self.state) self.assertIn("b", self.state) self.assertIn("c", self.state)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/timezones/admin.py
tests/timezones/admin.py
from django.contrib import admin from .models import Event, Timestamp class EventAdmin(admin.ModelAdmin): list_display = ("dt",) class TimestampAdmin(admin.ModelAdmin): readonly_fields = ("created", "updated") site = admin.AdminSite(name="admin_tz") site.register(Event, EventAdmin) site.register(Timestamp, TimestampAdmin)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/timezones/models.py
tests/timezones/models.py
from django.db import models class Event(models.Model): dt = models.DateTimeField() class MaybeEvent(models.Model): dt = models.DateTimeField(blank=True, null=True) class Session(models.Model): name = models.CharField(max_length=20) class SessionEvent(models.Model): dt = models.DateTimeField() session = models.ForeignKey(Session, models.CASCADE, related_name="events") class Timestamp(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class AllDayEvent(models.Model): day = models.DateField() class DailyEvent(models.Model): time = models.TimeField()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/timezones/__init__.py
tests/timezones/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/timezones/tests.py
tests/timezones/tests.py
import datetime import re import sys import zoneinfo from contextlib import contextmanager from unittest import SkipTest, skipIf from xml.dom.minidom import parseString from django.contrib.auth.models import User from django.core import serializers from django.db import connection from django.db.models import F, Max, Min from django.db.models.functions import Now from django.http import HttpRequest from django.template import ( Context, RequestContext, Template, TemplateSyntaxError, context_processors, ) from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.utils import requires_tz_support from django.urls import reverse from django.utils import timezone, translation from django.utils.timezone import timedelta from .forms import ( EventForm, EventLocalizedForm, EventLocalizedModelForm, EventModelForm, EventSplitForm, ) from .models import ( AllDayEvent, DailyEvent, Event, MaybeEvent, Session, SessionEvent, Timestamp, ) try: import yaml HAS_YAML = True except ImportError: HAS_YAML = False # These tests use the EAT (Eastern Africa Time) and ICT (Indochina Time) # who don't have daylight saving time, so we can represent them easily # with fixed offset timezones and use them directly as tzinfo in the # constructors. # settings.TIME_ZONE is forced to EAT. Most tests use a variant of # datetime.datetime(2011, 9, 1, 13, 20, 30), which translates to # 10:20:30 in UTC and 17:20:30 in ICT. UTC = datetime.UTC EAT = timezone.get_fixed_timezone(180) # Africa/Nairobi ICT = timezone.get_fixed_timezone(420) # Asia/Bangkok @contextmanager def override_database_connection_timezone(timezone): try: orig_timezone = connection.settings_dict["TIME_ZONE"] connection.settings_dict["TIME_ZONE"] = timezone # Clear cached properties, after first accessing them to ensure they # exist. connection.timezone del connection.timezone connection.timezone_name del connection.timezone_name yield finally: connection.settings_dict["TIME_ZONE"] = orig_timezone # Clear cached properties, after first accessing them to ensure they # exist. connection.timezone del connection.timezone connection.timezone_name del connection.timezone_name @override_settings(TIME_ZONE="Africa/Nairobi", USE_TZ=False) class LegacyDatabaseTests(TestCase): def test_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_naive_datetime_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) @skipUnlessDBFeature("supports_timezones") def test_aware_datetime_in_local_timezone(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertIsNone(event.dt.tzinfo) # interpret the naive datetime in local time to get the correct value self.assertEqual(event.dt.replace(tzinfo=EAT), dt) @skipUnlessDBFeature("supports_timezones") def test_aware_datetime_in_local_timezone_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060, tzinfo=EAT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertIsNone(event.dt.tzinfo) # interpret the naive datetime in local time to get the correct value self.assertEqual(event.dt.replace(tzinfo=EAT), dt) @skipUnlessDBFeature("supports_timezones") def test_aware_datetime_in_utc(self): dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) Event.objects.create(dt=dt) event = Event.objects.get() self.assertIsNone(event.dt.tzinfo) # interpret the naive datetime in local time to get the correct value self.assertEqual(event.dt.replace(tzinfo=EAT), dt) @skipUnlessDBFeature("supports_timezones") def test_aware_datetime_in_other_timezone(self): dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertIsNone(event.dt.tzinfo) # interpret the naive datetime in local time to get the correct value self.assertEqual(event.dt.replace(tzinfo=EAT), dt) @skipIfDBFeature("supports_timezones") def test_aware_datetime_unsupported(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) msg = "backend does not support timezone-aware datetimes when USE_TZ is False." with self.assertRaisesMessage(ValueError, msg): Event.objects.create(dt=dt) def test_auto_now_and_auto_now_add(self): now = datetime.datetime.now() past = now - datetime.timedelta(seconds=2) future = now + datetime.timedelta(seconds=2) Timestamp.objects.create() ts = Timestamp.objects.get() self.assertLess(past, ts.created) self.assertLess(past, ts.updated) self.assertGreater(future, ts.updated) self.assertGreater(future, ts.updated) def test_query_filter(self): dt1 = datetime.datetime(2011, 9, 1, 12, 20, 30) dt2 = datetime.datetime(2011, 9, 1, 14, 20, 30) Event.objects.create(dt=dt1) Event.objects.create(dt=dt2) self.assertEqual(Event.objects.filter(dt__gte=dt1).count(), 2) self.assertEqual(Event.objects.filter(dt__gt=dt1).count(), 1) self.assertEqual(Event.objects.filter(dt__gte=dt2).count(), 1) self.assertEqual(Event.objects.filter(dt__gt=dt2).count(), 0) def test_query_datetime_lookups(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0)) self.assertEqual(Event.objects.filter(dt__year=2011).count(), 2) self.assertEqual(Event.objects.filter(dt__month=1).count(), 2) self.assertEqual(Event.objects.filter(dt__day=1).count(), 2) self.assertEqual(Event.objects.filter(dt__week_day=7).count(), 2) self.assertEqual(Event.objects.filter(dt__iso_week_day=6).count(), 2) self.assertEqual(Event.objects.filter(dt__hour=1).count(), 1) self.assertEqual(Event.objects.filter(dt__minute=30).count(), 2) self.assertEqual(Event.objects.filter(dt__second=0).count(), 2) def test_query_aggregation(self): # Only min and max make sense for datetimes. Event.objects.create(dt=datetime.datetime(2011, 9, 1, 23, 20, 20)) Event.objects.create(dt=datetime.datetime(2011, 9, 1, 13, 20, 30)) Event.objects.create(dt=datetime.datetime(2011, 9, 1, 3, 20, 40)) result = Event.objects.aggregate(Min("dt"), Max("dt")) self.assertEqual( result, { "dt__min": datetime.datetime(2011, 9, 1, 3, 20, 40), "dt__max": datetime.datetime(2011, 9, 1, 23, 20, 20), }, ) def test_query_annotation(self): # Only min and max make sense for datetimes. morning = Session.objects.create(name="morning") afternoon = Session.objects.create(name="afternoon") SessionEvent.objects.create( dt=datetime.datetime(2011, 9, 1, 23, 20, 20), session=afternoon ) SessionEvent.objects.create( dt=datetime.datetime(2011, 9, 1, 13, 20, 30), session=afternoon ) SessionEvent.objects.create( dt=datetime.datetime(2011, 9, 1, 3, 20, 40), session=morning ) morning_min_dt = datetime.datetime(2011, 9, 1, 3, 20, 40) afternoon_min_dt = datetime.datetime(2011, 9, 1, 13, 20, 30) self.assertQuerySetEqual( Session.objects.annotate(dt=Min("events__dt")).order_by("dt"), [morning_min_dt, afternoon_min_dt], transform=lambda d: d.dt, ) self.assertQuerySetEqual( Session.objects.annotate(dt=Min("events__dt")).filter( dt__lt=afternoon_min_dt ), [morning_min_dt], transform=lambda d: d.dt, ) self.assertQuerySetEqual( Session.objects.annotate(dt=Min("events__dt")).filter( dt__gte=afternoon_min_dt ), [afternoon_min_dt], transform=lambda d: d.dt, ) def test_query_datetimes(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0)) self.assertSequenceEqual( Event.objects.datetimes("dt", "year"), [datetime.datetime(2011, 1, 1, 0, 0, 0)], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "month"), [datetime.datetime(2011, 1, 1, 0, 0, 0)], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "day"), [datetime.datetime(2011, 1, 1, 0, 0, 0)], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "hour"), [ datetime.datetime(2011, 1, 1, 1, 0, 0), datetime.datetime(2011, 1, 1, 4, 0, 0), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "minute"), [ datetime.datetime(2011, 1, 1, 1, 30, 0), datetime.datetime(2011, 1, 1, 4, 30, 0), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "second"), [ datetime.datetime(2011, 1, 1, 1, 30, 0), datetime.datetime(2011, 1, 1, 4, 30, 0), ], ) def test_raw_sql(self): # Regression test for #17755 dt = datetime.datetime(2011, 9, 1, 13, 20, 30) event = Event.objects.create(dt=dt) self.assertEqual( list( Event.objects.raw("SELECT * FROM timezones_event WHERE dt = %s", [dt]) ), [event], ) def test_cursor_execute_accepts_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30) with connection.cursor() as cursor: cursor.execute("INSERT INTO timezones_event (dt) VALUES (%s)", [dt]) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_cursor_execute_returns_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30) Event.objects.create(dt=dt) with connection.cursor() as cursor: cursor.execute("SELECT dt FROM timezones_event WHERE dt = %s", [dt]) self.assertEqual(cursor.fetchall()[0][0], dt) def test_filter_date_field_with_aware_datetime(self): # Regression test for #17742 day = datetime.date(2011, 9, 1) AllDayEvent.objects.create(day=day) # This is 2011-09-02T01:30:00+03:00 in EAT dt = datetime.datetime(2011, 9, 1, 22, 30, 0, tzinfo=UTC) self.assertTrue(AllDayEvent.objects.filter(day__gte=dt).exists()) @override_settings(TIME_ZONE="Africa/Nairobi", USE_TZ=True) class NewDatabaseTests(TestCase): naive_warning = "DateTimeField Event.dt received a naive datetime" @skipIfDBFeature("supports_timezones") def test_aware_time_unsupported(self): t = datetime.time(13, 20, 30, tzinfo=EAT) msg = "backend does not support timezone-aware times." with self.assertRaisesMessage(ValueError, msg): DailyEvent.objects.create(time=t) @requires_tz_support def test_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30) with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): Event.objects.create(dt=dt) event = Event.objects.get() # naive datetimes are interpreted in local time self.assertEqual(event.dt, dt.replace(tzinfo=EAT)) @requires_tz_support def test_datetime_from_date(self): dt = datetime.date(2011, 9, 1) with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, datetime.datetime(2011, 9, 1, tzinfo=EAT)) @requires_tz_support def test_filter_unbound_datetime_with_naive_date(self): dt = datetime.date(2011, 9, 1) msg = "DateTimeField (unbound) received a naive datetime" with self.assertWarnsMessage(RuntimeWarning, msg): Event.objects.annotate(unbound_datetime=Now()).filter(unbound_datetime=dt) @requires_tz_support def test_naive_datetime_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060) with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): Event.objects.create(dt=dt) event = Event.objects.get() # naive datetimes are interpreted in local time self.assertEqual(event.dt, dt.replace(tzinfo=EAT)) def test_aware_datetime_in_local_timezone(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_aware_datetime_in_local_timezone_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060, tzinfo=EAT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_aware_datetime_in_utc(self): dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_aware_datetime_in_other_timezone(self): dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_auto_now_and_auto_now_add(self): now = timezone.now() past = now - datetime.timedelta(seconds=2) future = now + datetime.timedelta(seconds=2) Timestamp.objects.create() ts = Timestamp.objects.get() self.assertLess(past, ts.created) self.assertLess(past, ts.updated) self.assertGreater(future, ts.updated) self.assertGreater(future, ts.updated) def test_query_filter(self): dt1 = datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=EAT) dt2 = datetime.datetime(2011, 9, 1, 14, 20, 30, tzinfo=EAT) Event.objects.create(dt=dt1) Event.objects.create(dt=dt2) self.assertEqual(Event.objects.filter(dt__gte=dt1).count(), 2) self.assertEqual(Event.objects.filter(dt__gt=dt1).count(), 1) self.assertEqual(Event.objects.filter(dt__gte=dt2).count(), 1) self.assertEqual(Event.objects.filter(dt__gt=dt2).count(), 0) def test_query_filter_with_timezones(self): tz = zoneinfo.ZoneInfo("Europe/Paris") dt = datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=tz) Event.objects.create(dt=dt) next = dt + datetime.timedelta(seconds=3) prev = dt - datetime.timedelta(seconds=3) self.assertEqual(Event.objects.filter(dt__exact=dt).count(), 1) self.assertEqual(Event.objects.filter(dt__exact=next).count(), 0) self.assertEqual(Event.objects.filter(dt__in=(prev, next)).count(), 0) self.assertEqual(Event.objects.filter(dt__in=(prev, dt, next)).count(), 1) self.assertEqual(Event.objects.filter(dt__range=(prev, next)).count(), 1) def test_query_convert_timezones(self): # Connection timezone is equal to the current timezone, datetime # shouldn't be converted. with override_database_connection_timezone("Africa/Nairobi"): event_datetime = datetime.datetime(2016, 1, 2, 23, 10, 11, 123, tzinfo=EAT) event = Event.objects.create(dt=event_datetime) self.assertEqual( Event.objects.filter(dt__date=event_datetime.date()).first(), event ) # Connection timezone is not equal to the current timezone, datetime # should be converted (-4h). with override_database_connection_timezone("Asia/Bangkok"): event_datetime = datetime.datetime(2016, 1, 2, 3, 10, 11, tzinfo=ICT) event = Event.objects.create(dt=event_datetime) self.assertEqual( Event.objects.filter(dt__date=datetime.date(2016, 1, 1)).first(), event ) @requires_tz_support def test_query_filter_with_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=EAT) Event.objects.create(dt=dt) dt = dt.replace(tzinfo=None) # naive datetimes are interpreted in local time with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): self.assertEqual(Event.objects.filter(dt__exact=dt).count(), 1) with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): self.assertEqual(Event.objects.filter(dt__lte=dt).count(), 1) with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): self.assertEqual(Event.objects.filter(dt__gt=dt).count(), 0) @skipUnlessDBFeature("has_zoneinfo_database") def test_query_datetime_lookups(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT)) self.assertEqual(Event.objects.filter(dt__year=2011).count(), 2) self.assertEqual(Event.objects.filter(dt__month=1).count(), 2) self.assertEqual(Event.objects.filter(dt__day=1).count(), 2) self.assertEqual(Event.objects.filter(dt__week_day=7).count(), 2) self.assertEqual(Event.objects.filter(dt__iso_week_day=6).count(), 2) self.assertEqual(Event.objects.filter(dt__hour=1).count(), 1) self.assertEqual(Event.objects.filter(dt__minute=30).count(), 2) self.assertEqual(Event.objects.filter(dt__second=0).count(), 2) @skipUnlessDBFeature("has_zoneinfo_database") def test_query_datetime_lookups_in_other_timezone(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT)) with timezone.override(UTC): # These two dates fall in the same day in EAT, but in different # days, years and months in UTC. self.assertEqual(Event.objects.filter(dt__year=2011).count(), 1) self.assertEqual(Event.objects.filter(dt__month=1).count(), 1) self.assertEqual(Event.objects.filter(dt__day=1).count(), 1) self.assertEqual(Event.objects.filter(dt__week_day=7).count(), 1) self.assertEqual(Event.objects.filter(dt__iso_week_day=6).count(), 1) self.assertEqual(Event.objects.filter(dt__hour=22).count(), 1) self.assertEqual(Event.objects.filter(dt__minute=30).count(), 2) self.assertEqual(Event.objects.filter(dt__second=0).count(), 2) def test_query_aggregation(self): # Only min and max make sense for datetimes. Event.objects.create(dt=datetime.datetime(2011, 9, 1, 23, 20, 20, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT)) result = Event.objects.aggregate(Min("dt"), Max("dt")) self.assertEqual( result, { "dt__min": datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT), "dt__max": datetime.datetime(2011, 9, 1, 23, 20, 20, tzinfo=EAT), }, ) def test_query_annotation(self): # Only min and max make sense for datetimes. morning = Session.objects.create(name="morning") afternoon = Session.objects.create(name="afternoon") SessionEvent.objects.create( dt=datetime.datetime(2011, 9, 1, 23, 20, 20, tzinfo=EAT), session=afternoon ) SessionEvent.objects.create( dt=datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), session=afternoon ) SessionEvent.objects.create( dt=datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT), session=morning ) morning_min_dt = datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT) afternoon_min_dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) self.assertQuerySetEqual( Session.objects.annotate(dt=Min("events__dt")).order_by("dt"), [morning_min_dt, afternoon_min_dt], transform=lambda d: d.dt, ) self.assertQuerySetEqual( Session.objects.annotate(dt=Min("events__dt")).filter( dt__lt=afternoon_min_dt ), [morning_min_dt], transform=lambda d: d.dt, ) self.assertQuerySetEqual( Session.objects.annotate(dt=Min("events__dt")).filter( dt__gte=afternoon_min_dt ), [afternoon_min_dt], transform=lambda d: d.dt, ) @skipUnlessDBFeature("has_zoneinfo_database") def test_query_datetimes(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT)) self.assertSequenceEqual( Event.objects.datetimes("dt", "year"), [datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=EAT)], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "month"), [datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=EAT)], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "day"), [datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=EAT)], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "hour"), [ datetime.datetime(2011, 1, 1, 1, 0, 0, tzinfo=EAT), datetime.datetime(2011, 1, 1, 4, 0, 0, tzinfo=EAT), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "minute"), [ datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT), datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "second"), [ datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT), datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT), ], ) @skipUnlessDBFeature("has_zoneinfo_database") def test_query_datetimes_in_other_timezone(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT)) with timezone.override(UTC): self.assertSequenceEqual( Event.objects.datetimes("dt", "year"), [ datetime.datetime(2010, 1, 1, 0, 0, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=UTC), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "month"), [ datetime.datetime(2010, 12, 1, 0, 0, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=UTC), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "day"), [ datetime.datetime(2010, 12, 31, 0, 0, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=UTC), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "hour"), [ datetime.datetime(2010, 12, 31, 22, 0, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 1, 0, 0, tzinfo=UTC), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "minute"), [ datetime.datetime(2010, 12, 31, 22, 30, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=UTC), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "second"), [ datetime.datetime(2010, 12, 31, 22, 30, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=UTC), ], ) def test_raw_sql(self): # Regression test for #17755 dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) event = Event.objects.create(dt=dt) self.assertSequenceEqual( list( Event.objects.raw("SELECT * FROM timezones_event WHERE dt = %s", [dt]) ), [event], ) @skipUnlessDBFeature("supports_timezones") def test_cursor_execute_accepts_aware_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) with connection.cursor() as cursor: cursor.execute("INSERT INTO timezones_event (dt) VALUES (%s)", [dt]) event = Event.objects.get() self.assertEqual(event.dt, dt) @skipIfDBFeature("supports_timezones") def test_cursor_execute_accepts_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) utc_naive_dt = timezone.make_naive(dt, UTC) with connection.cursor() as cursor: cursor.execute( "INSERT INTO timezones_event (dt) VALUES (%s)", [utc_naive_dt] ) event = Event.objects.get() self.assertEqual(event.dt, dt) @skipUnlessDBFeature("supports_timezones") def test_cursor_execute_returns_aware_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) Event.objects.create(dt=dt) with connection.cursor() as cursor: cursor.execute("SELECT dt FROM timezones_event WHERE dt = %s", [dt]) self.assertEqual(cursor.fetchall()[0][0], dt) @skipIfDBFeature("supports_timezones") def test_cursor_execute_returns_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) utc_naive_dt = timezone.make_naive(dt, UTC) Event.objects.create(dt=dt) with connection.cursor() as cursor: cursor.execute( "SELECT dt FROM timezones_event WHERE dt = %s", [utc_naive_dt] ) self.assertEqual(cursor.fetchall()[0][0], utc_naive_dt) @skipUnlessDBFeature("supports_timezones") def test_cursor_explicit_time_zone(self): with override_database_connection_timezone("Europe/Paris"): with connection.cursor() as cursor: cursor.execute("SELECT CURRENT_TIMESTAMP") now = cursor.fetchone()[0] self.assertEqual(str(now.tzinfo), "Europe/Paris") @requires_tz_support def test_filter_date_field_with_aware_datetime(self): # Regression test for #17742 day = datetime.date(2011, 9, 1) AllDayEvent.objects.create(day=day) # This is 2011-09-02T01:30:00+03:00 in EAT dt = datetime.datetime(2011, 9, 1, 22, 30, 0, tzinfo=UTC) self.assertFalse(AllDayEvent.objects.filter(day__gte=dt).exists()) def test_null_datetime(self): # Regression test for #17294 e = MaybeEvent.objects.create() self.assertIsNone(e.dt) def test_update_with_timedelta(self): initial_dt = timezone.now().replace(microsecond=0) event = Event.objects.create(dt=initial_dt) Event.objects.update(dt=F("dt") + timedelta(hours=2)) event.refresh_from_db() self.assertEqual(event.dt, initial_dt + timedelta(hours=2)) @override_settings(TIME_ZONE="Africa/Nairobi", USE_TZ=True) class ForcedTimeZoneDatabaseTests(TransactionTestCase): """ Test the TIME_ZONE database configuration parameter. Since this involves reading and writing to the same database through two connections, this is a TransactionTestCase. """ available_apps = ["timezones"] @classmethod def setUpClass(cls): # @skipIfDBFeature and @skipUnlessDBFeature cannot be chained. The # outermost takes precedence. Handle skipping manually instead. if connection.features.supports_timezones: raise SkipTest("Database has feature(s) supports_timezones") if not connection.features.test_db_allows_multiple_connections: raise SkipTest( "Database doesn't support feature(s): " "test_db_allows_multiple_connections" ) super().setUpClass() def test_read_datetime(self): fake_dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=UTC) Event.objects.create(dt=fake_dt) with override_database_connection_timezone("Asia/Bangkok"): event = Event.objects.get() dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) self.assertEqual(event.dt, dt) def test_write_datetime(self): dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) with override_database_connection_timezone("Asia/Bangkok"): Event.objects.create(dt=dt) event = Event.objects.get() fake_dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=UTC) self.assertEqual(event.dt, fake_dt) @override_settings(TIME_ZONE="Africa/Nairobi") class SerializationTests(SimpleTestCase): # Backend-specific notes: # - JSON supports only milliseconds, microseconds will be truncated. # - PyYAML dumps the UTC offset correctly for timezone-aware datetimes. # When PyYAML < 5.3 loads this representation, it subtracts the offset # and returns a naive datetime object in UTC. PyYAML 5.3+ loads timezones # correctly. # Tests are adapted to take these quirks into account. def assert_python_contains_datetime(self, objects, dt): self.assertEqual(objects[0]["fields"]["dt"], dt) def assert_json_contains_datetime(self, json, dt): self.assertIn('"fields": {"dt": "%s"}' % dt, json) def assert_xml_contains_datetime(self, xml, dt): field = parseString(xml).getElementsByTagName("field")[0] self.assertXMLEqual(field.childNodes[0].wholeText, dt) def assert_yaml_contains_datetime(self, yaml, dt): # Depending on the yaml dumper, '!timestamp' might be absent self.assertRegex(yaml, r"\n fields: {dt: !(!timestamp)? '%s'}" % re.escape(dt)) def test_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30) data = serializers.serialize("python", [Event(dt=dt)]) self.assert_python_contains_datetime(data, dt) obj = next(serializers.deserialize("python", data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize("json", [Event(dt=dt)]) self.assert_json_contains_datetime(data, "2011-09-01T13:20:30") obj = next(serializers.deserialize("json", data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize("xml", [Event(dt=dt)]) self.assert_xml_contains_datetime(data, "2011-09-01T13:20:30") obj = next(serializers.deserialize("xml", data)).object self.assertEqual(obj.dt, dt) if not isinstance( serializers.get_serializer("yaml"), serializers.BadSerializer ): data = serializers.serialize( "yaml", [Event(dt=dt)], default_flow_style=None ) self.assert_yaml_contains_datetime(data, "2011-09-01 13:20:30") obj = next(serializers.deserialize("yaml", data)).object self.assertEqual(obj.dt, dt) def test_naive_datetime_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060) data = serializers.serialize("python", [Event(dt=dt)]) self.assert_python_contains_datetime(data, dt)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/timezones/forms.py
tests/timezones/forms.py
from django import forms from .models import Event class EventForm(forms.Form): dt = forms.DateTimeField() class EventSplitForm(forms.Form): dt = forms.SplitDateTimeField() class EventLocalizedForm(forms.Form): dt = forms.DateTimeField(localize=True) class EventModelForm(forms.ModelForm): class Meta: model = Event fields = "__all__" class EventLocalizedModelForm(forms.ModelForm): class Meta: model = Event fields = "__all__" localized_fields = "__all__"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/timezones/urls.py
tests/timezones/urls.py
from django.urls import path from . import admin as tz_admin # NOQA: register tz_admin urlpatterns = [ path("admin/", tz_admin.site.urls), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/generic_relations/test_forms.py
tests/generic_relations/test_forms.py
from django import forms from django.contrib.contenttypes.forms import generic_inlineformset_factory from django.contrib.contenttypes.models import ContentType from django.db import models from django.test import TestCase from django.test.utils import isolate_apps from .models import ( Animal, ForProxyModelModel, Gecko, Mineral, ProxyRelatedModel, TaggedItem, ) class CustomWidget(forms.TextInput): pass class TaggedItemForm(forms.ModelForm): class Meta: model = TaggedItem fields = "__all__" widgets = {"tag": CustomWidget} class GenericInlineFormsetTests(TestCase): def test_output(self): GenericFormSet = generic_inlineformset_factory(TaggedItem, extra=1) formset = GenericFormSet() self.assertHTMLEqual( "".join(form.as_p() for form in formset.forms), """ <p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag"> Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50"></p> <p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE"> Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE"> <input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p> """, ) formset = GenericFormSet(instance=Animal()) self.assertHTMLEqual( "".join(form.as_p() for form in formset.forms), """ <p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag"> Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50"></p> <p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE"> Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE"> <input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p> """, ) platypus = Animal.objects.create( common_name="Platypus", latin_name="Ornithorhynchus anatinus", ) platypus.tags.create(tag="shiny") GenericFormSet = generic_inlineformset_factory(TaggedItem, extra=1) formset = GenericFormSet(instance=platypus) tagged_item_id = TaggedItem.objects.get(tag="shiny", object_id=platypus.id).id self.assertHTMLEqual( "".join(form.as_p() for form in formset.forms), """ <p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag"> Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" value="shiny" maxlength="50"></p> <p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE"> Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE"> <input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" value="%s" id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p> <p><label for="id_generic_relations-taggeditem-content_type-object_id-1-tag"> Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-1-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-1-tag" maxlength="50"></p> <p><label for="id_generic_relations-taggeditem-content_type-object_id-1-DELETE"> Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-1-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-1-DELETE"> <input type="hidden" name="generic_relations-taggeditem-content_type-object_id-1-id" id="id_generic_relations-taggeditem-content_type-object_id-1-id"></p> """ % tagged_item_id, ) lion = Animal.objects.create(common_name="Lion", latin_name="Panthera leo") formset = GenericFormSet(instance=lion, prefix="x") self.assertHTMLEqual( "".join(form.as_p() for form in formset.forms), """ <p><label for="id_x-0-tag">Tag:</label> <input id="id_x-0-tag" type="text" name="x-0-tag" maxlength="50"></p> <p><label for="id_x-0-DELETE">Delete:</label> <input type="checkbox" name="x-0-DELETE" id="id_x-0-DELETE"> <input type="hidden" name="x-0-id" id="id_x-0-id"></p> """, ) def test_options(self): TaggedItemFormSet = generic_inlineformset_factory( TaggedItem, can_delete=False, exclude=["tag"], extra=3, ) platypus = Animal.objects.create( common_name="Platypus", latin_name="Ornithorhynchus anatinus" ) harmless = platypus.tags.create(tag="harmless") mammal = platypus.tags.create(tag="mammal") # Works without a queryset. formset = TaggedItemFormSet(instance=platypus) self.assertEqual(len(formset.forms), 5) self.assertHTMLEqual( formset.forms[0].as_p(), '<input type="hidden" ' 'name="generic_relations-taggeditem-content_type-object_id-0-id" ' 'value="%s" ' 'id="id_generic_relations-taggeditem-content_type-object_id-0-id">' % harmless.pk, ) self.assertEqual(formset.forms[0].instance, harmless) self.assertEqual(formset.forms[1].instance, mammal) self.assertIsNone(formset.forms[2].instance.pk) # A queryset can be used to alter display ordering. formset = TaggedItemFormSet( instance=platypus, queryset=TaggedItem.objects.order_by("-tag") ) self.assertEqual(len(formset.forms), 5) self.assertEqual(formset.forms[0].instance, mammal) self.assertEqual(formset.forms[1].instance, harmless) self.assertIsNone(formset.forms[2].instance.pk) # A queryset that omits items. formset = TaggedItemFormSet( instance=platypus, queryset=TaggedItem.objects.filter(tag__startswith="harm"), ) self.assertEqual(len(formset.forms), 4) self.assertEqual(formset.forms[0].instance, harmless) self.assertIsNone(formset.forms[1].instance.pk) def test_get_queryset_ordering(self): """ BaseGenericInlineFormSet.get_queryset() adds default ordering, if needed. """ inline_formset = generic_inlineformset_factory(TaggedItem, exclude=("tag",)) formset = inline_formset(instance=Gecko.objects.create()) self.assertIs(formset.get_queryset().ordered, True) def test_initial(self): quartz = Mineral.objects.create(name="Quartz", hardness=7) GenericFormSet = generic_inlineformset_factory(TaggedItem, extra=1) ctype = ContentType.objects.get_for_model(quartz) initial_data = [ { "tag": "lizard", "content_type": ctype.pk, "object_id": quartz.pk, } ] formset = GenericFormSet(initial=initial_data) self.assertEqual(formset.forms[0].initial, initial_data[0]) def test_meta_widgets(self): """TaggedItemForm has a widget defined in Meta.""" Formset = generic_inlineformset_factory(TaggedItem, TaggedItemForm) form = Formset().forms[0] self.assertIsInstance(form["tag"].field.widget, CustomWidget) @isolate_apps("generic_relations") def test_incorrect_content_type(self): class BadModel(models.Model): content_type = models.PositiveIntegerField() msg = ( "fk_name 'generic_relations.BadModel.content_type' is not a ForeignKey to " "ContentType" ) with self.assertRaisesMessage(Exception, msg): generic_inlineformset_factory(BadModel, TaggedItemForm) def test_save_new_uses_form_save(self): class SaveTestForm(forms.ModelForm): def save(self, *args, **kwargs): self.instance.saved_by = "custom method" return super().save(*args, **kwargs) Formset = generic_inlineformset_factory( ForProxyModelModel, fields="__all__", form=SaveTestForm ) instance = ProxyRelatedModel.objects.create() data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "0", "form-MAX_NUM_FORMS": "", "form-0-title": "foo", } formset = Formset(data, instance=instance, prefix="form") self.assertTrue(formset.is_valid()) new_obj = formset.save()[0] self.assertEqual(new_obj.saved_by, "custom method") def test_save_new_for_proxy(self): Formset = generic_inlineformset_factory( ForProxyModelModel, fields="__all__", for_concrete_model=False ) instance = ProxyRelatedModel.objects.create() data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "0", "form-MAX_NUM_FORMS": "", "form-0-title": "foo", } formset = Formset(data, instance=instance, prefix="form") self.assertTrue(formset.is_valid()) (new_obj,) = formset.save() self.assertEqual(new_obj.obj, instance) def test_save_new_for_concrete(self): Formset = generic_inlineformset_factory( ForProxyModelModel, fields="__all__", for_concrete_model=True ) instance = ProxyRelatedModel.objects.create() data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "0", "form-MAX_NUM_FORMS": "", "form-0-title": "foo", } formset = Formset(data, instance=instance, prefix="form") self.assertTrue(formset.is_valid()) (new_obj,) = formset.save() self.assertNotIsInstance(new_obj.obj, ProxyRelatedModel) def test_initial_count(self): GenericFormSet = generic_inlineformset_factory(TaggedItem) data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "", } formset = GenericFormSet(data=data, prefix="form") self.assertEqual(formset.initial_form_count(), 3) formset = GenericFormSet(data=data, prefix="form", save_as_new=True) self.assertEqual(formset.initial_form_count(), 0) def test_save_as_new(self): """ The save_as_new parameter creates new items that are associated with the object. """ lion = Animal.objects.create(common_name="Lion", latin_name="Panthera leo") yellow = lion.tags.create(tag="yellow") hairy = lion.tags.create(tag="hairy") GenericFormSet = generic_inlineformset_factory(TaggedItem) data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "2", "form-MAX_NUM_FORMS": "", "form-0-id": str(yellow.pk), "form-0-tag": "hunts", "form-1-id": str(hairy.pk), "form-1-tag": "roars", } formset = GenericFormSet(data, instance=lion, prefix="form", save_as_new=True) self.assertTrue(formset.is_valid()) tags = formset.save() self.assertEqual([tag.tag for tag in tags], ["hunts", "roars"]) hunts, roars = tags self.assertSequenceEqual( lion.tags.order_by("tag"), [hairy, hunts, roars, yellow] ) def test_absolute_max(self): GenericFormSet = generic_inlineformset_factory(TaggedItem, absolute_max=1500) data = { "form-TOTAL_FORMS": "1501", "form-INITIAL_FORMS": "0", "form-MAX_NUM_FORMS": "0", } formset = GenericFormSet(data=data, prefix="form") self.assertIs(formset.is_valid(), False) self.assertEqual(len(formset.forms), 1500) self.assertEqual( formset.non_form_errors(), ["Please submit at most 1000 forms."], ) def test_absolute_max_with_max_num(self): GenericFormSet = generic_inlineformset_factory( TaggedItem, max_num=20, absolute_max=100, ) data = { "form-TOTAL_FORMS": "101", "form-INITIAL_FORMS": "0", "form-MAX_NUM_FORMS": "0", } formset = GenericFormSet(data=data, prefix="form") self.assertIs(formset.is_valid(), False) self.assertEqual(len(formset.forms), 100) self.assertEqual( formset.non_form_errors(), ["Please submit at most 20 forms."], ) def test_can_delete_extra(self): GenericFormSet = generic_inlineformset_factory( TaggedItem, can_delete=True, can_delete_extra=True, extra=2, ) formset = GenericFormSet() self.assertEqual(len(formset), 2) self.assertIn("DELETE", formset.forms[0].fields) self.assertIn("DELETE", formset.forms[1].fields) def test_disable_delete_extra(self): GenericFormSet = generic_inlineformset_factory( TaggedItem, can_delete=True, can_delete_extra=False, extra=2, ) formset = GenericFormSet() self.assertEqual(len(formset), 2) self.assertNotIn("DELETE", formset.forms[0].fields) self.assertNotIn("DELETE", formset.forms[1].fields)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/generic_relations/models.py
tests/generic_relations/models.py
""" Generic relations Generic relations let an object have a foreign key to any object through a content-type/object-id field. A ``GenericForeignKey`` field can point to any object, be it animal, vegetable, or mineral. The canonical example is tags (although this example implementation is *far* from complete). """ from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models class TaggedItem(models.Model): """A tag on an item.""" tag = models.SlugField() content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Meta: ordering = ["tag", "content_type__model"] def __str__(self): return self.tag class ValuableTaggedItem(TaggedItem): value = models.PositiveIntegerField() class AbstractComparison(models.Model): comparative = models.CharField(max_length=50) content_type1 = models.ForeignKey( ContentType, models.CASCADE, related_name="comparative1_set" ) object_id1 = models.PositiveIntegerField() first_obj = GenericForeignKey(ct_field="content_type1", fk_field="object_id1") class Comparison(AbstractComparison): """ A model that tests having multiple GenericForeignKeys. One is defined through an inherited abstract model and one defined directly on this class. """ content_type2 = models.ForeignKey( ContentType, models.CASCADE, related_name="comparative2_set" ) object_id2 = models.PositiveIntegerField() other_obj = GenericForeignKey(ct_field="content_type2", fk_field="object_id2") def __str__(self): return "%s is %s than %s" % (self.first_obj, self.comparative, self.other_obj) class Animal(models.Model): common_name = models.CharField(max_length=150) latin_name = models.CharField(max_length=150) tags = GenericRelation(TaggedItem, related_query_name="animal") comparisons = GenericRelation( Comparison, object_id_field="object_id1", content_type_field="content_type1" ) def __str__(self): return self.common_name class Vegetable(models.Model): name = models.CharField(max_length=150) is_yucky = models.BooleanField(default=True) tags = GenericRelation(TaggedItem) def __str__(self): return self.name class Carrot(Vegetable): pass class Mineral(models.Model): name = models.CharField(max_length=150) hardness = models.PositiveSmallIntegerField() # note the lack of an explicit GenericRelation here... def __str__(self): return self.name class GeckoManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(has_tail=True) class Gecko(models.Model): has_tail = models.BooleanField(default=False) objects = GeckoManager() # To test fix for #11263 class Rock(Mineral): tags = GenericRelation(TaggedItem) class ValuableRock(Mineral): tags = GenericRelation(ValuableTaggedItem) class ManualPK(models.Model): id = models.IntegerField(primary_key=True) tags = GenericRelation(TaggedItem, related_query_name="manualpk") class ForProxyModelModel(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() obj = GenericForeignKey(for_concrete_model=False) title = models.CharField(max_length=255, null=True) class ForConcreteModelModel(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() obj = GenericForeignKey() class ConcreteRelatedModel(models.Model): bases = GenericRelation(ForProxyModelModel, for_concrete_model=False) class ProxyRelatedModel(ConcreteRelatedModel): class Meta: proxy = True # To test fix for #7551 class AllowsNullGFK(models.Model): content_type = models.ForeignKey(ContentType, models.SET_NULL, null=True) object_id = models.PositiveIntegerField(null=True) content_object = GenericForeignKey()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/generic_relations/__init__.py
tests/generic_relations/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/generic_relations/tests.py
tests/generic_relations/tests.py
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.prefetch import GenericPrefetch from django.core.exceptions import FieldError, FieldFetchBlocked from django.db.models import Q, prefetch_related_objects from django.db.models.fetch_modes import FETCH_PEERS, RAISE from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from .models import ( AllowsNullGFK, Animal, Carrot, Comparison, ConcreteRelatedModel, ForConcreteModelModel, ForProxyModelModel, Gecko, ManualPK, Mineral, ProxyRelatedModel, Rock, TaggedItem, ValuableRock, ValuableTaggedItem, Vegetable, ) class GenericRelationsTests(TestCase): @classmethod def setUpTestData(cls): cls.lion = Animal.objects.create(common_name="Lion", latin_name="Panthera leo") cls.platypus = Animal.objects.create( common_name="Platypus", latin_name="Ornithorhynchus anatinus", ) Vegetable.objects.create(name="Eggplant", is_yucky=True) cls.bacon = Vegetable.objects.create(name="Bacon", is_yucky=False) cls.quartz = Mineral.objects.create(name="Quartz", hardness=7) # Tagging stuff. cls.fatty = cls.bacon.tags.create(tag="fatty") cls.salty = cls.bacon.tags.create(tag="salty") cls.yellow = cls.lion.tags.create(tag="yellow") cls.hairy = cls.lion.tags.create(tag="hairy") def comp_func(self, obj): # Original list of tags: return obj.tag, obj.content_type.model_class(), obj.object_id async def test_generic_async_acreate(self): await self.bacon.tags.acreate(tag="orange") self.assertEqual(await self.bacon.tags.acount(), 3) def test_generic_update_or_create_when_created(self): """ Should be able to use update_or_create from the generic related manager to create a tag. Refs #23611. """ count = self.bacon.tags.count() tag, created = self.bacon.tags.update_or_create(tag="stinky") self.assertTrue(created) self.assertEqual(count + 1, self.bacon.tags.count()) def test_generic_update_or_create_when_created_with_create_defaults(self): count = self.bacon.tags.count() tag, created = self.bacon.tags.update_or_create( # Since, the "stinky" tag doesn't exist create # a "juicy" tag. create_defaults={"tag": "juicy"}, defaults={"tag": "uncured"}, tag="stinky", ) self.assertEqual(tag.tag, "juicy") self.assertIs(created, True) self.assertEqual(count + 1, self.bacon.tags.count()) def test_generic_update_or_create_when_updated(self): """ Should be able to use update_or_create from the generic related manager to update a tag. Refs #23611. """ count = self.bacon.tags.count() tag = self.bacon.tags.create(tag="stinky") self.assertEqual(count + 1, self.bacon.tags.count()) tag, created = self.bacon.tags.update_or_create( defaults={"tag": "juicy"}, id=tag.id ) self.assertFalse(created) self.assertEqual(count + 1, self.bacon.tags.count()) self.assertEqual(tag.tag, "juicy") def test_generic_update_or_create_when_updated_with_defaults(self): count = self.bacon.tags.count() tag = self.bacon.tags.create(tag="stinky") self.assertEqual(count + 1, self.bacon.tags.count()) tag, created = self.bacon.tags.update_or_create( create_defaults={"tag": "uncured"}, defaults={"tag": "juicy"}, id=tag.id ) self.assertIs(created, False) self.assertEqual(count + 1, self.bacon.tags.count()) self.assertEqual(tag.tag, "juicy") async def test_generic_async_aupdate_or_create(self): tag, created = await self.bacon.tags.aupdate_or_create( id=self.fatty.id, defaults={"tag": "orange"} ) self.assertIs(created, False) self.assertEqual(tag.tag, "orange") self.assertEqual(await self.bacon.tags.acount(), 2) tag, created = await self.bacon.tags.aupdate_or_create(tag="pink") self.assertIs(created, True) self.assertEqual(await self.bacon.tags.acount(), 3) self.assertEqual(tag.tag, "pink") async def test_generic_async_aupdate_or_create_with_create_defaults(self): tag, created = await self.bacon.tags.aupdate_or_create( id=self.fatty.id, create_defaults={"tag": "pink"}, defaults={"tag": "orange"}, ) self.assertIs(created, False) self.assertEqual(tag.tag, "orange") self.assertEqual(await self.bacon.tags.acount(), 2) tag, created = await self.bacon.tags.aupdate_or_create( tag="pink", create_defaults={"tag": "brown"} ) self.assertIs(created, True) self.assertEqual(await self.bacon.tags.acount(), 3) self.assertEqual(tag.tag, "brown") def test_generic_get_or_create_when_created(self): """ Should be able to use get_or_create from the generic related manager to create a tag. Refs #23611. """ count = self.bacon.tags.count() tag, created = self.bacon.tags.get_or_create(tag="stinky") self.assertTrue(created) self.assertEqual(count + 1, self.bacon.tags.count()) def test_generic_get_or_create_when_exists(self): """ Should be able to use get_or_create from the generic related manager to get a tag. Refs #23611. """ count = self.bacon.tags.count() tag = self.bacon.tags.create(tag="stinky") self.assertEqual(count + 1, self.bacon.tags.count()) tag, created = self.bacon.tags.get_or_create( id=tag.id, defaults={"tag": "juicy"} ) self.assertFalse(created) self.assertEqual(count + 1, self.bacon.tags.count()) # shouldn't had changed the tag self.assertEqual(tag.tag, "stinky") async def test_generic_async_aget_or_create(self): tag, created = await self.bacon.tags.aget_or_create( id=self.fatty.id, defaults={"tag": "orange"} ) self.assertIs(created, False) self.assertEqual(tag.tag, "fatty") self.assertEqual(await self.bacon.tags.acount(), 2) tag, created = await self.bacon.tags.aget_or_create(tag="orange") self.assertIs(created, True) self.assertEqual(await self.bacon.tags.acount(), 3) self.assertEqual(tag.tag, "orange") def test_generic_relations_m2m_mimic(self): """ Objects with declared GenericRelations can be tagged directly -- the API mimics the many-to-many API. """ self.assertSequenceEqual(self.lion.tags.all(), [self.hairy, self.yellow]) self.assertSequenceEqual(self.bacon.tags.all(), [self.fatty, self.salty]) def test_access_content_object(self): """ Test accessing the content object like a foreign key. """ tagged_item = TaggedItem.objects.get(tag="salty") self.assertEqual(tagged_item.content_object, self.bacon) def test_query_content_object(self): qs = TaggedItem.objects.filter(animal__isnull=False).order_by( "animal__common_name", "tag" ) self.assertSequenceEqual(qs, [self.hairy, self.yellow]) mpk = ManualPK.objects.create(id=1) mpk.tags.create(tag="mpk") qs = TaggedItem.objects.filter( Q(animal__isnull=False) | Q(manualpk__id=1) ).order_by("tag") self.assertQuerySetEqual(qs, ["hairy", "mpk", "yellow"], lambda x: x.tag) def test_exclude_generic_relations(self): """ Test lookups over an object without GenericRelations. """ # Recall that the Mineral class doesn't have an explicit # GenericRelation defined. That's OK, because you can create # TaggedItems explicitly. However, excluding GenericRelations means # your lookups have to be a bit more explicit. shiny = TaggedItem.objects.create(content_object=self.quartz, tag="shiny") clearish = TaggedItem.objects.create(content_object=self.quartz, tag="clearish") ctype = ContentType.objects.get_for_model(self.quartz) q = TaggedItem.objects.filter( content_type__pk=ctype.id, object_id=self.quartz.id ) self.assertSequenceEqual(q, [clearish, shiny]) def test_access_via_content_type(self): """ Test lookups through content type. """ self.lion.delete() self.platypus.tags.create(tag="fatty") ctype = ContentType.objects.get_for_model(self.platypus) self.assertSequenceEqual( Animal.objects.filter(tags__content_type=ctype), [self.platypus], ) def test_set_foreign_key(self): """ You can set a generic foreign key in the way you'd expect. """ tag1 = TaggedItem.objects.create(content_object=self.quartz, tag="shiny") tag1.content_object = self.platypus tag1.save() self.assertSequenceEqual(self.platypus.tags.all(), [tag1]) def test_queries_across_generic_relations(self): """ Queries across generic relations respect the content types. Even though there are two TaggedItems with a tag of "fatty", this query only pulls out the one with the content type related to Animals. """ self.assertSequenceEqual( Animal.objects.order_by("common_name"), [self.lion, self.platypus], ) def test_queries_content_type_restriction(self): """ Create another fatty tagged instance with different PK to ensure there is a content type restriction in the generated queries below. """ mpk = ManualPK.objects.create(id=self.lion.pk) mpk.tags.create(tag="fatty") self.platypus.tags.create(tag="fatty") self.assertSequenceEqual( Animal.objects.filter(tags__tag="fatty"), [self.platypus], ) self.assertSequenceEqual( Animal.objects.exclude(tags__tag="fatty"), [self.lion], ) def test_object_deletion_with_generic_relation(self): """ If you delete an object with an explicit Generic relation, the related objects are deleted when the source object is deleted. """ self.assertQuerySetEqual( TaggedItem.objects.all(), [ ("fatty", Vegetable, self.bacon.pk), ("hairy", Animal, self.lion.pk), ("salty", Vegetable, self.bacon.pk), ("yellow", Animal, self.lion.pk), ], self.comp_func, ) self.lion.delete() self.assertQuerySetEqual( TaggedItem.objects.all(), [ ("fatty", Vegetable, self.bacon.pk), ("salty", Vegetable, self.bacon.pk), ], self.comp_func, ) def test_object_deletion_without_generic_relation(self): """ If Generic Relation is not explicitly defined, any related objects remain after deletion of the source object. """ TaggedItem.objects.create(content_object=self.quartz, tag="clearish") quartz_pk = self.quartz.pk self.quartz.delete() self.assertQuerySetEqual( TaggedItem.objects.all(), [ ("clearish", Mineral, quartz_pk), ("fatty", Vegetable, self.bacon.pk), ("hairy", Animal, self.lion.pk), ("salty", Vegetable, self.bacon.pk), ("yellow", Animal, self.lion.pk), ], self.comp_func, ) def test_tag_deletion_related_objects_unaffected(self): """ If you delete a tag, the objects using the tag are unaffected (other than losing a tag). """ ctype = ContentType.objects.get_for_model(self.lion) tag = TaggedItem.objects.get( content_type__pk=ctype.id, object_id=self.lion.id, tag="hairy" ) tag.delete() self.assertSequenceEqual(self.lion.tags.all(), [self.yellow]) self.assertQuerySetEqual( TaggedItem.objects.all(), [ ("fatty", Vegetable, self.bacon.pk), ("salty", Vegetable, self.bacon.pk), ("yellow", Animal, self.lion.pk), ], self.comp_func, ) def test_add_bulk(self): bacon = Vegetable.objects.create(name="Bacon", is_yucky=False) t1 = TaggedItem.objects.create(content_object=self.quartz, tag="shiny") t2 = TaggedItem.objects.create(content_object=self.quartz, tag="clearish") # One update() query. with self.assertNumQueries(1): bacon.tags.add(t1, t2) self.assertEqual(t1.content_object, bacon) self.assertEqual(t2.content_object, bacon) def test_add_bulk_false(self): bacon = Vegetable.objects.create(name="Bacon", is_yucky=False) t1 = TaggedItem.objects.create(content_object=self.quartz, tag="shiny") t2 = TaggedItem.objects.create(content_object=self.quartz, tag="clearish") # One save() for each object. with self.assertNumQueries(2): bacon.tags.add(t1, t2, bulk=False) self.assertEqual(t1.content_object, bacon) self.assertEqual(t2.content_object, bacon) def test_add_rejects_unsaved_objects(self): t1 = TaggedItem(content_object=self.quartz, tag="shiny") msg = ( "<TaggedItem: shiny> instance isn't saved. Use bulk=False or save the " "object first." ) with self.assertRaisesMessage(ValueError, msg): self.bacon.tags.add(t1) def test_add_rejects_wrong_instances(self): msg = "'TaggedItem' instance expected, got <Animal: Lion>" with self.assertRaisesMessage(TypeError, msg): self.bacon.tags.add(self.lion) async def test_aadd(self): bacon = await Vegetable.objects.acreate(name="Bacon", is_yucky=False) t1 = await TaggedItem.objects.acreate(content_object=self.quartz, tag="shiny") t2 = await TaggedItem.objects.acreate(content_object=self.quartz, tag="fatty") await bacon.tags.aadd(t1, t2, bulk=False) self.assertEqual(await bacon.tags.acount(), 2) def test_set(self): bacon = Vegetable.objects.create(name="Bacon", is_yucky=False) fatty = bacon.tags.create(tag="fatty") salty = bacon.tags.create(tag="salty") bacon.tags.set([fatty, salty]) self.assertSequenceEqual(bacon.tags.all(), [fatty, salty]) bacon.tags.set([fatty]) self.assertSequenceEqual(bacon.tags.all(), [fatty]) bacon.tags.set([]) self.assertSequenceEqual(bacon.tags.all(), []) bacon.tags.set([fatty, salty], bulk=False, clear=True) self.assertSequenceEqual(bacon.tags.all(), [fatty, salty]) bacon.tags.set([fatty], bulk=False, clear=True) self.assertSequenceEqual(bacon.tags.all(), [fatty]) bacon.tags.set([], clear=True) self.assertSequenceEqual(bacon.tags.all(), []) async def test_aset(self): bacon = await Vegetable.objects.acreate(name="Bacon", is_yucky=False) fatty = await bacon.tags.acreate(tag="fatty") await bacon.tags.aset([fatty]) self.assertEqual(await bacon.tags.acount(), 1) await bacon.tags.aset([]) self.assertEqual(await bacon.tags.acount(), 0) await bacon.tags.aset([fatty], bulk=False, clear=True) self.assertEqual(await bacon.tags.acount(), 1) def test_assign(self): bacon = Vegetable.objects.create(name="Bacon", is_yucky=False) fatty = bacon.tags.create(tag="fatty") salty = bacon.tags.create(tag="salty") bacon.tags.set([fatty, salty]) self.assertSequenceEqual(bacon.tags.all(), [fatty, salty]) bacon.tags.set([fatty]) self.assertSequenceEqual(bacon.tags.all(), [fatty]) bacon.tags.set([]) self.assertSequenceEqual(bacon.tags.all(), []) def test_assign_with_queryset(self): # Querysets used in reverse GFK assignments are pre-evaluated so their # value isn't affected by the clearing operation # in ManyRelatedManager.set() (#19816). bacon = Vegetable.objects.create(name="Bacon", is_yucky=False) bacon.tags.create(tag="fatty") bacon.tags.create(tag="salty") self.assertEqual(2, bacon.tags.count()) qs = bacon.tags.filter(tag="fatty") bacon.tags.set(qs) self.assertEqual(1, bacon.tags.count()) self.assertEqual(1, qs.count()) def test_clear(self): self.assertSequenceEqual( TaggedItem.objects.order_by("tag"), [self.fatty, self.hairy, self.salty, self.yellow], ) self.bacon.tags.clear() self.assertSequenceEqual(self.bacon.tags.all(), []) self.assertSequenceEqual( TaggedItem.objects.order_by("tag"), [self.hairy, self.yellow], ) async def test_aclear(self): await self.bacon.tags.aclear() self.assertEqual(await self.bacon.tags.acount(), 0) def test_remove(self): self.assertSequenceEqual( TaggedItem.objects.order_by("tag"), [self.fatty, self.hairy, self.salty, self.yellow], ) self.bacon.tags.remove(self.fatty) self.assertSequenceEqual(self.bacon.tags.all(), [self.salty]) self.assertSequenceEqual( TaggedItem.objects.order_by("tag"), [self.hairy, self.salty, self.yellow], ) async def test_aremove(self): await self.bacon.tags.aremove(self.fatty) self.assertEqual(await self.bacon.tags.acount(), 1) await self.bacon.tags.aremove(self.salty) self.assertEqual(await self.bacon.tags.acount(), 0) def test_generic_relation_related_name_default(self): # GenericRelation isn't usable from the reverse side by default. msg = ( "Cannot resolve keyword 'vegetable' into field. Choices are: " "animal, content_object, content_type, content_type_id, id, " "manualpk, object_id, tag, valuabletaggeditem" ) with self.assertRaisesMessage(FieldError, msg): TaggedItem.objects.filter(vegetable__isnull=True) def test_multiple_gfk(self): # Simple tests for multiple GenericForeignKeys # only uses one model, since the above tests should be sufficient. tiger = Animal.objects.create(common_name="tiger") cheetah = Animal.objects.create(common_name="cheetah") bear = Animal.objects.create(common_name="bear") # Create directly c1 = Comparison.objects.create( first_obj=cheetah, other_obj=tiger, comparative="faster" ) c2 = Comparison.objects.create( first_obj=tiger, other_obj=cheetah, comparative="cooler" ) # Create using GenericRelation c3 = tiger.comparisons.create(other_obj=bear, comparative="cooler") c4 = tiger.comparisons.create(other_obj=cheetah, comparative="stronger") self.assertSequenceEqual(cheetah.comparisons.all(), [c1]) # Filtering works self.assertCountEqual( tiger.comparisons.filter(comparative="cooler"), [c2, c3], ) # Filtering and deleting works subjective = ["cooler"] tiger.comparisons.filter(comparative__in=subjective).delete() self.assertCountEqual(Comparison.objects.all(), [c1, c4]) # If we delete cheetah, Comparisons with cheetah as 'first_obj' will be # deleted since Animal has an explicit GenericRelation to Comparison # through first_obj. Comparisons with cheetah as 'other_obj' will not # be deleted. cheetah.delete() self.assertSequenceEqual(Comparison.objects.all(), [c4]) def test_gfk_subclasses(self): # GenericForeignKey should work with subclasses (see #8309) quartz = Mineral.objects.create(name="Quartz", hardness=7) valuedtag = ValuableTaggedItem.objects.create( content_object=quartz, tag="shiny", value=10 ) self.assertEqual(valuedtag.content_object, quartz) def test_generic_relation_to_inherited_child(self): # GenericRelations to models that use multi-table inheritance work. granite = ValuableRock.objects.create(name="granite", hardness=5) ValuableTaggedItem.objects.create( content_object=granite, tag="countertop", value=1 ) self.assertEqual(ValuableRock.objects.filter(tags__value=1).count(), 1) # We're generating a slightly inefficient query for tags__tag - we # first join ValuableRock -> TaggedItem -> ValuableTaggedItem, and then # we fetch tag by joining TaggedItem from ValuableTaggedItem. The last # join isn't necessary, as TaggedItem <-> ValuableTaggedItem is a # one-to-one join. self.assertEqual(ValuableRock.objects.filter(tags__tag="countertop").count(), 1) granite.delete() # deleting the rock should delete the related tag. self.assertEqual(ValuableTaggedItem.objects.count(), 0) def test_gfk_manager(self): # GenericForeignKey should not use the default manager (which may # filter objects). tailless = Gecko.objects.create(has_tail=False) tag = TaggedItem.objects.create(content_object=tailless, tag="lizard") self.assertEqual(tag.content_object, tailless) def test_subclasses_with_gen_rel(self): """ Concrete model subclasses with generic relations work correctly (ticket 11263). """ granite = Rock.objects.create(name="granite", hardness=5) TaggedItem.objects.create(content_object=granite, tag="countertop") self.assertEqual(Rock.objects.get(tags__tag="countertop"), granite) def test_subclasses_with_parent_gen_rel(self): """ Generic relations on a base class (Vegetable) work correctly in subclasses (Carrot). """ bear = Carrot.objects.create(name="carrot") TaggedItem.objects.create(content_object=bear, tag="orange") self.assertEqual(Carrot.objects.get(tags__tag="orange"), bear) def test_get_or_create(self): # get_or_create should work with virtual fields (content_object) quartz = Mineral.objects.create(name="Quartz", hardness=7) tag, created = TaggedItem.objects.get_or_create( tag="shiny", defaults={"content_object": quartz} ) self.assertTrue(created) self.assertEqual(tag.tag, "shiny") self.assertEqual(tag.content_object.id, quartz.id) def test_update_or_create_defaults(self): # update_or_create should work with virtual fields (content_object) quartz = Mineral.objects.create(name="Quartz", hardness=7) diamond = Mineral.objects.create(name="Diamond", hardness=7) tag, created = TaggedItem.objects.update_or_create( tag="shiny", defaults={"content_object": quartz} ) self.assertTrue(created) self.assertEqual(tag.content_object.id, quartz.id) tag, created = TaggedItem.objects.update_or_create( tag="shiny", defaults={"content_object": diamond} ) self.assertFalse(created) self.assertEqual(tag.content_object.id, diamond.id) def test_update_or_create_defaults_with_create_defaults(self): # update_or_create() should work with virtual fields (content_object). quartz = Mineral.objects.create(name="Quartz", hardness=7) diamond = Mineral.objects.create(name="Diamond", hardness=7) tag, created = TaggedItem.objects.update_or_create( tag="shiny", create_defaults={"content_object": quartz}, defaults={"content_object": diamond}, ) self.assertIs(created, True) self.assertEqual(tag.content_object.id, quartz.id) tag, created = TaggedItem.objects.update_or_create( tag="shiny", create_defaults={"content_object": quartz}, defaults={"content_object": diamond}, ) self.assertIs(created, False) self.assertEqual(tag.content_object.id, diamond.id) def test_query_content_type(self): msg = "Field 'content_object' does not generate an automatic reverse relation" with self.assertRaisesMessage(FieldError, msg): TaggedItem.objects.get(content_object="") def test_unsaved_generic_foreign_key_parent_save(self): quartz = Mineral(name="Quartz", hardness=7) tagged_item = TaggedItem(tag="shiny", content_object=quartz) msg = ( "save() prohibited to prevent data loss due to unsaved related object " "'content_object'." ) with self.assertRaisesMessage(ValueError, msg): tagged_item.save() @skipUnlessDBFeature("has_bulk_insert") def test_unsaved_generic_foreign_key_parent_bulk_create(self): quartz = Mineral(name="Quartz", hardness=7) tagged_item = TaggedItem(tag="shiny", content_object=quartz) msg = ( "bulk_create() prohibited to prevent data loss due to unsaved related " "object 'content_object'." ) with self.assertRaisesMessage(ValueError, msg): TaggedItem.objects.bulk_create([tagged_item]) def test_cache_invalidation_for_content_type_id(self): # Create a Vegetable and Mineral with the same id. new_id = ( max( Vegetable.objects.order_by("-id")[0].id, Mineral.objects.order_by("-id")[0].id, ) + 1 ) broccoli = Vegetable.objects.create(id=new_id, name="Broccoli") diamond = Mineral.objects.create(id=new_id, name="Diamond", hardness=7) tag = TaggedItem.objects.create(content_object=broccoli, tag="yummy") tag.content_type = ContentType.objects.get_for_model(diamond) self.assertEqual(tag.content_object, diamond) def test_cache_invalidation_for_object_id(self): broccoli = Vegetable.objects.create(name="Broccoli") cauliflower = Vegetable.objects.create(name="Cauliflower") tag = TaggedItem.objects.create(content_object=broccoli, tag="yummy") tag.object_id = cauliflower.id self.assertEqual(tag.content_object, cauliflower) def test_assign_content_object_in_init(self): spinach = Vegetable(name="spinach") tag = TaggedItem(content_object=spinach) self.assertEqual(tag.content_object, spinach) def test_create_after_prefetch(self): platypus = Animal.objects.prefetch_related("tags").get(pk=self.platypus.pk) self.assertSequenceEqual(platypus.tags.all(), []) weird_tag = platypus.tags.create(tag="weird") self.assertSequenceEqual(platypus.tags.all(), [weird_tag]) def test_add_after_prefetch(self): platypus = Animal.objects.prefetch_related("tags").get(pk=self.platypus.pk) self.assertSequenceEqual(platypus.tags.all(), []) weird_tag = TaggedItem.objects.create(tag="weird", content_object=platypus) platypus.tags.add(weird_tag) self.assertSequenceEqual(platypus.tags.all(), [weird_tag]) def test_remove_after_prefetch(self): weird_tag = self.platypus.tags.create(tag="weird") platypus = Animal.objects.prefetch_related("tags").get(pk=self.platypus.pk) self.assertSequenceEqual(platypus.tags.all(), [weird_tag]) platypus.tags.remove(weird_tag) self.assertSequenceEqual(platypus.tags.all(), []) def test_clear_after_prefetch(self): weird_tag = self.platypus.tags.create(tag="weird") platypus = Animal.objects.prefetch_related("tags").get(pk=self.platypus.pk) self.assertSequenceEqual(platypus.tags.all(), [weird_tag]) platypus.tags.clear() self.assertSequenceEqual(platypus.tags.all(), []) def test_set_after_prefetch(self): platypus = Animal.objects.prefetch_related("tags").get(pk=self.platypus.pk) self.assertSequenceEqual(platypus.tags.all(), []) furry_tag = TaggedItem.objects.create(tag="furry", content_object=platypus) platypus.tags.set([furry_tag]) self.assertSequenceEqual(platypus.tags.all(), [furry_tag]) weird_tag = TaggedItem.objects.create(tag="weird", content_object=platypus) platypus.tags.set([weird_tag]) self.assertSequenceEqual(platypus.tags.all(), [weird_tag]) def test_add_then_remove_after_prefetch(self): furry_tag = self.platypus.tags.create(tag="furry") platypus = Animal.objects.prefetch_related("tags").get(pk=self.platypus.pk) self.assertSequenceEqual(platypus.tags.all(), [furry_tag]) weird_tag = self.platypus.tags.create(tag="weird") platypus.tags.add(weird_tag) self.assertSequenceEqual(platypus.tags.all(), [furry_tag, weird_tag]) platypus.tags.remove(weird_tag) self.assertSequenceEqual(platypus.tags.all(), [furry_tag]) def test_prefetch_related_different_content_types(self): TaggedItem.objects.create(content_object=self.platypus, tag="prefetch_tag_1") TaggedItem.objects.create( content_object=Vegetable.objects.create(name="Broccoli"), tag="prefetch_tag_2", ) TaggedItem.objects.create( content_object=Animal.objects.create(common_name="Bear"), tag="prefetch_tag_3", ) qs = TaggedItem.objects.filter( tag__startswith="prefetch_tag_", ).prefetch_related("content_object", "content_object__tags") with self.assertNumQueries(4): tags = list(qs) for tag in tags: self.assertSequenceEqual(tag.content_object.tags.all(), [tag]) def test_prefetch_related_custom_object_id(self): tiger = Animal.objects.create(common_name="tiger") cheetah = Animal.objects.create(common_name="cheetah") Comparison.objects.create( first_obj=cheetah, other_obj=tiger, comparative="faster", ) Comparison.objects.create( first_obj=tiger, other_obj=cheetah, comparative="cooler", ) qs = Comparison.objects.prefetch_related("first_obj__comparisons") for comparison in qs: self.assertSequenceEqual( comparison.first_obj.comparisons.all(), [comparison] ) def test_generic_prefetch(self): tagged_vegetable = TaggedItem.objects.create( tag="great", content_object=self.bacon ) tagged_animal = TaggedItem.objects.create( tag="awesome", content_object=self.platypus ) # Getting the instances again so that content object is deferred. tagged_vegetable = TaggedItem.objects.get(pk=tagged_vegetable.pk) tagged_animal = TaggedItem.objects.get(pk=tagged_animal.pk) with self.assertNumQueries(2): prefetch_related_objects( [tagged_vegetable, tagged_animal], GenericPrefetch( "content_object", [Vegetable.objects.all(), Animal.objects.only("common_name")], ), ) with self.assertNumQueries(0): self.assertEqual(tagged_vegetable.content_object.name, self.bacon.name) with self.assertNumQueries(0): self.assertEqual( tagged_animal.content_object.common_name, self.platypus.common_name, ) with self.assertNumQueries(1): self.assertEqual( tagged_animal.content_object.latin_name, self.platypus.latin_name, ) def test_fetch_mode_fetch_peers(self): TaggedItem.objects.bulk_create( [ TaggedItem(tag="lion", content_object=self.lion), TaggedItem(tag="platypus", content_object=self.platypus), TaggedItem(tag="quartz", content_object=self.quartz), ] ) # Peers fetching should fetch all related peers GFKs at once which is # one query per content type. with self.assertNumQueries(1):
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/foreign_object/test_tuple_lookups.py
tests/foreign_object/test_tuple_lookups.py
import itertools from django.db.models import F from django.db.models.fields.tuple_lookups import ( TupleExact, TupleGreaterThan, TupleGreaterThanOrEqual, TupleIn, TupleIsNull, TupleLessThan, TupleLessThanOrEqual, ) from django.db.models.lookups import In from django.test import TestCase, skipUnlessDBFeature from .models import Contact, Customer class TupleLookupsTests(TestCase): @classmethod def setUpTestData(cls): super().setUpTestData() cls.customer_1 = Customer.objects.create(customer_id=1, company="a") cls.customer_2 = Customer.objects.create(customer_id=1, company="b") cls.customer_3 = Customer.objects.create(customer_id=2, company="c") cls.customer_4 = Customer.objects.create(customer_id=3, company="d") cls.customer_5 = Customer.objects.create(customer_id=1, company="e") cls.contact_1 = Contact.objects.create(customer=cls.customer_1) cls.contact_2 = Contact.objects.create(customer=cls.customer_1) cls.contact_3 = Contact.objects.create(customer=cls.customer_2) cls.contact_4 = Contact.objects.create(customer=cls.customer_3) cls.contact_5 = Contact.objects.create(customer=cls.customer_1) cls.contact_6 = Contact.objects.create(customer=cls.customer_5) def test_exact(self): test_cases = ( (self.customer_1, (self.contact_1, self.contact_2, self.contact_5)), (self.customer_2, (self.contact_3,)), (self.customer_3, (self.contact_4,)), (self.customer_4, ()), (self.customer_5, (self.contact_6,)), ) for customer, contacts in test_cases: with self.subTest( "filter(customer=customer)", customer=customer, contacts=contacts, ): self.assertSequenceEqual( Contact.objects.filter(customer=customer).order_by("id"), contacts ) with self.subTest( "filter(TupleExact)", customer=customer, contacts=contacts, ): lhs = (F("customer_code"), F("company_code")) rhs = (customer.customer_id, customer.company) lookup = TupleExact(lhs, rhs) self.assertSequenceEqual( Contact.objects.filter(lookup).order_by("id"), contacts ) def test_exact_subquery(self): msg = ( "The QuerySet value for the exact lookup must have 2 selected " "fields (received 1)" ) with self.assertRaisesMessage(ValueError, msg): subquery = Customer.objects.filter(id=self.customer_1.id)[:1] self.assertSequenceEqual( Contact.objects.filter(customer=subquery).order_by("id"), () ) def test_in(self): cust_1, cust_2, cust_3, cust_4, cust_5 = ( self.customer_1, self.customer_2, self.customer_3, self.customer_4, self.customer_5, ) c1, c2, c3, c4, c5, c6 = ( self.contact_1, self.contact_2, self.contact_3, self.contact_4, self.contact_5, self.contact_6, ) test_cases = ( ((), ()), ((cust_1,), (c1, c2, c5)), ((cust_1, cust_2), (c1, c2, c3, c5)), ((cust_1, cust_2, cust_3), (c1, c2, c3, c4, c5)), ((cust_1, cust_2, cust_3, cust_4), (c1, c2, c3, c4, c5)), ((cust_1, cust_2, cust_3, cust_4, cust_5), (c1, c2, c3, c4, c5, c6)), ) for customers, contacts in test_cases: with self.subTest( "filter(customer__in=customers)", customers=customers, contacts=contacts, ): self.assertSequenceEqual( Contact.objects.filter(customer__in=customers).order_by("id"), contacts, ) with self.subTest( "filter(TupleIn)", customers=customers, contacts=contacts, ): lhs = (F("customer_code"), F("company_code")) rhs = [(c.customer_id, c.company) for c in customers] lookup = TupleIn(lhs, rhs) self.assertSequenceEqual( Contact.objects.filter(lookup).order_by("id"), contacts ) @skipUnlessDBFeature("allow_sliced_subqueries_with_in") def test_in_subquery(self): subquery = Customer.objects.filter(id=self.customer_1.id)[:1] self.assertSequenceEqual( Contact.objects.filter(customer__in=subquery).order_by("id"), (self.contact_1, self.contact_2, self.contact_5), ) def test_tuple_in_subquery_must_be_query(self): lhs = (F("customer_code"), F("company_code")) # If rhs is any non-Query object with an as_sql() function. rhs = In(F("customer_code"), [1, 2, 3]) with self.assertRaisesMessage( ValueError, "'in' subquery lookup of ('customer_code', 'company_code') " "must be a Query object (received 'In')", ): TupleIn(lhs, rhs) def test_tuple_in_subquery_must_have_2_fields(self): lhs = (F("customer_code"), F("company_code")) rhs = Customer.objects.values_list("customer_id").query msg = ( "The QuerySet value for the 'in' lookup must have 2 selected " "fields (received 1)" ) with self.assertRaisesMessage(ValueError, msg): TupleIn(lhs, rhs) def test_tuple_in_subquery(self): customers = Customer.objects.values_list("customer_id", "company") test_cases = ( (self.customer_1, (self.contact_1, self.contact_2, self.contact_5)), (self.customer_2, (self.contact_3,)), (self.customer_3, (self.contact_4,)), (self.customer_4, ()), (self.customer_5, (self.contact_6,)), ) for customer, contacts in test_cases: lhs = (F("customer_code"), F("company_code")) rhs = customers.filter(id=customer.id).query lookup = TupleIn(lhs, rhs) qs = Contact.objects.filter(lookup).order_by("id") with self.subTest(customer=customer.id, query=str(qs.query)): self.assertSequenceEqual(qs, contacts) def test_tuple_in_rhs_must_be_collection_of_tuples_or_lists(self): test_cases = ( (1, 2, 3), ((1, 2), (3, 4), None), ) for rhs in test_cases: with self.subTest(rhs=rhs): with self.assertRaisesMessage( ValueError, "'in' lookup of ('customer_code', 'company_code') " "must be a collection of tuples or lists", ): TupleIn((F("customer_code"), F("company_code")), rhs) def test_tuple_in_rhs_must_have_2_elements_each(self): test_cases = ( ((),), ((1,),), ((1, 2, 3),), ) for rhs in test_cases: with self.subTest(rhs=rhs): with self.assertRaisesMessage( ValueError, "'in' lookup of ('customer_code', 'company_code') " "must have 2 elements each", ): TupleIn((F("customer_code"), F("company_code")), rhs) def test_lt(self): c1, c2, c3, c4, c5, c6 = ( self.contact_1, self.contact_2, self.contact_3, self.contact_4, self.contact_5, self.contact_6, ) test_cases = ( (self.customer_1, ()), (self.customer_2, (c1, c2, c5)), (self.customer_5, (c1, c2, c3, c5)), (self.customer_3, (c1, c2, c3, c5, c6)), (self.customer_4, (c1, c2, c3, c4, c5, c6)), ) for customer, contacts in test_cases: with self.subTest( "filter(customer__lt=customer)", customer=customer, contacts=contacts, ): self.assertSequenceEqual( Contact.objects.filter(customer__lt=customer).order_by("id"), contacts, ) with self.subTest( "filter(TupleLessThan)", customer=customer, contacts=contacts, ): lhs = (F("customer_code"), F("company_code")) rhs = (customer.customer_id, customer.company) lookup = TupleLessThan(lhs, rhs) self.assertSequenceEqual( Contact.objects.filter(lookup).order_by("id"), contacts ) def test_lt_subquery(self): with self.assertRaisesMessage( ValueError, "'lt' doesn't support multi-column subqueries." ): subquery = Customer.objects.filter(id=self.customer_1.id)[:1] self.assertSequenceEqual( Contact.objects.filter(customer__lt=subquery).order_by("id"), () ) def test_lte(self): c1, c2, c3, c4, c5, c6 = ( self.contact_1, self.contact_2, self.contact_3, self.contact_4, self.contact_5, self.contact_6, ) test_cases = ( (self.customer_1, (c1, c2, c5)), (self.customer_2, (c1, c2, c3, c5)), (self.customer_5, (c1, c2, c3, c5, c6)), (self.customer_3, (c1, c2, c3, c4, c5, c6)), (self.customer_4, (c1, c2, c3, c4, c5, c6)), ) for customer, contacts in test_cases: with self.subTest( "filter(customer__lte=customer)", customer=customer, contacts=contacts, ): self.assertSequenceEqual( Contact.objects.filter(customer__lte=customer).order_by("id"), contacts, ) with self.subTest( "filter(TupleLessThanOrEqual)", customer=customer, contacts=contacts, ): lhs = (F("customer_code"), F("company_code")) rhs = (customer.customer_id, customer.company) lookup = TupleLessThanOrEqual(lhs, rhs) self.assertSequenceEqual( Contact.objects.filter(lookup).order_by("id"), contacts ) def test_lte_subquery(self): with self.assertRaisesMessage( ValueError, "'lte' doesn't support multi-column subqueries." ): subquery = Customer.objects.filter(id=self.customer_1.id)[:1] self.assertSequenceEqual( Contact.objects.filter(customer__lte=subquery).order_by("id"), () ) def test_gt(self): test_cases = ( (self.customer_1, (self.contact_3, self.contact_4, self.contact_6)), (self.customer_2, (self.contact_4, self.contact_6)), (self.customer_5, (self.contact_4,)), (self.customer_3, ()), (self.customer_4, ()), ) for customer, contacts in test_cases: with self.subTest( "filter(customer__gt=customer)", customer=customer, contacts=contacts, ): self.assertSequenceEqual( Contact.objects.filter(customer__gt=customer).order_by("id"), contacts, ) with self.subTest( "filter(TupleGreaterThan)", customer=customer, contacts=contacts, ): lhs = (F("customer_code"), F("company_code")) rhs = (customer.customer_id, customer.company) lookup = TupleGreaterThan(lhs, rhs) self.assertSequenceEqual( Contact.objects.filter(lookup).order_by("id"), contacts ) def test_gt_subquery(self): with self.assertRaisesMessage( ValueError, "'gt' doesn't support multi-column subqueries." ): subquery = Customer.objects.filter(id=self.customer_1.id)[:1] self.assertSequenceEqual( Contact.objects.filter(customer__gt=subquery).order_by("id"), () ) def test_gte(self): c1, c2, c3, c4, c5, c6 = ( self.contact_1, self.contact_2, self.contact_3, self.contact_4, self.contact_5, self.contact_6, ) test_cases = ( (self.customer_1, (c1, c2, c3, c4, c5, c6)), (self.customer_2, (c3, c4, c6)), (self.customer_5, (c4, c6)), (self.customer_3, (c4,)), (self.customer_4, ()), ) for customer, contacts in test_cases: with self.subTest( "filter(customer__gte=customer)", customer=customer, contacts=contacts, ): self.assertSequenceEqual( Contact.objects.filter(customer__gte=customer).order_by("pk"), contacts, ) with self.subTest( "filter(TupleGreaterThanOrEqual)", customer=customer, contacts=contacts, ): lhs = (F("customer_code"), F("company_code")) rhs = (customer.customer_id, customer.company) lookup = TupleGreaterThanOrEqual(lhs, rhs) self.assertSequenceEqual( Contact.objects.filter(lookup).order_by("id"), contacts ) def test_gte_subquery(self): with self.assertRaisesMessage( ValueError, "'gte' doesn't support multi-column subqueries." ): subquery = Customer.objects.filter(id=self.customer_1.id)[:1] self.assertSequenceEqual( Contact.objects.filter(customer__gte=subquery).order_by("id"), () ) def test_isnull(self): contacts = ( self.contact_1, self.contact_2, self.contact_3, self.contact_4, self.contact_5, self.contact_6, ) with self.subTest("filter(customer__isnull=True)"): self.assertSequenceEqual( Contact.objects.filter(customer__isnull=True).order_by("id"), (), ) with self.subTest("filter(TupleIsNull(True))"): lhs = (F("customer_code"), F("company_code")) lookup = TupleIsNull(lhs, True) self.assertSequenceEqual( Contact.objects.filter(lookup).order_by("id"), (), ) with self.subTest("filter(customer__isnull=False)"): self.assertSequenceEqual( Contact.objects.filter(customer__isnull=False).order_by("id"), contacts, ) with self.subTest("filter(TupleIsNull(False))"): lhs = (F("customer_code"), F("company_code")) lookup = TupleIsNull(lhs, False) self.assertSequenceEqual( Contact.objects.filter(lookup).order_by("id"), contacts, ) def test_isnull_subquery(self): with self.assertRaisesMessage( ValueError, "'isnull' doesn't support multi-column subqueries." ): subquery = Customer.objects.filter(id=0)[:1] self.assertSequenceEqual( Contact.objects.filter(customer__isnull=subquery).order_by("id"), () ) def test_lookup_errors(self): m_2_elements = "'%s' lookup of 'customer' must have 2 elements" m_2_elements_each = "'in' lookup of 'customer' must have 2 elements each" test_cases = ( ({"customer": 1}, m_2_elements % "exact"), ({"customer": (1, 2, 3)}, m_2_elements % "exact"), ({"customer__in": (1, 2, 3)}, m_2_elements_each), ({"customer__in": ("foo", "bar")}, m_2_elements_each), ({"customer__gt": 1}, m_2_elements % "gt"), ({"customer__gt": (1, 2, 3)}, m_2_elements % "gt"), ({"customer__gte": 1}, m_2_elements % "gte"), ({"customer__gte": (1, 2, 3)}, m_2_elements % "gte"), ({"customer__lt": 1}, m_2_elements % "lt"), ({"customer__lt": (1, 2, 3)}, m_2_elements % "lt"), ({"customer__lte": 1}, m_2_elements % "lte"), ({"customer__lte": (1, 2, 3)}, m_2_elements % "lte"), ) for kwargs, message in test_cases: with ( self.subTest(kwargs=kwargs), self.assertRaisesMessage(ValueError, message), ): Contact.objects.get(**kwargs) def test_tuple_lookup_names(self): test_cases = ( (TupleExact, "exact"), (TupleGreaterThan, "gt"), (TupleGreaterThanOrEqual, "gte"), (TupleLessThan, "lt"), (TupleLessThanOrEqual, "lte"), (TupleIn, "in"), (TupleIsNull, "isnull"), ) for lookup_class, lookup_name in test_cases: with self.subTest(lookup_name): self.assertEqual(lookup_class.lookup_name, lookup_name) def test_tuple_lookup_rhs_must_be_tuple_or_list(self): test_cases = itertools.product( ( TupleExact, TupleGreaterThan, TupleGreaterThanOrEqual, TupleLessThan, TupleLessThanOrEqual, TupleIn, ), ( 0, 1, None, True, False, {"foo": "bar"}, ), ) for lookup_cls, rhs in test_cases: lookup_name = lookup_cls.lookup_name with self.subTest(lookup_name=lookup_name, rhs=rhs): with self.assertRaisesMessage( ValueError, f"'{lookup_name}' lookup of ('customer_code', 'company_code') " "must be a tuple or a list", ): lookup_cls((F("customer_code"), F("company_code")), rhs) def test_tuple_lookup_rhs_must_have_2_elements(self): test_cases = itertools.product( ( TupleExact, TupleGreaterThan, TupleGreaterThanOrEqual, TupleLessThan, TupleLessThanOrEqual, ), ( [], [1], [1, 2, 3], (), (1,), (1, 2, 3), ), ) for lookup_cls, rhs in test_cases: lookup_name = lookup_cls.lookup_name with self.subTest(lookup_name=lookup_name, rhs=rhs): with self.assertRaisesMessage( ValueError, f"'{lookup_name}' lookup of ('customer_code', 'company_code') " "must have 2 elements", ): lookup_cls((F("customer_code"), F("company_code")), rhs)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/foreign_object/test_forms.py
tests/foreign_object/test_forms.py
import datetime from django import forms from django.test import TestCase from .models import Article class FormsTests(TestCase): # ForeignObjects should not have any form fields, currently the user needs # to manually deal with the foreignobject relation. class ArticleForm(forms.ModelForm): class Meta: model = Article fields = "__all__" def test_foreign_object_form(self): # A very crude test checking that the non-concrete fields do not get # form fields. form = FormsTests.ArticleForm() self.assertIn("id_pub_date", form.as_table()) self.assertNotIn("active_translation", form.as_table()) form = FormsTests.ArticleForm(data={"pub_date": str(datetime.date.today())}) self.assertTrue(form.is_valid()) a = form.save() self.assertEqual(a.pub_date, datetime.date.today()) form = FormsTests.ArticleForm(instance=a, data={"pub_date": "2013-01-01"}) a2 = form.save() self.assertEqual(a.pk, a2.pk) self.assertEqual(a2.pub_date, datetime.date(2013, 1, 1))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/foreign_object/test_agnostic_order_trimjoin.py
tests/foreign_object/test_agnostic_order_trimjoin.py
from operator import attrgetter from django.test.testcases import TestCase from .models import Address, Contact, Customer class TestLookupQuery(TestCase): @classmethod def setUpTestData(cls): cls.address = Address.objects.create(company=1, customer_id=20) cls.customer1 = Customer.objects.create(company=1, customer_id=20) cls.contact1 = Contact.objects.create(company_code=1, customer_code=20) def test_deep_mixed_forward(self): self.assertQuerySetEqual( Address.objects.filter(customer__contacts=self.contact1), [self.address.id], attrgetter("id"), ) def test_deep_mixed_backward(self): self.assertQuerySetEqual( Contact.objects.filter(customer__address=self.address), [self.contact1.id], attrgetter("id"), )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/foreign_object/__init__.py
tests/foreign_object/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/foreign_object/tests.py
tests/foreign_object/tests.py
import copy import datetime import pickle from operator import attrgetter from django.core.exceptions import FieldError, ValidationError from django.db import connection, models from django.db.models import FETCH_PEERS from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext, isolate_apps from django.utils import translation from .models import ( Article, ArticleIdea, ArticleTag, ArticleTranslation, Country, CustomerTab, Friendship, Group, Membership, NewsArticle, Person, ) # Note that these tests are testing internal implementation details. # ForeignObject is not part of public API. class MultiColumnFKTests(TestCase): @classmethod def setUpTestData(cls): # Creating countries cls.usa = Country.objects.create(name="United States of America") cls.soviet_union = Country.objects.create(name="Soviet Union") # Creating People cls.bob = Person.objects.create(name="Bob", person_country=cls.usa) cls.jim = Person.objects.create(name="Jim", person_country=cls.usa) cls.george = Person.objects.create(name="George", person_country=cls.usa) cls.jane = Person.objects.create(name="Jane", person_country=cls.soviet_union) cls.mark = Person.objects.create(name="Mark", person_country=cls.soviet_union) cls.sam = Person.objects.create(name="Sam", person_country=cls.soviet_union) # Creating Groups cls.kgb = Group.objects.create(name="KGB", group_country=cls.soviet_union) cls.cia = Group.objects.create(name="CIA", group_country=cls.usa) cls.republican = Group.objects.create(name="Republican", group_country=cls.usa) cls.democrat = Group.objects.create(name="Democrat", group_country=cls.usa) def test_get_succeeds_on_multicolumn_match(self): # Membership objects have access to their related Person if both # country_ids match between them membership = Membership.objects.create( membership_country_id=self.usa.id, person_id=self.bob.id, group_id=self.cia.id, ) person = membership.person self.assertEqual((person.id, person.name), (self.bob.id, "Bob")) def test_get_fails_on_multicolumn_mismatch(self): # Membership objects returns DoesNotExist error when there is no # Person with the same id and country_id membership = Membership.objects.create( membership_country_id=self.usa.id, person_id=self.jane.id, group_id=self.cia.id, ) with self.assertRaises(Person.DoesNotExist): getattr(membership, "person") def test_reverse_query_returns_correct_result(self): # Creating a valid membership because it has the same country has the # person Membership.objects.create( membership_country_id=self.usa.id, person_id=self.bob.id, group_id=self.cia.id, ) # Creating an invalid membership because it has a different country has # the person. Membership.objects.create( membership_country_id=self.soviet_union.id, person_id=self.bob.id, group_id=self.republican.id, ) with self.assertNumQueries(1): membership = self.bob.membership_set.get() self.assertEqual(membership.group_id, self.cia.id) self.assertIs(membership.person, self.bob) def test_query_filters_correctly(self): # Creating a to valid memberships Membership.objects.create( membership_country_id=self.usa.id, person_id=self.bob.id, group_id=self.cia.id, ) Membership.objects.create( membership_country_id=self.usa.id, person_id=self.jim.id, group_id=self.cia.id, ) # Creating an invalid membership Membership.objects.create( membership_country_id=self.soviet_union.id, person_id=self.george.id, group_id=self.cia.id, ) self.assertQuerySetEqual( Membership.objects.filter(person__name__contains="o"), [self.bob.id], attrgetter("person_id"), ) def test_reverse_query_filters_correctly(self): timemark = datetime.datetime.now(tz=datetime.UTC).replace(tzinfo=None) timedelta = datetime.timedelta(days=1) # Creating a to valid memberships Membership.objects.create( membership_country_id=self.usa.id, person_id=self.bob.id, group_id=self.cia.id, date_joined=timemark - timedelta, ) Membership.objects.create( membership_country_id=self.usa.id, person_id=self.jim.id, group_id=self.cia.id, date_joined=timemark + timedelta, ) # Creating an invalid membership Membership.objects.create( membership_country_id=self.soviet_union.id, person_id=self.george.id, group_id=self.cia.id, date_joined=timemark + timedelta, ) self.assertQuerySetEqual( Person.objects.filter(membership__date_joined__gte=timemark), ["Jim"], attrgetter("name"), ) def test_forward_in_lookup_filters_correctly(self): Membership.objects.create( membership_country_id=self.usa.id, person_id=self.bob.id, group_id=self.cia.id, ) Membership.objects.create( membership_country_id=self.usa.id, person_id=self.jim.id, group_id=self.cia.id, ) # Creating an invalid membership Membership.objects.create( membership_country_id=self.soviet_union.id, person_id=self.george.id, group_id=self.cia.id, ) self.assertQuerySetEqual( Membership.objects.filter(person__in=[self.george, self.jim]), [ self.jim.id, ], attrgetter("person_id"), ) self.assertQuerySetEqual( Membership.objects.filter(person__in=Person.objects.filter(name="Jim")), [ self.jim.id, ], attrgetter("person_id"), ) def test_double_nested_query(self): m1 = Membership.objects.create( membership_country_id=self.usa.id, person_id=self.bob.id, group_id=self.cia.id, ) m2 = Membership.objects.create( membership_country_id=self.usa.id, person_id=self.jim.id, group_id=self.cia.id, ) Friendship.objects.create( from_friend_country_id=self.usa.id, from_friend_id=self.bob.id, to_friend_country_id=self.usa.id, to_friend_id=self.jim.id, ) self.assertSequenceEqual( Membership.objects.filter( person__in=Person.objects.filter( from_friend__in=Friendship.objects.filter( to_friend__in=Person.objects.all() ) ) ), [m1], ) self.assertSequenceEqual( Membership.objects.exclude( person__in=Person.objects.filter( from_friend__in=Friendship.objects.filter( to_friend__in=Person.objects.all() ) ) ), [m2], ) def test_query_does_not_mutate(self): """ Recompiling the same subquery doesn't mutate it. """ queryset = Friendship.objects.filter(to_friend__in=Person.objects.all()) self.assertEqual(str(queryset.query), str(queryset.query)) def test_select_related_foreignkey_forward_works(self): Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.cia ) Membership.objects.create( membership_country=self.usa, person=self.jim, group=self.democrat ) with self.assertNumQueries(1): people = [ m.person for m in Membership.objects.select_related("person").order_by("pk") ] normal_people = [m.person for m in Membership.objects.order_by("pk")] self.assertEqual(people, normal_people) def test_prefetch_foreignobject_forward(self): Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.cia ) Membership.objects.create( membership_country=self.usa, person=self.jim, group=self.democrat ) with self.assertNumQueries(2): people = [ m.person for m in Membership.objects.prefetch_related("person").order_by("pk") ] normal_people = [m.person for m in Membership.objects.order_by("pk")] self.assertEqual(people, normal_people) def test_prefetch_foreignobject_hidden_forward(self): Friendship.objects.create( from_friend_country=self.usa, from_friend_id=self.bob.id, to_friend_country_id=self.usa.id, to_friend_id=self.george.id, ) Friendship.objects.create( from_friend_country=self.usa, from_friend_id=self.bob.id, to_friend_country_id=self.soviet_union.id, to_friend_id=self.sam.id, ) with self.assertNumQueries(2) as ctx: friendships = list( Friendship.objects.prefetch_related("to_friend").order_by("pk") ) prefetch_sql = ctx[-1]["sql"] # Prefetch queryset should be filtered by all foreign related fields # to prevent extra rows from being eagerly fetched. prefetch_where_sql = prefetch_sql.split("WHERE")[-1] for to_field_name in Friendship.to_friend.field.to_fields: to_field = Person._meta.get_field(to_field_name) with self.subTest(to_field=to_field): self.assertIn( connection.ops.quote_name(to_field.column), prefetch_where_sql, ) self.assertNotIn(" JOIN ", prefetch_sql) with self.assertNumQueries(0): self.assertEqual(friendships[0].to_friend, self.george) self.assertEqual(friendships[1].to_friend, self.sam) def test_prefetch_foreignobject_null_hidden_forward_skipped(self): fiendship = Friendship.objects.create( from_friend_country=self.usa, from_friend_id=self.bob.id, to_friend_country_id=self.usa.id, to_friend_id=None, ) with self.assertNumQueries(1): self.assertEqual( Friendship.objects.prefetch_related("to_friend").get(), fiendship, ) def test_prefetch_foreignobject_reverse(self): Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.cia ) Membership.objects.create( membership_country=self.usa, person=self.jim, group=self.democrat ) with self.assertNumQueries(2): membership_sets = [ list(p.membership_set.all()) for p in Person.objects.prefetch_related("membership_set").order_by( "pk" ) ] with self.assertNumQueries(7): normal_membership_sets = [ list(p.membership_set.all()) for p in Person.objects.order_by("pk") ] self.assertEqual(membership_sets, normal_membership_sets) def test_m2m_through_forward_returns_valid_members(self): # We start out by making sure that the Group 'CIA' has no members. self.assertQuerySetEqual(self.cia.members.all(), []) Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.cia ) Membership.objects.create( membership_country=self.usa, person=self.jim, group=self.cia ) # Bob and Jim should be members of the CIA. self.assertQuerySetEqual( self.cia.members.all(), ["Bob", "Jim"], attrgetter("name") ) def test_m2m_through_reverse_returns_valid_members(self): # We start out by making sure that Bob is in no groups. self.assertQuerySetEqual(self.bob.groups.all(), []) Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.cia ) Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.republican ) # Bob should be in the CIA and a Republican self.assertQuerySetEqual( self.bob.groups.all(), ["CIA", "Republican"], attrgetter("name") ) def test_m2m_through_forward_ignores_invalid_members(self): # We start out by making sure that the Group 'CIA' has no members. self.assertQuerySetEqual(self.cia.members.all(), []) # Something adds jane to group CIA but Jane is in Soviet Union which # isn't CIA's country. Membership.objects.create( membership_country=self.usa, person=self.jane, group=self.cia ) # There should still be no members in CIA self.assertQuerySetEqual(self.cia.members.all(), []) def test_m2m_through_reverse_ignores_invalid_members(self): # We start out by making sure that Jane has no groups. self.assertQuerySetEqual(self.jane.groups.all(), []) # Something adds jane to group CIA but Jane is in Soviet Union which # isn't CIA's country. Membership.objects.create( membership_country=self.usa, person=self.jane, group=self.cia ) # Jane should still not be in any groups self.assertQuerySetEqual(self.jane.groups.all(), []) def test_m2m_through_on_self_works(self): self.assertQuerySetEqual(self.jane.friends.all(), []) Friendship.objects.create( from_friend_country=self.jane.person_country, from_friend=self.jane, to_friend_country=self.george.person_country, to_friend=self.george, ) self.assertQuerySetEqual( self.jane.friends.all(), ["George"], attrgetter("name") ) def test_m2m_through_on_self_ignores_mismatch_columns(self): self.assertQuerySetEqual(self.jane.friends.all(), []) # Note that we use ids instead of instances. This is because instances # on ForeignObject properties will set all related field off of the # given instance. Friendship.objects.create( from_friend_id=self.jane.id, to_friend_id=self.george.id, to_friend_country_id=self.jane.person_country_id, from_friend_country_id=self.george.person_country_id, ) self.assertQuerySetEqual(self.jane.friends.all(), []) def test_prefetch_related_m2m_forward_works(self): Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.cia ) Membership.objects.create( membership_country=self.usa, person=self.jim, group=self.democrat ) with self.assertNumQueries(2): members_lists = [ list(g.members.all()) for g in Group.objects.prefetch_related("members") ] normal_members_lists = [list(g.members.all()) for g in Group.objects.all()] self.assertEqual(members_lists, normal_members_lists) def test_prefetch_related_m2m_reverse_works(self): Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.cia ) Membership.objects.create( membership_country=self.usa, person=self.jim, group=self.democrat ) with self.assertNumQueries(2): groups_lists = [ list(p.groups.all()) for p in Person.objects.prefetch_related("groups") ] normal_groups_lists = [list(p.groups.all()) for p in Person.objects.all()] self.assertEqual(groups_lists, normal_groups_lists) def test_refresh_foreign_object(self): member = Membership.objects.create( membership_country=self.usa, person=self.bob, group=self.cia ) member.person = self.jim with self.assertNumQueries(1): member.refresh_from_db() self.assertEqual(member.person, self.bob) @translation.override("fi") def test_translations(self): a1 = Article.objects.create(pub_date=datetime.date.today()) at1_fi = ArticleTranslation( article=a1, lang="fi", title="Otsikko", body="Diipadaapa" ) at1_fi.save() at2_en = ArticleTranslation( article=a1, lang="en", title="Title", body="Lalalalala" ) at2_en.save() self.assertEqual(Article.objects.get(pk=a1.pk).active_translation, at1_fi) with self.assertNumQueries(1): fetched = Article.objects.select_related("active_translation").get( active_translation__title="Otsikko" ) self.assertEqual(fetched.active_translation.title, "Otsikko") a2 = Article.objects.create(pub_date=datetime.date.today()) at2_fi = ArticleTranslation( article=a2, lang="fi", title="Atsikko", body="Diipadaapa", abstract="dipad" ) at2_fi.save() a3 = Article.objects.create(pub_date=datetime.date.today()) at3_en = ArticleTranslation( article=a3, lang="en", title="A title", body="lalalalala", abstract="lala" ) at3_en.save() # Test model initialization with active_translation field. a3 = Article(id=a3.id, pub_date=a3.pub_date, active_translation=at3_en) a3.save() self.assertEqual( list(Article.objects.filter(active_translation__abstract=None)), [a1, a3] ) self.assertEqual( list( Article.objects.filter( active_translation__abstract=None, active_translation__pk__isnull=False, ) ), [a1], ) with translation.override("en"): self.assertEqual( list(Article.objects.filter(active_translation__abstract=None)), [a1, a2], ) def test_foreign_key_raises_informative_does_not_exist(self): referrer = ArticleTranslation() with self.assertRaisesMessage( Article.DoesNotExist, "ArticleTranslation has no article" ): referrer.article def test_foreign_key_related_query_name(self): a1 = Article.objects.create(pub_date=datetime.date.today()) ArticleTag.objects.create(article=a1, name="foo") self.assertEqual(Article.objects.filter(tag__name="foo").count(), 1) self.assertEqual(Article.objects.filter(tag__name="bar").count(), 0) msg = ( "Cannot resolve keyword 'tags' into field. Choices are: " "active_translation, active_translation_q, articletranslation, " "id, idea_things, newsarticle, pub_date, tag" ) with self.assertRaisesMessage(FieldError, msg): Article.objects.filter(tags__name="foo") def test_many_to_many_related_query_name(self): a1 = Article.objects.create(pub_date=datetime.date.today()) i1 = ArticleIdea.objects.create(name="idea1") a1.ideas.add(i1) self.assertEqual(Article.objects.filter(idea_things__name="idea1").count(), 1) self.assertEqual(Article.objects.filter(idea_things__name="idea2").count(), 0) msg = ( "Cannot resolve keyword 'ideas' into field. Choices are: " "active_translation, active_translation_q, articletranslation, " "id, idea_things, newsarticle, pub_date, tag" ) with self.assertRaisesMessage(FieldError, msg): Article.objects.filter(ideas__name="idea1") @translation.override("fi") def test_inheritance(self): na = NewsArticle.objects.create(pub_date=datetime.date.today()) ArticleTranslation.objects.create( article=na, lang="fi", title="foo", body="bar" ) self.assertSequenceEqual( NewsArticle.objects.select_related("active_translation"), [na] ) with self.assertNumQueries(1): self.assertEqual( NewsArticle.objects.select_related("active_translation")[ 0 ].active_translation.title, "foo", ) @skipUnlessDBFeature("has_bulk_insert") def test_batch_create_foreign_object(self): objs = [ Person(name="abcd_%s" % i, person_country=self.usa) for i in range(0, 5) ] Person.objects.bulk_create(objs, 10) def test_isnull_lookup(self): m1 = Membership.objects.create( person_id=self.bob.id, membership_country_id=self.usa.id, group_id=None, ) m2 = Membership.objects.create( person_id=self.jim.id, membership_country_id=None, group_id=self.cia.id, ) m3 = Membership.objects.create( person_id=self.jane.id, membership_country_id=None, group_id=None, ) m4 = Membership.objects.create( person_id=self.george.id, membership_country_id=self.soviet_union.id, group_id=self.kgb.id, ) for member in [m1, m2, m3]: with self.assertRaises(Membership.group.RelatedObjectDoesNotExist): getattr(member, "group") self.assertSequenceEqual( Membership.objects.filter(group__isnull=True), [m1, m2, m3], ) self.assertSequenceEqual( Membership.objects.filter(group__isnull=False), [m4], ) def test_fetch_mode_copied_forward_fetching_one(self): person = Person.objects.fetch_mode(FETCH_PEERS).get(pk=self.bob.pk) self.assertEqual(person._state.fetch_mode, FETCH_PEERS) self.assertEqual( person.person_country._state.fetch_mode, FETCH_PEERS, ) def test_fetch_mode_copied_forward_fetching_many(self): people = list(Person.objects.fetch_mode(FETCH_PEERS)) person = people[0] self.assertEqual(person._state.fetch_mode, FETCH_PEERS) self.assertEqual( person.person_country._state.fetch_mode, FETCH_PEERS, ) def test_fetch_mode_copied_reverse_fetching_one(self): country = Country.objects.fetch_mode(FETCH_PEERS).get(pk=self.usa.pk) self.assertEqual(country._state.fetch_mode, FETCH_PEERS) person = country.person_set.get(pk=self.bob.pk) self.assertEqual( person._state.fetch_mode, FETCH_PEERS, ) def test_fetch_mode_copied_reverse_fetching_many(self): countries = list(Country.objects.fetch_mode(FETCH_PEERS)) country = countries[0] self.assertEqual(country._state.fetch_mode, FETCH_PEERS) person = country.person_set.earliest("pk") self.assertEqual( person._state.fetch_mode, FETCH_PEERS, ) class TestModelCheckTests(SimpleTestCase): @isolate_apps("foreign_object") def test_check_composite_foreign_object(self): class Parent(models.Model): a = models.PositiveIntegerField() b = models.PositiveIntegerField() class Meta: unique_together = (("a", "b"),) class Child(models.Model): a = models.PositiveIntegerField() b = models.PositiveIntegerField() value = models.CharField(max_length=255) parent = models.ForeignObject( Parent, on_delete=models.SET_NULL, from_fields=("a", "b"), to_fields=("a", "b"), related_name="children", ) self.assertEqual(Child._meta.get_field("parent").check(from_model=Child), []) @isolate_apps("foreign_object") def test_check_subset_composite_foreign_object(self): class Parent(models.Model): a = models.PositiveIntegerField() b = models.PositiveIntegerField() c = models.PositiveIntegerField() class Meta: unique_together = (("a", "b"),) class Child(models.Model): a = models.PositiveIntegerField() b = models.PositiveIntegerField() c = models.PositiveIntegerField() d = models.CharField(max_length=255) parent = models.ForeignObject( Parent, on_delete=models.SET_NULL, from_fields=("a", "b", "c"), to_fields=("a", "b", "c"), related_name="children", ) self.assertEqual(Child._meta.get_field("parent").check(from_model=Child), []) class TestExtraJoinFilterQ(TestCase): @translation.override("fi") def test_extra_join_filter_q(self): a = Article.objects.create(pub_date=datetime.datetime.today()) ArticleTranslation.objects.create( article=a, lang="fi", title="title", body="body" ) qs = Article.objects.all() with self.assertNumQueries(2): self.assertEqual(qs[0].active_translation_q.title, "title") qs = qs.select_related("active_translation_q") with self.assertNumQueries(1): self.assertEqual(qs[0].active_translation_q.title, "title") class TestCachedPathInfo(TestCase): def test_equality(self): """ The path_infos and reverse_path_infos attributes are equivalent to calling the get_<method>() with no arguments. """ foreign_object = Membership._meta.get_field("person") self.assertEqual( foreign_object.path_infos, foreign_object.get_path_info(), ) self.assertEqual( foreign_object.reverse_path_infos, foreign_object.get_reverse_path_info(), ) def test_copy_removes_direct_cached_values(self): """ Shallow copying a ForeignObject (or a ForeignObjectRel) removes the object's direct cached PathInfo values. """ foreign_object = Membership._meta.get_field("person") # Trigger storage of cached_property into ForeignObject's __dict__. foreign_object.path_infos foreign_object.reverse_path_infos # The ForeignObjectRel doesn't have reverse_path_infos. foreign_object.remote_field.path_infos self.assertIn("path_infos", foreign_object.__dict__) self.assertIn("reverse_path_infos", foreign_object.__dict__) self.assertIn("path_infos", foreign_object.remote_field.__dict__) # Cached value is removed via __getstate__() on ForeignObjectRel # because no __copy__() method exists, so __reduce_ex__() is used. remote_field_copy = copy.copy(foreign_object.remote_field) self.assertNotIn("path_infos", remote_field_copy.__dict__) # Cached values are removed via __copy__() on ForeignObject for # consistency of behavior. foreign_object_copy = copy.copy(foreign_object) self.assertNotIn("path_infos", foreign_object_copy.__dict__) self.assertNotIn("reverse_path_infos", foreign_object_copy.__dict__) # ForeignObjectRel's remains because it's part of a shallow copy. self.assertIn("path_infos", foreign_object_copy.remote_field.__dict__) def test_deepcopy_removes_cached_values(self): """ Deep copying a ForeignObject removes the object's cached PathInfo values, including those of the related ForeignObjectRel. """ foreign_object = Membership._meta.get_field("person") # Trigger storage of cached_property into ForeignObject's __dict__. foreign_object.path_infos foreign_object.reverse_path_infos # The ForeignObjectRel doesn't have reverse_path_infos. foreign_object.remote_field.path_infos self.assertIn("path_infos", foreign_object.__dict__) self.assertIn("reverse_path_infos", foreign_object.__dict__) self.assertIn("path_infos", foreign_object.remote_field.__dict__) # Cached value is removed via __getstate__() on ForeignObjectRel # because no __deepcopy__() method exists, so __reduce_ex__() is used. remote_field_copy = copy.deepcopy(foreign_object.remote_field) self.assertNotIn("path_infos", remote_field_copy.__dict__) # Field.__deepcopy__() internally uses __copy__() on both the # ForeignObject and ForeignObjectRel, so all cached values are removed. foreign_object_copy = copy.deepcopy(foreign_object) self.assertNotIn("path_infos", foreign_object_copy.__dict__) self.assertNotIn("reverse_path_infos", foreign_object_copy.__dict__) self.assertNotIn("path_infos", foreign_object_copy.remote_field.__dict__) def test_pickling_foreignobjectrel(self): """ Pickling a ForeignObjectRel removes the path_infos attribute. ForeignObjectRel implements __getstate__(), so copy and pickle modules both use that, but ForeignObject implements __reduce__() and __copy__() separately, so doesn't share the same behavior. """ foreign_object_rel = Membership._meta.get_field("person").remote_field # Trigger storage of cached_property into ForeignObjectRel's __dict__. foreign_object_rel.path_infos self.assertIn("path_infos", foreign_object_rel.__dict__) foreign_object_rel_restored = pickle.loads(pickle.dumps(foreign_object_rel)) self.assertNotIn("path_infos", foreign_object_rel_restored.__dict__) def test_pickling_foreignobject(self): """ Pickling a ForeignObject does not remove the cached PathInfo values. ForeignObject will always keep the path_infos and reverse_path_infos attributes within the same process, because of the way Field.__reduce__() is used for restoring values. """ foreign_object = Membership._meta.get_field("person") # Trigger storage of cached_property into ForeignObjectRel's __dict__ foreign_object.path_infos foreign_object.reverse_path_infos self.assertIn("path_infos", foreign_object.__dict__) self.assertIn("reverse_path_infos", foreign_object.__dict__) foreign_object_restored = pickle.loads(pickle.dumps(foreign_object)) self.assertIn("path_infos", foreign_object_restored.__dict__) self.assertIn("reverse_path_infos", foreign_object_restored.__dict__) class ForeignObjectModelValidationTests(TestCase): @skipUnlessDBFeature("supports_table_check_constraints") def test_validate_constraints_with_foreign_object(self): customer_tab = CustomerTab(customer_id=1500) with self.assertRaisesMessage(ValidationError, "customer_id_limit"): customer_tab.validate_constraints() @skipUnlessDBFeature("supports_table_check_constraints") def test_validate_constraints_success_case_single_query(self): customer_tab = CustomerTab(customer_id=500) with CaptureQueriesContext(connection) as ctx: customer_tab.validate_constraints() select_queries = [ query["sql"] for query in ctx.captured_queries if "select" in query["sql"].lower() ] self.assertEqual(len(select_queries), 1) @skipUnlessDBFeature("supports_table_check_constraints") def test_validate_constraints_excluding_foreign_object(self): customer_tab = CustomerTab(customer_id=150) customer_tab.validate_constraints(exclude={"customer"}) @skipUnlessDBFeature("supports_table_check_constraints") def test_validate_constraints_excluding_foreign_object_member(self): customer_tab = CustomerTab(customer_id=150) customer_tab.validate_constraints(exclude={"customer_id"})
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/foreign_object/test_empty_join.py
tests/foreign_object/test_empty_join.py
from django.test import TestCase from .models import SlugPage class RestrictedConditionsTests(TestCase): @classmethod def setUpTestData(cls): slugs = [ "a", "a/a", "a/b", "a/b/a", "x", "x/y/z", ] SlugPage.objects.bulk_create([SlugPage(slug=slug) for slug in slugs]) def test_restrictions_with_no_joining_columns(self): """ It's possible to create a working related field that doesn't use any joining columns, as long as an extra restriction is supplied. """ a = SlugPage.objects.get(slug="a") self.assertEqual( [p.slug for p in SlugPage.objects.filter(ascendants=a)], ["a", "a/a", "a/b", "a/b/a"], ) self.assertEqual( [p.slug for p in a.descendants.all()], ["a", "a/a", "a/b", "a/b/a"], ) aba = SlugPage.objects.get(slug="a/b/a") self.assertEqual( [p.slug for p in SlugPage.objects.filter(descendants__in=[aba])], ["a", "a/b", "a/b/a"], ) self.assertEqual( [p.slug for p in aba.ascendants.all()], ["a", "a/b", "a/b/a"], ) def test_empty_join_conditions(self): x = SlugPage.objects.get(slug="x") message = "Join generated an empty ON clause." with self.assertRaisesMessage(ValueError, message): list(SlugPage.objects.filter(containers=x))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/foreign_object/models/article.py
tests/foreign_object/models/article.py
from django.db import models from django.db.models.fields.related import ForwardManyToOneDescriptor from django.utils.translation import get_language class ArticleTranslationDescriptor(ForwardManyToOneDescriptor): """ The set of articletranslation should not set any local fields. """ def __set__(self, instance, value): if instance is None: raise AttributeError("%s must be accessed via instance" % self.field.name) self.field.set_cached_value(instance, value) if value is not None and not self.field.remote_field.multiple: self.field.remote_field.set_cached_value(value, instance) class ColConstraint: # Anything with as_sql() method works in get_extra_restriction(). def __init__(self, alias, col, value): self.alias, self.col, self.value = alias, col, value def as_sql(self, compiler, connection): qn = compiler.quote_name_unless_alias return "%s.%s = %%s" % (qn(self.alias), qn(self.col)), [self.value] class ActiveTranslationField(models.ForeignObject): """ This field will allow querying and fetching the currently active translation for Article from ArticleTranslation. """ requires_unique_target = False def get_extra_restriction(self, alias, related_alias): return ColConstraint(alias, "lang", get_language()) def get_extra_descriptor_filter(self, instance): return {"lang": get_language()} def contribute_to_class(self, cls, name): super().contribute_to_class(cls, name) setattr(cls, self.name, ArticleTranslationDescriptor(self)) class ActiveTranslationFieldWithQ(ActiveTranslationField): def get_extra_descriptor_filter(self, instance): return models.Q(lang=get_language()) class Article(models.Model): active_translation = ActiveTranslationField( "ArticleTranslation", from_fields=["id"], to_fields=["article"], related_name="+", on_delete=models.CASCADE, null=True, ) active_translation_q = ActiveTranslationFieldWithQ( "ArticleTranslation", from_fields=["id"], to_fields=["article"], related_name="+", on_delete=models.CASCADE, null=True, ) pub_date = models.DateField() def __str__(self): try: return self.active_translation.title except ArticleTranslation.DoesNotExist: return "[No translation found]" class NewsArticle(Article): pass class ArticleTranslation(models.Model): article = models.ForeignKey(Article, models.CASCADE) lang = models.CharField(max_length=2) title = models.CharField(max_length=100) body = models.TextField() abstract = models.TextField(null=True) class Meta: unique_together = ("article", "lang") class ArticleTag(models.Model): article = models.ForeignKey( Article, models.CASCADE, related_name="tags", related_query_name="tag", ) name = models.CharField(max_length=255) class ArticleIdea(models.Model): articles = models.ManyToManyField( Article, related_name="ideas", related_query_name="idea_things", ) name = models.CharField(max_length=255)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/foreign_object/models/empty_join.py
tests/foreign_object/models/empty_join.py
from django.db import models from django.db.models.fields.related import ReverseManyToOneDescriptor from django.db.models.lookups import StartsWith from django.db.models.query_utils import PathInfo class CustomForeignObjectRel(models.ForeignObjectRel): """ Define some extra Field methods so this Rel acts more like a Field, which lets us use ReverseManyToOneDescriptor in both directions. """ @property def foreign_related_fields(self): return tuple(lhs_field for lhs_field, rhs_field in self.field.related_fields) def get_attname(self): return self.name class StartsWithRelation(models.ForeignObject): """ A ForeignObject that uses StartsWith operator in its joins instead of the default equality operator. This is logically a many-to-many relation and creates a ReverseManyToOneDescriptor in both directions. """ auto_created = False many_to_many = False many_to_one = True one_to_many = False one_to_one = False rel_class = CustomForeignObjectRel def __init__(self, *args, **kwargs): kwargs["on_delete"] = models.DO_NOTHING super().__init__(*args, **kwargs) @property def field(self): """ Makes ReverseManyToOneDescriptor work in both directions. """ return self.remote_field def get_extra_restriction(self, alias, related_alias): to_field = self.remote_field.model._meta.get_field(self.to_fields[0]) from_field = self.model._meta.get_field(self.from_fields[0]) return StartsWith(to_field.get_col(alias), from_field.get_col(related_alias)) def get_joining_fields(self, reverse_join=False): return () def get_path_info(self, filtered_relation=None): to_opts = self.remote_field.model._meta from_opts = self.model._meta return [ PathInfo( from_opts=from_opts, to_opts=to_opts, target_fields=(to_opts.pk,), join_field=self, m2m=False, direct=False, filtered_relation=filtered_relation, ) ] def get_reverse_path_info(self, filtered_relation=None): to_opts = self.model._meta from_opts = self.remote_field.model._meta return [ PathInfo( from_opts=from_opts, to_opts=to_opts, target_fields=(to_opts.pk,), join_field=self.remote_field, m2m=False, direct=False, filtered_relation=filtered_relation, ) ] def contribute_to_class(self, cls, name, private_only=False): super().contribute_to_class(cls, name, private_only) setattr(cls, self.name, ReverseManyToOneDescriptor(self)) class BrokenContainsRelation(StartsWithRelation): """ This model is designed to yield no join conditions and raise an exception in ``Join.as_sql()``. """ def get_extra_restriction(self, alias, related_alias): return None class SlugPage(models.Model): slug = models.CharField(max_length=20, unique=True) descendants = StartsWithRelation( "self", from_fields=["slug"], to_fields=["slug"], related_name="ascendants", ) containers = BrokenContainsRelation( "self", from_fields=["slug"], to_fields=["slug"], ) class Meta: ordering = ["slug"] def __str__(self): return "SlugPage %s" % self.slug
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/foreign_object/models/customers.py
tests/foreign_object/models/customers.py
from django.db import models class Address(models.Model): company = models.CharField(max_length=1) customer_id = models.IntegerField() class Meta: unique_together = [ ("company", "customer_id"), ] class Customer(models.Model): company = models.CharField(max_length=1) customer_id = models.IntegerField() address = models.ForeignObject( Address, models.CASCADE, null=True, # order mismatches the Contact ForeignObject. from_fields=["company", "customer_id"], to_fields=["company", "customer_id"], ) class Meta: unique_together = [ ("company", "customer_id"), ] class Contact(models.Model): company_code = models.CharField(max_length=1) customer_code = models.IntegerField() customer = models.ForeignObject( Customer, models.CASCADE, related_name="contacts", to_fields=["customer_id", "company"], from_fields=["customer_code", "company_code"], ) class CustomerTab(models.Model): customer_id = models.IntegerField() customer = models.ForeignObject( Customer, from_fields=["customer_id"], to_fields=["id"], on_delete=models.CASCADE, ) class Meta: required_db_features = {"supports_table_check_constraints"} constraints = [ models.CheckConstraint( condition=models.Q(customer__lt=1000), name="customer_id_limit", ), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/foreign_object/models/__init__.py
tests/foreign_object/models/__init__.py
from .article import Article, ArticleIdea, ArticleTag, ArticleTranslation, NewsArticle from .customers import Address, Contact, Customer, CustomerTab from .empty_join import SlugPage from .person import Country, Friendship, Group, Membership, Person __all__ = [ "Address", "Article", "ArticleIdea", "ArticleTag", "ArticleTranslation", "Contact", "Country", "Customer", "CustomerTab", "Friendship", "Group", "Membership", "NewsArticle", "Person", "SlugPage", ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/foreign_object/models/person.py
tests/foreign_object/models/person.py
import datetime from django.db import models class Country(models.Model): # Table Column Fields name = models.CharField(max_length=50) def __str__(self): return self.name class Person(models.Model): # Table Column Fields name = models.CharField(max_length=128) person_country_id = models.IntegerField() # Relation Fields person_country = models.ForeignObject( Country, from_fields=["person_country_id"], to_fields=["id"], on_delete=models.CASCADE, ) friends = models.ManyToManyField("self", through="Friendship", symmetrical=False) class Meta: ordering = ("name",) def __str__(self): return self.name class Group(models.Model): # Table Column Fields name = models.CharField(max_length=128) group_country = models.ForeignKey(Country, models.CASCADE) members = models.ManyToManyField( Person, related_name="groups", through="Membership" ) class Meta: ordering = ("name",) def __str__(self): return self.name class Membership(models.Model): # Table Column Fields membership_country = models.ForeignKey(Country, models.CASCADE, null=True) date_joined = models.DateTimeField(default=datetime.datetime.now) invite_reason = models.CharField(max_length=64, null=True) person_id = models.IntegerField() group_id = models.IntegerField(blank=True, null=True) # Relation Fields person = models.ForeignObject( Person, from_fields=["person_id", "membership_country"], to_fields=["id", "person_country_id"], on_delete=models.CASCADE, ) group = models.ForeignObject( Group, from_fields=["group_id", "membership_country"], to_fields=["id", "group_country"], on_delete=models.CASCADE, ) class Meta: ordering = ("date_joined", "invite_reason") def __str__(self): group_name = self.group.name if self.group_id else "NULL" return "%s is a member of %s" % (self.person.name, group_name) class Friendship(models.Model): # Table Column Fields from_friend_country = models.ForeignKey( Country, models.CASCADE, related_name="from_friend_country" ) from_friend_id = models.IntegerField() to_friend_country_id = models.IntegerField() to_friend_id = models.IntegerField(null=True) # Relation Fields from_friend = models.ForeignObject( Person, on_delete=models.CASCADE, from_fields=["from_friend_country", "from_friend_id"], to_fields=["person_country_id", "id"], related_name="from_friend", ) to_friend_country = models.ForeignObject( Country, from_fields=["to_friend_country_id"], to_fields=["id"], related_name="to_friend_country", on_delete=models.CASCADE, ) to_friend = models.ForeignObject( Person, from_fields=["to_friend_country_id", "to_friend_id"], to_fields=["person_country_id", "id"], related_name="to_friend+", on_delete=models.CASCADE, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/constraints/models.py
tests/constraints/models.py
from django.db import models from django.db.models.functions import Coalesce, Lower class Product(models.Model): price = models.IntegerField(null=True) discounted_price = models.IntegerField(null=True) unit = models.CharField(max_length=15, null=True) class Meta: required_db_features = { "supports_table_check_constraints", } constraints = [ models.CheckConstraint( condition=models.Q(price__gt=models.F("discounted_price")), name="price_gt_discounted_price", ), models.CheckConstraint( condition=models.Q(price__gt=0), name="%(app_label)s_%(class)s_price_gt_0", ), models.CheckConstraint( condition=models.Q( models.Q(unit__isnull=True) | models.Q(unit__in=["μg/mL", "ng/mL"]) ), name="unicode_unit_list", ), ] class GeneratedFieldStoredProduct(models.Model): name = models.CharField(max_length=255, null=True) price = models.IntegerField(null=True) discounted_price = models.IntegerField(null=True) rebate = models.GeneratedField( expression=Coalesce("price", 0) - Coalesce("discounted_price", Coalesce("price", 0)), output_field=models.IntegerField(), db_persist=True, ) lower_name = models.GeneratedField( expression=Lower(models.F("name")), output_field=models.CharField(max_length=255, null=True), db_persist=True, ) class Meta: required_db_features = {"supports_stored_generated_columns"} class GeneratedFieldVirtualProduct(models.Model): name = models.CharField(max_length=255, null=True) price = models.IntegerField(null=True) discounted_price = models.IntegerField(null=True) rebate = models.GeneratedField( expression=Coalesce("price", 0) - Coalesce("discounted_price", Coalesce("price", 0)), output_field=models.IntegerField(), db_persist=False, ) lower_name = models.GeneratedField( expression=Lower(models.F("name")), output_field=models.CharField(max_length=255, null=True), db_persist=False, ) class Meta: required_db_features = {"supports_virtual_generated_columns"} class UniqueConstraintProduct(models.Model): name = models.CharField(max_length=255) color = models.CharField(max_length=32, null=True) age = models.IntegerField(null=True) updated = models.DateTimeField(null=True) class Meta: constraints = [ models.UniqueConstraint( fields=["name", "color"], name="name_color_uniq", ) ] class ChildUniqueConstraintProduct(UniqueConstraintProduct): pass class UniqueConstraintConditionProduct(models.Model): name = models.CharField(max_length=255) color = models.CharField(max_length=32, null=True) class Meta: required_db_features = {"supports_partial_indexes"} constraints = [ models.UniqueConstraint( fields=["name"], name="name_without_color_uniq", condition=models.Q(color__isnull=True), ), ] class UniqueConstraintDeferrable(models.Model): name = models.CharField(max_length=255) shelf = models.CharField(max_length=31) class Meta: required_db_features = { "supports_deferrable_unique_constraints", } constraints = [ models.UniqueConstraint( fields=["name"], name="name_init_deferred_uniq", deferrable=models.Deferrable.DEFERRED, ), models.UniqueConstraint( fields=["shelf"], name="sheld_init_immediate_uniq", deferrable=models.Deferrable.IMMEDIATE, ), ] class UniqueConstraintInclude(models.Model): name = models.CharField(max_length=255) color = models.CharField(max_length=32, null=True) class Meta: required_db_features = { "supports_table_check_constraints", "supports_covering_indexes", } constraints = [ models.UniqueConstraint( fields=["name"], name="name_include_color_uniq", include=["color"], ), ] class AbstractModel(models.Model): age = models.IntegerField() class Meta: abstract = True required_db_features = { "supports_table_check_constraints", } constraints = [ models.CheckConstraint( condition=models.Q(age__gte=18), name="%(app_label)s_%(class)s_adult", ), ] class ChildModel(AbstractModel): pass class JSONFieldModel(models.Model): data = models.JSONField(null=True) class Meta: required_db_features = {"supports_json_field"} class ModelWithDatabaseDefault(models.Model): field = models.CharField(max_length=255) field_with_db_default = models.CharField( max_length=255, db_default=models.Value("field_with_db_default") )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/constraints/__init__.py
tests/constraints/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/constraints/tests.py
tests/constraints/tests.py
from datetime import datetime, timedelta from unittest import mock from django.core.exceptions import ValidationError from django.db import IntegrityError, connection, models from django.db.models import Case, F, When from django.db.models.constraints import BaseConstraint, UniqueConstraint from django.db.models.functions import Abs, Lower, Sqrt, Upper from django.db.transaction import atomic from django.test import SimpleTestCase, TestCase, skipIfDBFeature, skipUnlessDBFeature from .models import ( ChildModel, ChildUniqueConstraintProduct, GeneratedFieldStoredProduct, GeneratedFieldVirtualProduct, JSONFieldModel, ModelWithDatabaseDefault, Product, UniqueConstraintConditionProduct, UniqueConstraintDeferrable, UniqueConstraintInclude, UniqueConstraintProduct, ) def get_constraints(table): with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) class BaseConstraintTests(SimpleTestCase): def test_constraint_sql(self): c = BaseConstraint(name="name") msg = "This method must be implemented by a subclass." with self.assertRaisesMessage(NotImplementedError, msg): c.constraint_sql(None, None) def test_contains_expressions(self): c = BaseConstraint(name="name") self.assertIs(c.contains_expressions, False) def test_create_sql(self): c = BaseConstraint(name="name") msg = "This method must be implemented by a subclass." with self.assertRaisesMessage(NotImplementedError, msg): c.create_sql(None, None) def test_remove_sql(self): c = BaseConstraint(name="name") msg = "This method must be implemented by a subclass." with self.assertRaisesMessage(NotImplementedError, msg): c.remove_sql(None, None) def test_validate(self): c = BaseConstraint(name="name") msg = "This method must be implemented by a subclass." with self.assertRaisesMessage(NotImplementedError, msg): c.validate(None, None) def test_default_violation_error_message(self): c = BaseConstraint(name="name") self.assertEqual( c.get_violation_error_message(), "Constraint “name” is violated." ) def test_custom_violation_error_message(self): c = BaseConstraint( name="base_name", violation_error_message="custom %(name)s message" ) self.assertEqual(c.get_violation_error_message(), "custom base_name message") def test_custom_violation_error_message_clone(self): constraint = BaseConstraint( name="base_name", violation_error_message="custom %(name)s message", ).clone() self.assertEqual( constraint.get_violation_error_message(), "custom base_name message", ) def test_custom_violation_code_message(self): c = BaseConstraint(name="base_name", violation_error_code="custom_code") self.assertEqual(c.violation_error_code, "custom_code") def test_deconstruction(self): constraint = BaseConstraint( name="base_name", violation_error_message="custom %(name)s message", violation_error_code="custom_code", ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, "django.db.models.BaseConstraint") self.assertEqual(args, ()) self.assertEqual( kwargs, { "name": "base_name", "violation_error_message": "custom %(name)s message", "violation_error_code": "custom_code", }, ) def test_name_required(self): msg = ( "BaseConstraint.__init__() missing 1 required keyword-only argument: 'name'" ) with self.assertRaisesMessage(TypeError, msg): BaseConstraint() class CheckConstraintTests(TestCase): def test_eq(self): check1 = models.Q(price__gt=models.F("discounted_price")) check2 = models.Q(price__lt=models.F("discounted_price")) self.assertEqual( models.CheckConstraint(condition=check1, name="price"), models.CheckConstraint(condition=check1, name="price"), ) self.assertEqual( models.CheckConstraint(condition=check1, name="price"), mock.ANY ) self.assertNotEqual( models.CheckConstraint(condition=check1, name="price"), models.CheckConstraint(condition=check1, name="price2"), ) self.assertNotEqual( models.CheckConstraint(condition=check1, name="price"), models.CheckConstraint(condition=check2, name="price"), ) self.assertNotEqual(models.CheckConstraint(condition=check1, name="price"), 1) self.assertNotEqual( models.CheckConstraint(condition=check1, name="price"), models.CheckConstraint( condition=check1, name="price", violation_error_message="custom error" ), ) self.assertNotEqual( models.CheckConstraint( condition=check1, name="price", violation_error_message="custom error" ), models.CheckConstraint( condition=check1, name="price", violation_error_message="other custom error", ), ) self.assertEqual( models.CheckConstraint( condition=check1, name="price", violation_error_message="custom error" ), models.CheckConstraint( condition=check1, name="price", violation_error_message="custom error" ), ) self.assertNotEqual( models.CheckConstraint(condition=check1, name="price"), models.CheckConstraint( condition=check1, name="price", violation_error_code="custom_code" ), ) self.assertEqual( models.CheckConstraint( condition=check1, name="price", violation_error_code="custom_code" ), models.CheckConstraint( condition=check1, name="price", violation_error_code="custom_code" ), ) def test_repr(self): constraint = models.CheckConstraint( condition=models.Q(price__gt=models.F("discounted_price")), name="price_gt_discounted_price", ) self.assertEqual( repr(constraint), "<CheckConstraint: condition=(AND: ('price__gt', F(discounted_price))) " "name='price_gt_discounted_price'>", ) def test_repr_with_violation_error_message(self): constraint = models.CheckConstraint( condition=models.Q(price__lt=1), name="price_lt_one", violation_error_message="More than 1", ) self.assertEqual( repr(constraint), "<CheckConstraint: condition=(AND: ('price__lt', 1)) name='price_lt_one' " "violation_error_message='More than 1'>", ) def test_repr_with_violation_error_code(self): constraint = models.CheckConstraint( condition=models.Q(price__lt=1), name="price_lt_one", violation_error_code="more_than_one", ) self.assertEqual( repr(constraint), "<CheckConstraint: condition=(AND: ('price__lt', 1)) name='price_lt_one' " "violation_error_code='more_than_one'>", ) def test_invalid_check_types(self): msg = "CheckConstraint.condition must be a Q instance or boolean expression." with self.assertRaisesMessage(TypeError, msg): models.CheckConstraint(condition=models.F("discounted_price"), name="check") def test_deconstruction(self): check = models.Q(price__gt=models.F("discounted_price")) name = "price_gt_discounted_price" constraint = models.CheckConstraint(condition=check, name=name) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, "django.db.models.CheckConstraint") self.assertEqual(args, ()) self.assertEqual(kwargs, {"condition": check, "name": name}) @skipUnlessDBFeature("supports_table_check_constraints") def test_database_constraint(self): Product.objects.create(price=10, discounted_price=5) with self.assertRaises(IntegrityError): Product.objects.create(price=10, discounted_price=20) @skipUnlessDBFeature("supports_table_check_constraints") def test_database_constraint_unicode(self): Product.objects.create(price=10, discounted_price=5, unit="μg/mL") with self.assertRaises(IntegrityError): Product.objects.create(price=10, discounted_price=7, unit="l") @skipUnlessDBFeature( "supports_table_check_constraints", "can_introspect_check_constraints" ) def test_name(self): constraints = get_constraints(Product._meta.db_table) for expected_name in ( "price_gt_discounted_price", "constraints_product_price_gt_0", ): with self.subTest(expected_name): self.assertIn(expected_name, constraints) @skipUnlessDBFeature( "supports_table_check_constraints", "can_introspect_check_constraints" ) def test_abstract_name(self): constraints = get_constraints(ChildModel._meta.db_table) self.assertIn("constraints_childmodel_adult", constraints) def test_validate(self): check = models.Q(price__gt=models.F("discounted_price")) constraint = models.CheckConstraint(condition=check, name="price") # Invalid product. invalid_product = Product(price=10, discounted_price=42) with self.assertRaises(ValidationError): constraint.validate(Product, invalid_product) with self.assertRaises(ValidationError): constraint.validate(Product, invalid_product, exclude={"unit"}) # Fields used by the check constraint are excluded. constraint.validate(Product, invalid_product, exclude={"price"}) constraint.validate(Product, invalid_product, exclude={"discounted_price"}) constraint.validate( Product, invalid_product, exclude={"discounted_price", "price"}, ) # Valid product. constraint.validate(Product, Product(price=10, discounted_price=5)) def test_validate_custom_error(self): check = models.Q(price__gt=models.F("discounted_price")) constraint = models.CheckConstraint( condition=check, name="price", violation_error_message="discount is fake", violation_error_code="fake_discount", ) # Invalid product. invalid_product = Product(price=10, discounted_price=42) msg = "discount is fake" with self.assertRaisesMessage(ValidationError, msg) as cm: constraint.validate(Product, invalid_product) self.assertEqual(cm.exception.code, "fake_discount") def test_validate_boolean_expressions(self): constraint = models.CheckConstraint( condition=models.expressions.ExpressionWrapper( models.Q(price__gt=500) | models.Q(price__lt=500), output_field=models.BooleanField(), ), name="price_neq_500_wrap", ) msg = f"Constraint “{constraint.name}” is violated." with self.assertRaisesMessage(ValidationError, msg): constraint.validate(Product, Product(price=500, discounted_price=5)) constraint.validate(Product, Product(price=501, discounted_price=5)) constraint.validate(Product, Product(price=499, discounted_price=5)) def test_validate_rawsql_expressions_noop(self): constraint = models.CheckConstraint( condition=models.expressions.RawSQL( "price < %s OR price > %s", (500, 500), output_field=models.BooleanField(), ), name="price_neq_500_raw", ) # RawSQL can not be checked and is always considered valid. constraint.validate(Product, Product(price=500, discounted_price=5)) constraint.validate(Product, Product(price=501, discounted_price=5)) constraint.validate(Product, Product(price=499, discounted_price=5)) @skipUnlessDBFeature("supports_comparing_boolean_expr") def test_validate_nullable_field_with_none(self): # Nullable fields should be considered valid on None values. constraint = models.CheckConstraint( condition=models.Q(price__gte=0), name="positive_price", ) constraint.validate(Product, Product()) @skipIfDBFeature("supports_comparing_boolean_expr") def test_validate_nullable_field_with_isnull(self): constraint = models.CheckConstraint( condition=models.Q(price__gte=0) | models.Q(price__isnull=True), name="positive_price", ) constraint.validate(Product, Product()) @skipUnlessDBFeature("supports_json_field") def test_validate_nullable_jsonfield(self): is_null_constraint = models.CheckConstraint( condition=models.Q(data__isnull=True), name="nullable_data", ) is_not_null_constraint = models.CheckConstraint( condition=models.Q(data__isnull=False), name="nullable_data", ) is_null_constraint.validate(JSONFieldModel, JSONFieldModel(data=None)) msg = f"Constraint “{is_null_constraint.name}” is violated." with self.assertRaisesMessage(ValidationError, msg): is_null_constraint.validate(JSONFieldModel, JSONFieldModel(data={})) msg = f"Constraint “{is_not_null_constraint.name}” is violated." with self.assertRaisesMessage(ValidationError, msg): is_not_null_constraint.validate(JSONFieldModel, JSONFieldModel(data=None)) is_not_null_constraint.validate(JSONFieldModel, JSONFieldModel(data={})) def test_validate_pk_field(self): constraint_with_pk = models.CheckConstraint( condition=~models.Q(pk=models.F("age")), name="pk_not_age_check", ) constraint_with_pk.validate(ChildModel, ChildModel(pk=1, age=2)) msg = f"Constraint “{constraint_with_pk.name}” is violated." with self.assertRaisesMessage(ValidationError, msg): constraint_with_pk.validate(ChildModel, ChildModel(pk=1, age=1)) with self.assertRaisesMessage(ValidationError, msg): constraint_with_pk.validate(ChildModel, ChildModel(id=1, age=1)) constraint_with_pk.validate(ChildModel, ChildModel(pk=1, age=1), exclude={"pk"}) def test_validate_fk_attname(self): constraint_with_fk = models.CheckConstraint( condition=models.Q(uniqueconstraintproduct_ptr_id__isnull=False), name="parent_ptr_present", ) with self.assertRaisesMessage( ValidationError, "Constraint “parent_ptr_present” is violated." ): constraint_with_fk.validate( ChildUniqueConstraintProduct, ChildUniqueConstraintProduct() ) constraint_with_fk.validate( ChildUniqueConstraintProduct, ChildUniqueConstraintProduct(uniqueconstraintproduct_ptr_id=1), ) @skipUnlessDBFeature("supports_json_field") def test_validate_jsonfield_exact(self): data = {"release": "5.0.2", "version": "stable"} json_exact_constraint = models.CheckConstraint( condition=models.Q(data__version="stable"), name="only_stable_version", ) json_exact_constraint.validate(JSONFieldModel, JSONFieldModel(data=data)) data = {"release": "5.0.2", "version": "not stable"} msg = f"Constraint “{json_exact_constraint.name}” is violated." with self.assertRaisesMessage(ValidationError, msg): json_exact_constraint.validate(JSONFieldModel, JSONFieldModel(data=data)) @skipUnlessDBFeature("supports_stored_generated_columns") def test_validate_generated_field_stored(self): self.assertGeneratedFieldIsValidated(model=GeneratedFieldStoredProduct) @skipUnlessDBFeature("supports_virtual_generated_columns") def test_validate_generated_field_virtual(self): self.assertGeneratedFieldIsValidated(model=GeneratedFieldVirtualProduct) def assertGeneratedFieldIsValidated(self, model): constraint = models.CheckConstraint( condition=models.Q(rebate__range=(0, 100)), name="bounded_rebate" ) constraint.validate(model, model(price=50, discounted_price=20)) invalid_product = model(price=1200, discounted_price=500) msg = f"Constraint “{constraint.name}” is violated." with self.assertRaisesMessage(ValidationError, msg): constraint.validate(model, invalid_product) # Excluding referenced or generated fields should skip validation. constraint.validate(model, invalid_product, exclude={"price"}) constraint.validate(model, invalid_product, exclude={"rebate"}) def test_database_default(self): models.CheckConstraint( condition=models.Q(field_with_db_default="field_with_db_default"), name="check_field_with_db_default", ).validate(ModelWithDatabaseDefault, ModelWithDatabaseDefault()) # Ensure that a check also does not silently pass with either # FieldError or DatabaseError when checking with a db_default. with self.assertRaises(ValidationError): models.CheckConstraint( condition=models.Q( field_with_db_default="field_with_db_default", field="field" ), name="check_field_with_db_default_2", ).validate( ModelWithDatabaseDefault, ModelWithDatabaseDefault(field="not-field") ) with self.assertRaises(ValidationError): models.CheckConstraint( condition=models.Q(field_with_db_default="field_with_db_default"), name="check_field_with_db_default", ).validate( ModelWithDatabaseDefault, ModelWithDatabaseDefault(field_with_db_default="other value"), ) class UniqueConstraintTests(TestCase): @classmethod def setUpTestData(cls): cls.p1 = UniqueConstraintProduct.objects.create(name="p1", color="red") cls.p2 = UniqueConstraintProduct.objects.create(name="p2") def test_eq(self): self.assertEqual( models.UniqueConstraint(fields=["foo", "bar"], name="unique"), models.UniqueConstraint(fields=["foo", "bar"], name="unique"), ) self.assertEqual( models.UniqueConstraint(fields=["foo", "bar"], name="unique"), mock.ANY, ) self.assertNotEqual( models.UniqueConstraint(fields=["foo", "bar"], name="unique"), models.UniqueConstraint(fields=["foo", "bar"], name="unique2"), ) self.assertNotEqual( models.UniqueConstraint(fields=["foo", "bar"], name="unique"), models.UniqueConstraint(fields=["foo", "baz"], name="unique"), ) self.assertNotEqual( models.UniqueConstraint(fields=["foo", "bar"], name="unique"), 1 ) self.assertNotEqual( models.UniqueConstraint(fields=["foo", "bar"], name="unique"), models.UniqueConstraint( fields=["foo", "bar"], name="unique", violation_error_message="custom error", ), ) self.assertNotEqual( models.UniqueConstraint( fields=["foo", "bar"], name="unique", violation_error_message="custom error", ), models.UniqueConstraint( fields=["foo", "bar"], name="unique", violation_error_message="other custom error", ), ) self.assertEqual( models.UniqueConstraint( fields=["foo", "bar"], name="unique", violation_error_message="custom error", ), models.UniqueConstraint( fields=["foo", "bar"], name="unique", violation_error_message="custom error", ), ) self.assertNotEqual( models.UniqueConstraint( fields=["foo", "bar"], name="unique", violation_error_code="custom_error", ), models.UniqueConstraint( fields=["foo", "bar"], name="unique", violation_error_code="other_custom_error", ), ) self.assertEqual( models.UniqueConstraint( fields=["foo", "bar"], name="unique", violation_error_code="custom_error", ), models.UniqueConstraint( fields=["foo", "bar"], name="unique", violation_error_code="custom_error", ), ) def test_eq_with_condition(self): self.assertEqual( models.UniqueConstraint( fields=["foo", "bar"], name="unique", condition=models.Q(foo=models.F("bar")), ), models.UniqueConstraint( fields=["foo", "bar"], name="unique", condition=models.Q(foo=models.F("bar")), ), ) self.assertNotEqual( models.UniqueConstraint( fields=["foo", "bar"], name="unique", condition=models.Q(foo=models.F("bar")), ), models.UniqueConstraint( fields=["foo", "bar"], name="unique", condition=models.Q(foo=models.F("baz")), ), ) def test_eq_with_deferrable(self): constraint_1 = models.UniqueConstraint( fields=["foo", "bar"], name="unique", deferrable=models.Deferrable.DEFERRED, ) constraint_2 = models.UniqueConstraint( fields=["foo", "bar"], name="unique", deferrable=models.Deferrable.IMMEDIATE, ) self.assertEqual(constraint_1, constraint_1) self.assertNotEqual(constraint_1, constraint_2) def test_eq_with_include(self): constraint_1 = models.UniqueConstraint( fields=["foo", "bar"], name="include", include=["baz_1"], ) constraint_2 = models.UniqueConstraint( fields=["foo", "bar"], name="include", include=["baz_2"], ) self.assertEqual(constraint_1, constraint_1) self.assertNotEqual(constraint_1, constraint_2) def test_eq_with_opclasses(self): constraint_1 = models.UniqueConstraint( fields=["foo", "bar"], name="opclasses", opclasses=["text_pattern_ops", "varchar_pattern_ops"], ) constraint_2 = models.UniqueConstraint( fields=["foo", "bar"], name="opclasses", opclasses=["varchar_pattern_ops", "text_pattern_ops"], ) self.assertEqual(constraint_1, constraint_1) self.assertNotEqual(constraint_1, constraint_2) def test_eq_with_expressions(self): constraint = models.UniqueConstraint( Lower("title"), F("author"), name="book_func_uq", ) same_constraint = models.UniqueConstraint( Lower("title"), "author", name="book_func_uq", ) another_constraint = models.UniqueConstraint( Lower("title"), name="book_func_uq", ) self.assertEqual(constraint, same_constraint) self.assertEqual(constraint, mock.ANY) self.assertNotEqual(constraint, another_constraint) def test_eq_with_nulls_distinct(self): constraint_1 = models.UniqueConstraint( Lower("title"), nulls_distinct=False, name="book_func_nulls_distinct_uq", ) constraint_2 = models.UniqueConstraint( Lower("title"), nulls_distinct=True, name="book_func_nulls_distinct_uq", ) constraint_3 = models.UniqueConstraint( Lower("title"), name="book_func_nulls_distinct_uq", ) self.assertEqual(constraint_1, constraint_1) self.assertEqual(constraint_1, mock.ANY) self.assertNotEqual(constraint_1, constraint_2) self.assertNotEqual(constraint_1, constraint_3) self.assertNotEqual(constraint_2, constraint_3) def test_repr(self): fields = ["foo", "bar"] name = "unique_fields" constraint = models.UniqueConstraint(fields=fields, name=name) self.assertEqual( repr(constraint), "<UniqueConstraint: fields=('foo', 'bar') name='unique_fields'>", ) def test_repr_with_condition(self): constraint = models.UniqueConstraint( fields=["foo", "bar"], name="unique_fields", condition=models.Q(foo=models.F("bar")), ) self.assertEqual( repr(constraint), "<UniqueConstraint: fields=('foo', 'bar') name='unique_fields' " "condition=(AND: ('foo', F(bar)))>", ) def test_repr_with_deferrable(self): constraint = models.UniqueConstraint( fields=["foo", "bar"], name="unique_fields", deferrable=models.Deferrable.IMMEDIATE, ) self.assertEqual( repr(constraint), "<UniqueConstraint: fields=('foo', 'bar') name='unique_fields' " "deferrable=Deferrable.IMMEDIATE>", ) def test_repr_with_include(self): constraint = models.UniqueConstraint( fields=["foo", "bar"], name="include_fields", include=["baz_1", "baz_2"], ) self.assertEqual( repr(constraint), "<UniqueConstraint: fields=('foo', 'bar') name='include_fields' " "include=('baz_1', 'baz_2')>", ) def test_repr_with_opclasses(self): constraint = models.UniqueConstraint( fields=["foo", "bar"], name="opclasses_fields", opclasses=["text_pattern_ops", "varchar_pattern_ops"], ) self.assertEqual( repr(constraint), "<UniqueConstraint: fields=('foo', 'bar') name='opclasses_fields' " "opclasses=['text_pattern_ops', 'varchar_pattern_ops']>", ) def test_repr_with_nulls_distinct(self): constraint = models.UniqueConstraint( fields=["foo", "bar"], name="nulls_distinct_fields", nulls_distinct=False, ) self.assertEqual( repr(constraint), "<UniqueConstraint: fields=('foo', 'bar') name='nulls_distinct_fields' " "nulls_distinct=False>", ) def test_repr_with_expressions(self): constraint = models.UniqueConstraint( Lower("title"), F("author"), name="book_func_uq", ) self.assertEqual( repr(constraint), "<UniqueConstraint: expressions=(Lower(F(title)), F(author)) " "name='book_func_uq'>", ) def test_repr_with_violation_error_message(self): constraint = models.UniqueConstraint( models.F("baz__lower"), name="unique_lower_baz", violation_error_message="BAZ", ) self.assertEqual( repr(constraint), ( "<UniqueConstraint: expressions=(F(baz__lower),) " "name='unique_lower_baz' violation_error_message='BAZ'>" ), ) def test_repr_with_violation_error_code(self): constraint = models.UniqueConstraint( models.F("baz__lower"), name="unique_lower_baz", violation_error_code="baz", ) self.assertEqual( repr(constraint), ( "<UniqueConstraint: expressions=(F(baz__lower),) " "name='unique_lower_baz' violation_error_code='baz'>" ), ) def test_deconstruction(self): fields = ["foo", "bar"] name = "unique_fields" constraint = models.UniqueConstraint(fields=fields, name=name) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, "django.db.models.UniqueConstraint") self.assertEqual(args, ()) self.assertEqual(kwargs, {"fields": tuple(fields), "name": name}) def test_deconstruction_with_condition(self): fields = ["foo", "bar"] name = "unique_fields" condition = models.Q(foo=models.F("bar")) constraint = models.UniqueConstraint( fields=fields, name=name, condition=condition ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, "django.db.models.UniqueConstraint") self.assertEqual(args, ()) self.assertEqual( kwargs, {"fields": tuple(fields), "name": name, "condition": condition} ) def test_deconstruction_with_deferrable(self): fields = ["foo"] name = "unique_fields" constraint = models.UniqueConstraint( fields=fields, name=name, deferrable=models.Deferrable.DEFERRED, ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, "django.db.models.UniqueConstraint") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": tuple(fields), "name": name, "deferrable": models.Deferrable.DEFERRED, }, ) def test_deconstruction_with_include(self): fields = ["foo", "bar"] name = "unique_fields" include = ["baz_1", "baz_2"] constraint = models.UniqueConstraint(fields=fields, name=name, include=include) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, "django.db.models.UniqueConstraint") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": tuple(fields), "name": name, "include": tuple(include), }, ) def test_deconstruction_with_opclasses(self): fields = ["foo", "bar"] name = "unique_fields" opclasses = ["varchar_pattern_ops", "text_pattern_ops"] constraint = models.UniqueConstraint( fields=fields, name=name, opclasses=opclasses ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, "django.db.models.UniqueConstraint") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": tuple(fields), "name": name, "opclasses": opclasses, }, ) def test_deconstruction_with_nulls_distinct(self): fields = ["foo", "bar"] name = "unique_fields" constraint = models.UniqueConstraint( fields=fields, name=name, nulls_distinct=True ) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, "django.db.models.UniqueConstraint") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": tuple(fields), "name": name, "nulls_distinct": True, }, ) def test_deconstruction_with_expressions(self): name = "unique_fields" constraint = models.UniqueConstraint(Lower("title"), name=name) path, args, kwargs = constraint.deconstruct() self.assertEqual(path, "django.db.models.UniqueConstraint") self.assertEqual(args, (Lower("title"),)) self.assertEqual(kwargs, {"name": name}) def test_database_constraint(self): with self.assertRaises(IntegrityError):
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/aggregation_regress/models.py
tests/aggregation_regress/models.py
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() friends = models.ManyToManyField("self", blank=True) class Publisher(models.Model): name = models.CharField(max_length=255) num_awards = models.IntegerField() class ItemTag(models.Model): tag = models.CharField(max_length=100) content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") class Book(models.Model): isbn = models.CharField(max_length=9) name = models.CharField(max_length=255) pages = models.IntegerField() rating = models.FloatField() price = models.DecimalField(decimal_places=2, max_digits=6) authors = models.ManyToManyField(Author) contact = models.ForeignKey(Author, models.CASCADE, related_name="book_contact_set") publisher = models.ForeignKey(Publisher, models.CASCADE) pubdate = models.DateField() tags = GenericRelation(ItemTag) class Meta: ordering = ("name",) class Store(models.Model): name = models.CharField(max_length=255) books = models.ManyToManyField(Book) original_opening = models.DateTimeField() friday_night_closing = models.TimeField() class Entries(models.Model): EntryID = models.AutoField(primary_key=True, db_column="Entry ID") Entry = models.CharField(unique=True, max_length=50) Exclude = models.BooleanField(default=False) class Clues(models.Model): ID = models.AutoField(primary_key=True) EntryID = models.ForeignKey( Entries, models.CASCADE, verbose_name="Entry", db_column="Entry ID" ) Clue = models.CharField(max_length=150) class WithManualPK(models.Model): # The generic relations regression test needs two different model # classes with the same PK value, and there are some (external) # DB backends that don't work nicely when assigning integer to AutoField # column (MSSQL at least). id = models.IntegerField(primary_key=True) class HardbackBook(Book): weight = models.FloatField() # Models for ticket #21150 class Alfa(models.Model): name = models.CharField(max_length=10, null=True) class Bravo(models.Model): pass class Charlie(models.Model): alfa = models.ForeignKey(Alfa, models.SET_NULL, null=True) bravo = models.ForeignKey(Bravo, models.SET_NULL, null=True) class SelfRefFK(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey( "self", models.SET_NULL, null=True, blank=True, related_name="children" ) class AuthorProxy(Author): class Meta: proxy = True class Recipe(models.Model): name = models.CharField(max_length=20) author = models.ForeignKey(AuthorProxy, models.CASCADE) tasters = models.ManyToManyField(AuthorProxy, related_name="recipes") class RecipeProxy(Recipe): class Meta: proxy = True class AuthorUnmanaged(models.Model): age = models.IntegerField() class Meta: db_table = Author._meta.db_table managed = False class RecipeTasterUnmanaged(models.Model): recipe = models.ForeignKey("RecipeUnmanaged", models.CASCADE) author = models.ForeignKey( AuthorUnmanaged, models.CASCADE, db_column="authorproxy_id" ) class Meta: managed = False db_table = Recipe.tasters.through._meta.db_table class RecipeUnmanaged(models.Model): author = models.ForeignKey(AuthorUnmanaged, models.CASCADE) tasters = models.ManyToManyField( AuthorUnmanaged, through=RecipeTasterUnmanaged, related_name="+" ) class Meta: managed = False db_table = Recipe._meta.db_table
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/aggregation_regress/__init__.py
tests/aggregation_regress/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/aggregation_regress/tests.py
tests/aggregation_regress/tests.py
import datetime import pickle from decimal import Decimal from operator import attrgetter from unittest import mock from django.contrib.contenttypes.models import ContentType from django.core.exceptions import FieldError from django.db import connection from django.db.models import ( Aggregate, Avg, Case, CharField, Count, DecimalField, F, IntegerField, Max, Q, StdDev, Sum, Value, Variance, When, ) from django.db.models.functions import Cast, Concat from django.test import TestCase, skipUnlessDBFeature from django.test.utils import Approximate from .models import ( Alfa, Author, AuthorProxy, AuthorUnmanaged, Book, Bravo, Charlie, Clues, Entries, HardbackBook, ItemTag, Publisher, RecipeProxy, RecipeUnmanaged, SelfRefFK, Store, WithManualPK, ) class AggregationTests(TestCase): @classmethod def setUpTestData(cls): cls.a1 = Author.objects.create(name="Adrian Holovaty", age=34) cls.a2 = Author.objects.create(name="Jacob Kaplan-Moss", age=35) cls.a3 = Author.objects.create(name="Brad Dayley", age=45) cls.a4 = Author.objects.create(name="James Bennett", age=29) cls.a5 = Author.objects.create(name="Jeffrey Forcier", age=37) cls.a6 = Author.objects.create(name="Paul Bissex", age=29) cls.a7 = Author.objects.create(name="Wesley J. Chun", age=25) cls.a8 = Author.objects.create(name="Peter Norvig", age=57) cls.a9 = Author.objects.create(name="Stuart Russell", age=46) cls.a1.friends.add(cls.a2, cls.a4) cls.a2.friends.add(cls.a1, cls.a7) cls.a4.friends.add(cls.a1) cls.a5.friends.add(cls.a6, cls.a7) cls.a6.friends.add(cls.a5, cls.a7) cls.a7.friends.add(cls.a2, cls.a5, cls.a6) cls.a8.friends.add(cls.a9) cls.a9.friends.add(cls.a8) cls.p1 = Publisher.objects.create(name="Apress", num_awards=3) cls.p2 = Publisher.objects.create(name="Sams", num_awards=1) cls.p3 = Publisher.objects.create(name="Prentice Hall", num_awards=7) cls.p4 = Publisher.objects.create(name="Morgan Kaufmann", num_awards=9) cls.p5 = Publisher.objects.create(name="Jonno's House of Books", num_awards=0) cls.b1 = Book.objects.create( isbn="159059725", name="The Definitive Guide to Django: Web Development Done Right", pages=447, rating=4.5, price=Decimal("30.00"), contact=cls.a1, publisher=cls.p1, pubdate=datetime.date(2007, 12, 6), ) cls.b2 = Book.objects.create( isbn="067232959", name="Sams Teach Yourself Django in 24 Hours", pages=528, rating=3.0, price=Decimal("23.09"), contact=cls.a3, publisher=cls.p2, pubdate=datetime.date(2008, 3, 3), ) cls.b3 = Book.objects.create( isbn="159059996", name="Practical Django Projects", pages=300, rating=4.0, price=Decimal("29.69"), contact=cls.a4, publisher=cls.p1, pubdate=datetime.date(2008, 6, 23), ) cls.b4 = Book.objects.create( isbn="013235613", name="Python Web Development with Django", pages=350, rating=4.0, price=Decimal("29.69"), contact=cls.a5, publisher=cls.p3, pubdate=datetime.date(2008, 11, 3), ) cls.b5 = HardbackBook.objects.create( isbn="013790395", name="Artificial Intelligence: A Modern Approach", pages=1132, rating=4.0, price=Decimal("82.80"), contact=cls.a8, publisher=cls.p3, pubdate=datetime.date(1995, 1, 15), weight=4.5, ) cls.b6 = HardbackBook.objects.create( isbn="155860191", name=( "Paradigms of Artificial Intelligence Programming: Case Studies in " "Common Lisp" ), pages=946, rating=5.0, price=Decimal("75.00"), contact=cls.a8, publisher=cls.p4, pubdate=datetime.date(1991, 10, 15), weight=3.7, ) cls.b1.authors.add(cls.a1, cls.a2) cls.b2.authors.add(cls.a3) cls.b3.authors.add(cls.a4) cls.b4.authors.add(cls.a5, cls.a6, cls.a7) cls.b5.authors.add(cls.a8, cls.a9) cls.b6.authors.add(cls.a8) s1 = Store.objects.create( name="Amazon.com", original_opening=datetime.datetime(1994, 4, 23, 9, 17, 42), friday_night_closing=datetime.time(23, 59, 59), ) s2 = Store.objects.create( name="Books.com", original_opening=datetime.datetime(2001, 3, 15, 11, 23, 37), friday_night_closing=datetime.time(23, 59, 59), ) s3 = Store.objects.create( name="Mamma and Pappa's Books", original_opening=datetime.datetime(1945, 4, 25, 16, 24, 14), friday_night_closing=datetime.time(21, 30), ) s1.books.add(cls.b1, cls.b2, cls.b3, cls.b4, cls.b5, cls.b6) s2.books.add(cls.b1, cls.b3, cls.b5, cls.b6) s3.books.add(cls.b3, cls.b4, cls.b6) def assertObjectAttrs(self, obj, **kwargs): for attr, value in kwargs.items(): self.assertEqual(getattr(obj, attr), value) def test_count_preserve_group_by(self): # new release of the same book Book.objects.create( isbn="113235613", name=self.b4.name, pages=self.b4.pages, rating=4.0, price=Decimal("39.69"), contact=self.a5, publisher=self.p3, pubdate=datetime.date(2018, 11, 3), ) qs = Book.objects.values("contact__name", "publisher__name").annotate( publications=Count("id") ) self.assertEqual(qs.order_by("id").count(), len(qs.order_by("id"))) self.assertEqual(qs.extra(order_by=["id"]).count(), len(qs.order_by("id"))) def test_annotation_with_value(self): values = ( Book.objects.filter( name="Practical Django Projects", ) .annotate( discount_price=F("price") * 2, ) .values( "discount_price", ) .annotate(sum_discount=Sum("discount_price")) ) with self.assertNumQueries(1) as ctx: self.assertSequenceEqual( values, [ { "discount_price": Decimal("59.38"), "sum_discount": Decimal("59.38"), } ], ) if connection.features.allows_group_by_select_index: self.assertIn("GROUP BY 1", ctx[0]["sql"]) def test_aggregates_in_where_clause(self): """ Regression test for #12822: DatabaseError: aggregates not allowed in WHERE clause The subselect works and returns results equivalent to a query with the IDs listed. Before the corresponding fix for this bug, this test passed in 1.1 and failed in 1.2-beta (trunk). """ qs = Book.objects.values("contact").annotate(Max("id")) qs = qs.order_by("contact").values_list("id__max", flat=True) # don't do anything with the queryset (qs) before including it as a # subquery books = Book.objects.order_by("id") qs1 = books.filter(id__in=qs) qs2 = books.filter(id__in=list(qs)) self.assertEqual(list(qs1), list(qs2)) def test_aggregates_in_where_clause_pre_eval(self): """ Regression test for #12822: DatabaseError: aggregates not allowed in WHERE clause Same as the above test, but evaluates the queryset for the subquery before it's used as a subquery. Before the corresponding fix for this bug, this test failed in both 1.1 and 1.2-beta (trunk). """ qs = Book.objects.values("contact").annotate(Max("id")) qs = qs.order_by("contact").values_list("id__max", flat=True) # force the queryset (qs) for the subquery to be evaluated in its # current state list(qs) books = Book.objects.order_by("id") qs1 = books.filter(id__in=qs) qs2 = books.filter(id__in=list(qs)) self.assertEqual(list(qs1), list(qs2)) @skipUnlessDBFeature("supports_subqueries_in_group_by") def test_annotate_with_extra(self): """ Regression test for #11916: Extra params + aggregation creates incorrect SQL. """ # Oracle doesn't support subqueries in group by clause shortest_book_sql = """ SELECT name FROM aggregation_regress_book b WHERE b.publisher_id = aggregation_regress_publisher.id ORDER BY b.pages LIMIT 1 """ # tests that this query does not raise a DatabaseError due to the full # subselect being (erroneously) added to the GROUP BY parameters qs = Publisher.objects.extra( select={ "name_of_shortest_book": shortest_book_sql, } ).annotate(total_books=Count("book")) # force execution of the query list(qs) def test_aggregate(self): # Ordering requests are ignored self.assertEqual( Author.objects.order_by("name").aggregate(Avg("age")), {"age__avg": Approximate(37.444, places=1)}, ) # Implicit ordering is also ignored self.assertEqual( Book.objects.aggregate(Sum("pages")), {"pages__sum": 3703}, ) # Baseline results self.assertEqual( Book.objects.aggregate(Sum("pages"), Avg("pages")), {"pages__sum": 3703, "pages__avg": Approximate(617.166, places=2)}, ) # Empty values query doesn't affect grouping or results self.assertEqual( Book.objects.values().aggregate(Sum("pages"), Avg("pages")), {"pages__sum": 3703, "pages__avg": Approximate(617.166, places=2)}, ) # Aggregate overrides extra selected column self.assertEqual( Book.objects.extra(select={"price_per_page": "price / pages"}).aggregate( Sum("pages") ), {"pages__sum": 3703}, ) def test_annotation(self): # Annotations get combined with extra select clauses obj = ( Book.objects.annotate(mean_auth_age=Avg("authors__age")) .extra(select={"manufacture_cost": "price * .5"}) .get(pk=self.b2.pk) ) self.assertObjectAttrs( obj, contact_id=self.a3.id, isbn="067232959", mean_auth_age=45.0, name="Sams Teach Yourself Django in 24 Hours", pages=528, price=Decimal("23.09"), pubdate=datetime.date(2008, 3, 3), publisher_id=self.p2.id, rating=3.0, ) # Different DB backends return different types for the extra select # computation self.assertIn(obj.manufacture_cost, (11.545, Decimal("11.545"))) # Order of the annotate/extra in the query doesn't matter obj = ( Book.objects.extra(select={"manufacture_cost": "price * .5"}) .annotate(mean_auth_age=Avg("authors__age")) .get(pk=self.b2.pk) ) self.assertObjectAttrs( obj, contact_id=self.a3.id, isbn="067232959", mean_auth_age=45.0, name="Sams Teach Yourself Django in 24 Hours", pages=528, price=Decimal("23.09"), pubdate=datetime.date(2008, 3, 3), publisher_id=self.p2.id, rating=3.0, ) # Different DB backends return different types for the extra select # computation self.assertIn(obj.manufacture_cost, (11.545, Decimal("11.545"))) # Values queries can be combined with annotate and extra obj = ( Book.objects.annotate(mean_auth_age=Avg("authors__age")) .extra(select={"manufacture_cost": "price * .5"}) .values() .get(pk=self.b2.pk) ) manufacture_cost = obj["manufacture_cost"] self.assertIn(manufacture_cost, (11.545, Decimal("11.545"))) del obj["manufacture_cost"] self.assertEqual( obj, { "id": self.b2.id, "contact_id": self.a3.id, "isbn": "067232959", "mean_auth_age": 45.0, "name": "Sams Teach Yourself Django in 24 Hours", "pages": 528, "price": Decimal("23.09"), "pubdate": datetime.date(2008, 3, 3), "publisher_id": self.p2.id, "rating": 3.0, }, ) # The order of the (empty) values, annotate and extra clauses doesn't # matter obj = ( Book.objects.values() .annotate(mean_auth_age=Avg("authors__age")) .extra(select={"manufacture_cost": "price * .5"}) .get(pk=self.b2.pk) ) manufacture_cost = obj["manufacture_cost"] self.assertIn(manufacture_cost, (11.545, Decimal("11.545"))) del obj["manufacture_cost"] self.assertEqual( obj, { "id": self.b2.id, "contact_id": self.a3.id, "isbn": "067232959", "mean_auth_age": 45.0, "name": "Sams Teach Yourself Django in 24 Hours", "pages": 528, "price": Decimal("23.09"), "pubdate": datetime.date(2008, 3, 3), "publisher_id": self.p2.id, "rating": 3.0, }, ) # If the annotation precedes the values clause, it won't be included # unless it is explicitly named obj = ( Book.objects.annotate(mean_auth_age=Avg("authors__age")) .extra(select={"price_per_page": "price / pages"}) .values("name") .get(pk=self.b1.pk) ) self.assertEqual( obj, { "name": "The Definitive Guide to Django: Web Development Done Right", }, ) obj = ( Book.objects.annotate(mean_auth_age=Avg("authors__age")) .extra(select={"price_per_page": "price / pages"}) .values("name", "mean_auth_age") .get(pk=self.b1.pk) ) self.assertEqual( obj, { "mean_auth_age": 34.5, "name": "The Definitive Guide to Django: Web Development Done Right", }, ) # If an annotation isn't included in the values, it can still be used # in a filter qs = ( Book.objects.annotate(n_authors=Count("authors")) .values("name") .filter(n_authors__gt=2) ) self.assertSequenceEqual( qs, [{"name": "Python Web Development with Django"}], ) # The annotations are added to values output if values() precedes # annotate() obj = ( Book.objects.values("name") .annotate(mean_auth_age=Avg("authors__age")) .extra(select={"price_per_page": "price / pages"}) .get(pk=self.b1.pk) ) self.assertEqual( obj, { "mean_auth_age": 34.5, "name": "The Definitive Guide to Django: Web Development Done Right", }, ) # All of the objects are getting counted (allow_nulls) and that values # respects the amount of objects self.assertEqual(len(Author.objects.annotate(Avg("friends__age")).values()), 9) # Consecutive calls to annotate accumulate in the query qs = ( Book.objects.values("price") .annotate(oldest=Max("authors__age")) .order_by("oldest", "price") .annotate(Max("publisher__num_awards")) ) self.assertSequenceEqual( qs, [ {"price": Decimal("30"), "oldest": 35, "publisher__num_awards__max": 3}, { "price": Decimal("29.69"), "oldest": 37, "publisher__num_awards__max": 7, }, { "price": Decimal("23.09"), "oldest": 45, "publisher__num_awards__max": 1, }, {"price": Decimal("75"), "oldest": 57, "publisher__num_awards__max": 9}, { "price": Decimal("82.8"), "oldest": 57, "publisher__num_awards__max": 7, }, ], ) def test_aggregate_annotation(self): # Aggregates can be composed over annotations. # The return type is derived from the composed aggregate vals = Book.objects.annotate(num_authors=Count("authors__id")).aggregate( Max("pages"), Max("price"), Sum("num_authors"), Avg("num_authors") ) self.assertEqual( vals, { "num_authors__sum": 10, "num_authors__avg": Approximate(1.666, places=2), "pages__max": 1132, "price__max": Decimal("82.80"), }, ) # Regression for #15624 - Missing SELECT columns when using values, # annotate and aggregate in a single query self.assertEqual( Book.objects.annotate(c=Count("authors")).values("c").aggregate(Max("c")), {"c__max": 3}, ) def test_conditional_aggregate(self): # Conditional aggregation of a grouped queryset. self.assertEqual( Book.objects.annotate(c=Count("authors")) .values("pk") .aggregate(test=Sum(Case(When(c__gt=1, then=1))))["test"], 3, ) def test_sliced_conditional_aggregate(self): self.assertEqual( Author.objects.order_by("pk")[:5].aggregate( test=Sum(Case(When(age__lte=35, then=1))) )["test"], 3, ) def test_annotated_conditional_aggregate(self): annotated_qs = Book.objects.annotate( discount_price=F("price") * Decimal("0.75") ) self.assertAlmostEqual( annotated_qs.aggregate( test=Avg( Case( When(pages__lt=400, then="discount_price"), output_field=DecimalField(), ) ) )["test"], Decimal("22.27"), places=2, ) def test_distinct_conditional_aggregate(self): self.assertEqual( Book.objects.distinct().aggregate( test=Avg( Case( When(price=Decimal("29.69"), then="pages"), output_field=IntegerField(), ) ) )["test"], 325, ) def test_conditional_aggregate_on_complex_condition(self): self.assertEqual( Book.objects.distinct().aggregate( test=Avg( Case( When( Q(price__gte=Decimal("29")) & Q(price__lt=Decimal("30")), then="pages", ), output_field=IntegerField(), ) ) )["test"], 325, ) def test_q_annotation_aggregate(self): self.assertEqual(Book.objects.annotate(has_pk=Q(pk__isnull=False)).count(), 6) def test_decimal_aggregate_annotation_filter(self): """ Filtering on an aggregate annotation with Decimal values should work. Requires special handling on SQLite (#18247). """ self.assertEqual( len( Author.objects.annotate(sum=Sum("book_contact_set__price")).filter( sum__gt=Decimal(40) ) ), 1, ) self.assertEqual( len( Author.objects.annotate(sum=Sum("book_contact_set__price")).filter( sum__lte=Decimal(40) ) ), 4, ) def test_field_error(self): # Bad field requests in aggregates are caught and reported msg = ( "Cannot resolve keyword 'foo' into field. Choices are: authors, " "contact, contact_id, hardbackbook, id, isbn, name, pages, price, " "pubdate, publisher, publisher_id, rating, store, tags" ) with self.assertRaisesMessage(FieldError, msg): Book.objects.aggregate(num_authors=Count("foo")) with self.assertRaisesMessage(FieldError, msg): Book.objects.annotate(num_authors=Count("foo")) msg = ( "Cannot resolve keyword 'foo' into field. Choices are: authors, " "contact, contact_id, hardbackbook, id, isbn, name, num_authors, " "pages, price, pubdate, publisher, publisher_id, rating, store, tags" ) with self.assertRaisesMessage(FieldError, msg): Book.objects.annotate(num_authors=Count("authors__id")).aggregate( Max("foo") ) def test_more(self): # Old-style count aggregations can be mixed with new-style self.assertEqual(Book.objects.annotate(num_authors=Count("authors")).count(), 6) # Non-ordinal, non-computed Aggregates over annotations correctly # inherit the annotation's internal type if the annotation is ordinal # or computed vals = Book.objects.annotate(num_authors=Count("authors")).aggregate( Max("num_authors") ) self.assertEqual(vals, {"num_authors__max": 3}) vals = Publisher.objects.annotate(avg_price=Avg("book__price")).aggregate( Max("avg_price") ) self.assertEqual(vals, {"avg_price__max": 75.0}) # Aliases are quoted to protected aliases that might be reserved names vals = Book.objects.aggregate(number=Max("pages"), select=Max("pages")) self.assertEqual(vals, {"number": 1132, "select": 1132}) # Regression for #10064: select_related() plays nice with aggregates obj = ( Book.objects.select_related("publisher") .annotate(num_authors=Count("authors")) .values() .get(isbn="013790395") ) self.assertEqual( obj, { "contact_id": self.a8.id, "id": self.b5.id, "isbn": "013790395", "name": "Artificial Intelligence: A Modern Approach", "num_authors": 2, "pages": 1132, "price": Decimal("82.8"), "pubdate": datetime.date(1995, 1, 15), "publisher_id": self.p3.id, "rating": 4.0, }, ) # Regression for #10010: exclude on an aggregate field is correctly # negated self.assertEqual(len(Book.objects.annotate(num_authors=Count("authors"))), 6) self.assertEqual( len( Book.objects.annotate(num_authors=Count("authors")).filter( num_authors__gt=2 ) ), 1, ) self.assertEqual( len( Book.objects.annotate(num_authors=Count("authors")).exclude( num_authors__gt=2 ) ), 5, ) self.assertEqual( len( Book.objects.annotate(num_authors=Count("authors")) .filter(num_authors__lt=3) .exclude(num_authors__lt=2) ), 2, ) self.assertEqual( len( Book.objects.annotate(num_authors=Count("authors")) .exclude(num_authors__lt=2) .filter(num_authors__lt=3) ), 2, ) def test_aggregate_fexpr(self): # Aggregates can be used with F() expressions # ... where the F() is pushed into the HAVING clause qs = ( Publisher.objects.annotate(num_books=Count("book")) .filter(num_books__lt=F("num_awards") / 2) .order_by("name") .values("name", "num_books", "num_awards") ) self.assertSequenceEqual( qs, [ {"num_books": 1, "name": "Morgan Kaufmann", "num_awards": 9}, {"num_books": 2, "name": "Prentice Hall", "num_awards": 7}, ], ) qs = ( Publisher.objects.annotate(num_books=Count("book")) .exclude(num_books__lt=F("num_awards") / 2) .order_by("name") .values("name", "num_books", "num_awards") ) self.assertSequenceEqual( qs, [ {"num_books": 2, "name": "Apress", "num_awards": 3}, {"num_books": 0, "name": "Jonno's House of Books", "num_awards": 0}, {"num_books": 1, "name": "Sams", "num_awards": 1}, ], ) # ... and where the F() references an aggregate qs = ( Publisher.objects.annotate(num_books=Count("book")) .filter(num_awards__gt=2 * F("num_books")) .order_by("name") .values("name", "num_books", "num_awards") ) self.assertSequenceEqual( qs, [ {"num_books": 1, "name": "Morgan Kaufmann", "num_awards": 9}, {"num_books": 2, "name": "Prentice Hall", "num_awards": 7}, ], ) qs = ( Publisher.objects.annotate(num_books=Count("book")) .exclude(num_books__lt=F("num_awards") / 2) .order_by("name") .values("name", "num_books", "num_awards") ) self.assertSequenceEqual( qs, [ {"num_books": 2, "name": "Apress", "num_awards": 3}, {"num_books": 0, "name": "Jonno's House of Books", "num_awards": 0}, {"num_books": 1, "name": "Sams", "num_awards": 1}, ], ) def test_db_col_table(self): # Tests on fields with non-default table and column names. qs = Clues.objects.values("EntryID__Entry").annotate( Appearances=Count("EntryID"), Distinct_Clues=Count("Clue", distinct=True) ) self.assertSequenceEqual(qs, []) qs = Entries.objects.annotate(clue_count=Count("clues__ID")) self.assertSequenceEqual(qs, []) def test_boolean_conversion(self): # Aggregates mixed up ordering of columns for backend's convert_values # method. Refs #21126. e = Entries.objects.create(Entry="foo") c = Clues.objects.create(EntryID=e, Clue="bar") qs = Clues.objects.select_related("EntryID").annotate(Count("ID")) self.assertSequenceEqual(qs, [c]) self.assertEqual(qs[0].EntryID, e) self.assertIs(qs[0].EntryID.Exclude, False) def test_empty(self): # Regression for #10089: Check handling of empty result sets with # aggregates self.assertEqual(Book.objects.filter(id__in=[]).count(), 0) vals = Book.objects.filter(id__in=[]).aggregate( num_authors=Count("authors"), avg_authors=Avg("authors"), max_authors=Max("authors"), max_price=Max("price"), max_rating=Max("rating"), ) self.assertEqual( vals, { "max_authors": None, "max_rating": None, "num_authors": 0, "avg_authors": None, "max_price": None, }, ) qs = ( Publisher.objects.filter(name="Jonno's House of Books") .annotate( num_authors=Count("book__authors"), avg_authors=Avg("book__authors"), max_authors=Max("book__authors"), max_price=Max("book__price"), max_rating=Max("book__rating"), ) .values() ) self.assertSequenceEqual( qs, [ { "max_authors": None, "name": "Jonno's House of Books", "num_awards": 0, "max_price": None, "num_authors": 0, "max_rating": None, "id": self.p5.id, "avg_authors": None, } ], ) def test_more_more(self): # Regression for #10113 - Fields mentioned in order_by() must be # included in the GROUP BY. This only becomes a problem when the # order_by introduces a new join. self.assertQuerySetEqual( Book.objects.annotate(num_authors=Count("authors")).order_by( "publisher__name", "name" ), [ "Practical Django Projects", "The Definitive Guide to Django: Web Development Done Right", "Paradigms of Artificial Intelligence Programming: Case Studies in " "Common Lisp", "Artificial Intelligence: A Modern Approach", "Python Web Development with Django", "Sams Teach Yourself Django in 24 Hours", ], lambda b: b.name, ) # Regression for #10127 - Empty select_related() works with annotate qs = ( Book.objects.filter(rating__lt=4.5) .select_related() .annotate(Avg("authors__age")) .order_by("name") ) self.assertQuerySetEqual( qs, [ ( "Artificial Intelligence: A Modern Approach", 51.5, "Prentice Hall", "Peter Norvig", ), ("Practical Django Projects", 29.0, "Apress", "James Bennett"), ( "Python Web Development with Django", Approximate(30.333, places=2), "Prentice Hall", "Jeffrey Forcier", ), ("Sams Teach Yourself Django in 24 Hours", 45.0, "Sams", "Brad Dayley"), ], lambda b: (b.name, b.authors__age__avg, b.publisher.name, b.contact.name), ) # Regression for #10132 - If the values() clause only mentioned extra # (select=) columns, those columns are used for grouping qs = ( Book.objects.extra(select={"pub": "publisher_id"}) .values("pub") .annotate(Count("id")) .order_by("pub") ) self.assertSequenceEqual( qs, [ {"pub": self.p1.id, "id__count": 2}, {"pub": self.p2.id, "id__count": 1}, {"pub": self.p3.id, "id__count": 2}, {"pub": self.p4.id, "id__count": 1}, ], ) qs = ( Book.objects.extra(select={"pub": "publisher_id", "foo": "pages"}) .values("pub") .annotate(Count("id")) .order_by("pub") ) self.assertSequenceEqual( qs, [ {"pub": self.p1.id, "id__count": 2}, {"pub": self.p2.id, "id__count": 1}, {"pub": self.p3.id, "id__count": 2}, {"pub": self.p4.id, "id__count": 1}, ], ) # Regression for #10182 - Queries with aggregate calls are correctly # realiased when used in a subquery ids = ( Book.objects.filter(pages__gt=100) .annotate(n_authors=Count("authors"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/many_to_one/models.py
tests/many_to_one/models.py
""" Many-to-one relationships To define a many-to-one relationship, use ``ForeignKey()``. """ from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, models.CASCADE) class Meta: ordering = ("headline",) def __str__(self): return self.headline class Country(models.Model): id = models.SmallAutoField(primary_key=True) name = models.CharField(max_length=50) class City(models.Model): id = models.BigAutoField(primary_key=True) country = models.ForeignKey( Country, models.CASCADE, related_name="cities", null=True ) name = models.CharField(max_length=50) class District(models.Model): city = models.ForeignKey(City, models.CASCADE, related_name="districts", null=True) name = models.CharField(max_length=50) def __str__(self): return self.name # If ticket #1578 ever slips back in, these models will not be able to be # created (the field names being lowercased versions of their opposite classes # is important here). class First(models.Model): second = models.IntegerField() class Second(models.Model): first = models.ForeignKey(First, models.CASCADE, related_name="the_first") # Protect against repetition of #1839, #2415 and #2536. class Third(models.Model): name = models.CharField(max_length=20) third = models.ForeignKey( "self", models.SET_NULL, null=True, related_name="child_set" ) class Parent(models.Model): name = models.CharField(max_length=20, unique=True) bestchild = models.ForeignKey( "Child", models.SET_NULL, null=True, related_name="favored_by" ) class ParentStringPrimaryKey(models.Model): name = models.CharField(primary_key=True, max_length=15) class Child(models.Model): name = models.CharField(max_length=20) parent = models.ForeignKey(Parent, models.CASCADE) class ChildNullableParent(models.Model): parent = models.ForeignKey(Parent, models.CASCADE, null=True) class ChildStringPrimaryKeyParent(models.Model): parent = models.ForeignKey(ParentStringPrimaryKey, on_delete=models.CASCADE) class ToFieldChild(models.Model): parent = models.ForeignKey( Parent, models.CASCADE, to_field="name", related_name="to_field_children" ) # Multiple paths to the same model (#7110, #7125) class Category(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Record(models.Model): category = models.ForeignKey(Category, models.CASCADE) class Relation(models.Model): left = models.ForeignKey(Record, models.CASCADE, related_name="left_set") right = models.ForeignKey(Record, models.CASCADE, related_name="right_set") def __str__(self): return "%s - %s" % (self.left.category.name, self.right.category.name) # Test related objects visibility. class SchoolManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_public=True) class School(models.Model): is_public = models.BooleanField(default=False) objects = SchoolManager() class Student(models.Model): school = models.ForeignKey(School, models.CASCADE)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/many_to_one/__init__.py
tests/many_to_one/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/many_to_one/tests.py
tests/many_to_one/tests.py
import datetime from copy import deepcopy from django.core.exceptions import ( FieldError, FieldFetchBlocked, MultipleObjectsReturned, ) from django.db import IntegrityError, models, transaction from django.db.models import FETCH_PEERS, RAISE from django.test import TestCase from django.utils.translation import gettext_lazy from .models import ( Article, Category, Child, ChildNullableParent, ChildStringPrimaryKeyParent, City, Country, District, First, Parent, ParentStringPrimaryKey, Record, Relation, Reporter, School, Student, Third, ToFieldChild, ) class ManyToOneTests(TestCase): @classmethod def setUpTestData(cls): # Create a few Reporters. cls.r = Reporter(first_name="John", last_name="Smith", email="john@example.com") cls.r.save() cls.r2 = Reporter( first_name="Paul", last_name="Jones", email="paul@example.com" ) cls.r2.save() # Create an Article. cls.a = Article( headline="This is a test", pub_date=datetime.date(2005, 7, 27), reporter=cls.r, ) cls.a.save() def test_get(self): # Article objects have access to their related Reporter objects. r = self.a.reporter self.assertEqual(r.id, self.r.id) self.assertEqual((r.first_name, self.r.last_name), ("John", "Smith")) def test_create(self): # You can also instantiate an Article by passing the Reporter's ID # instead of a Reporter object. a3 = Article( headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id, ) a3.save() self.assertEqual(a3.reporter.id, self.r.id) # Similarly, the reporter ID can be a string. a4 = Article( headline="Fourth article", pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id), ) a4.save() self.assertEqual(repr(a4.reporter), "<Reporter: John Smith>") def test_add(self): # Create an Article via the Reporter object. new_article = self.r.article_set.create( headline="John's second story", pub_date=datetime.date(2005, 7, 29) ) self.assertEqual(repr(new_article), "<Article: John's second story>") self.assertEqual(new_article.reporter.id, self.r.id) # Create a new article, and add it to the article set. new_article2 = Article( headline="Paul's story", pub_date=datetime.date(2006, 1, 17) ) msg = ( "<Article: Paul's story> instance isn't saved. Use bulk=False or save the " "object first." ) with self.assertRaisesMessage(ValueError, msg): self.r.article_set.add(new_article2) self.r.article_set.add(new_article2, bulk=False) self.assertEqual(new_article2.reporter.id, self.r.id) self.assertSequenceEqual( self.r.article_set.all(), [new_article, new_article2, self.a], ) # Add the same article to a different article set - check that it # moves. self.r2.article_set.add(new_article2) self.assertEqual(new_article2.reporter.id, self.r2.id) self.assertSequenceEqual(self.r2.article_set.all(), [new_article2]) # Adding an object of the wrong type raises TypeError. with transaction.atomic(): with self.assertRaisesMessage( TypeError, "'Article' instance expected, got <Reporter:" ): self.r.article_set.add(self.r2) self.assertSequenceEqual( self.r.article_set.all(), [new_article, self.a], ) def test_set(self): new_article = self.r.article_set.create( headline="John's second story", pub_date=datetime.date(2005, 7, 29) ) new_article2 = self.r2.article_set.create( headline="Paul's story", pub_date=datetime.date(2006, 1, 17) ) # Assign the article to the reporter. new_article2.reporter = self.r new_article2.save() self.assertEqual(repr(new_article2.reporter), "<Reporter: John Smith>") self.assertEqual(new_article2.reporter.id, self.r.id) self.assertSequenceEqual( self.r.article_set.all(), [new_article, new_article2, self.a], ) self.assertSequenceEqual(self.r2.article_set.all(), []) # Set the article back again. self.r2.article_set.set([new_article, new_article2]) self.assertSequenceEqual(self.r.article_set.all(), [self.a]) self.assertSequenceEqual( self.r2.article_set.all(), [new_article, new_article2], ) # Funny case - because the ForeignKey cannot be null, # existing members of the set must remain. self.r.article_set.set([new_article]) self.assertSequenceEqual( self.r.article_set.all(), [new_article, self.a], ) self.assertSequenceEqual(self.r2.article_set.all(), [new_article2]) def test_reverse_assignment_deprecation(self): msg = ( "Direct assignment to the reverse side of a related set is " "prohibited. Use article_set.set() instead." ) with self.assertRaisesMessage(TypeError, msg): self.r2.article_set = [] def test_assign(self): new_article = self.r.article_set.create( headline="John's second story", pub_date=datetime.date(2005, 7, 29) ) new_article2 = self.r2.article_set.create( headline="Paul's story", pub_date=datetime.date(2006, 1, 17) ) # Assign the article to the reporter directly using the descriptor. new_article2.reporter = self.r new_article2.save() self.assertEqual(repr(new_article2.reporter), "<Reporter: John Smith>") self.assertEqual(new_article2.reporter.id, self.r.id) self.assertSequenceEqual( self.r.article_set.all(), [new_article, new_article2, self.a], ) self.assertSequenceEqual(self.r2.article_set.all(), []) # Set the article back again using set() method. self.r2.article_set.set([new_article, new_article2]) self.assertSequenceEqual(self.r.article_set.all(), [self.a]) self.assertSequenceEqual( self.r2.article_set.all(), [new_article, new_article2], ) # Because the ForeignKey cannot be null, existing members of the set # must remain. self.r.article_set.set([new_article]) self.assertSequenceEqual( self.r.article_set.all(), [new_article, self.a], ) self.assertSequenceEqual(self.r2.article_set.all(), [new_article2]) # Reporter cannot be null - there should not be a clear or remove # method self.assertFalse(hasattr(self.r2.article_set, "remove")) self.assertFalse(hasattr(self.r2.article_set, "clear")) def test_assign_fk_id_value(self): parent = Parent.objects.create(name="jeff") child1 = Child.objects.create(name="frank", parent=parent) child2 = Child.objects.create(name="randy", parent=parent) parent.bestchild = child1 parent.save() parent.bestchild_id = child2.pk parent.save() self.assertEqual(parent.bestchild_id, child2.pk) self.assertFalse(Parent.bestchild.is_cached(parent)) self.assertEqual(parent.bestchild, child2) self.assertTrue(Parent.bestchild.is_cached(parent)) # Reassigning the same value doesn't clear cached instance. parent.bestchild_id = child2.pk self.assertTrue(Parent.bestchild.is_cached(parent)) def test_assign_fk_id_none(self): parent = Parent.objects.create(name="jeff") child = Child.objects.create(name="frank", parent=parent) parent.bestchild = child parent.save() parent.bestchild_id = None parent.save() self.assertIsNone(parent.bestchild_id) self.assertFalse(Parent.bestchild.is_cached(parent)) self.assertIsNone(parent.bestchild) self.assertTrue(Parent.bestchild.is_cached(parent)) def test_selects(self): new_article1 = self.r.article_set.create( headline="John's second story", pub_date=datetime.date(2005, 7, 29), ) new_article2 = self.r2.article_set.create( headline="Paul's story", pub_date=datetime.date(2006, 1, 17), ) # Reporter objects have access to their related Article objects. self.assertSequenceEqual( self.r.article_set.all(), [new_article1, self.a], ) self.assertSequenceEqual( self.r.article_set.filter(headline__startswith="This"), [self.a] ) self.assertEqual(self.r.article_set.count(), 2) self.assertEqual(self.r2.article_set.count(), 1) # Get articles by id self.assertSequenceEqual(Article.objects.filter(id__exact=self.a.id), [self.a]) self.assertSequenceEqual(Article.objects.filter(pk=self.a.id), [self.a]) # Query on an article property self.assertSequenceEqual( Article.objects.filter(headline__startswith="This"), [self.a] ) # The API automatically follows relationships as far as you need. # Use double underscores to separate relationships. # This works as many levels deep as you want. There's no limit. # Find all Articles for any Reporter whose first name is "John". self.assertSequenceEqual( Article.objects.filter(reporter__first_name__exact="John"), [new_article1, self.a], ) # Implied __exact also works self.assertSequenceEqual( Article.objects.filter(reporter__first_name="John"), [new_article1, self.a], ) # Query twice over the related field. self.assertSequenceEqual( Article.objects.filter( reporter__first_name__exact="John", reporter__last_name__exact="Smith" ), [new_article1, self.a], ) # The underlying query only makes one join when a related table is # referenced twice. queryset = Article.objects.filter( reporter__first_name__exact="John", reporter__last_name__exact="Smith" ) self.assertNumQueries(1, list, queryset) self.assertEqual( queryset.query.get_compiler(queryset.db).as_sql()[0].count("INNER JOIN"), 1 ) # The automatically joined table has a predictable name. self.assertSequenceEqual( Article.objects.filter(reporter__first_name__exact="John").extra( where=["many_to_one_reporter.last_name='Smith'"] ), [new_article1, self.a], ) # ... and should work fine with the string that comes out of # forms.Form.cleaned_data. self.assertQuerySetEqual( ( Article.objects.filter(reporter__first_name__exact="John").extra( where=["many_to_one_reporter.last_name='%s'" % "Smith"] ) ), [new_article1, self.a], ) # Find all Articles for a Reporter. # Use direct ID check, pk check, and object comparison self.assertSequenceEqual( Article.objects.filter(reporter__id__exact=self.r.id), [new_article1, self.a], ) self.assertSequenceEqual( Article.objects.filter(reporter__pk=self.r.id), [new_article1, self.a], ) self.assertSequenceEqual( Article.objects.filter(reporter=self.r.id), [new_article1, self.a], ) self.assertSequenceEqual( Article.objects.filter(reporter=self.r), [new_article1, self.a], ) self.assertSequenceEqual( Article.objects.filter(reporter__in=[self.r.id, self.r2.id]).distinct(), [new_article1, new_article2, self.a], ) self.assertSequenceEqual( Article.objects.filter(reporter__in=[self.r, self.r2]).distinct(), [new_article1, new_article2, self.a], ) # You can also use a queryset instead of a literal list of instances. # The queryset must be reduced to a list of values using values(), # then converted into a query self.assertSequenceEqual( Article.objects.filter( reporter__in=Reporter.objects.filter(first_name="John") .values("pk") .query ).distinct(), [new_article1, self.a], ) def test_reverse_selects(self): a3 = Article.objects.create( headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id, ) Article.objects.create( headline="Fourth article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id, ) john_smith = [self.r] # Reporters can be queried self.assertSequenceEqual( Reporter.objects.filter(id__exact=self.r.id), john_smith ) self.assertSequenceEqual(Reporter.objects.filter(pk=self.r.id), john_smith) self.assertSequenceEqual( Reporter.objects.filter(first_name__startswith="John"), john_smith ) # Reporters can query in opposite direction of ForeignKey definition self.assertSequenceEqual( Reporter.objects.filter(article__id__exact=self.a.id), john_smith ) self.assertSequenceEqual( Reporter.objects.filter(article__pk=self.a.id), john_smith ) self.assertSequenceEqual(Reporter.objects.filter(article=self.a.id), john_smith) self.assertSequenceEqual(Reporter.objects.filter(article=self.a), john_smith) self.assertSequenceEqual( Reporter.objects.filter(article__in=[self.a.id, a3.id]).distinct(), john_smith, ) self.assertSequenceEqual( Reporter.objects.filter(article__in=[self.a.id, a3]).distinct(), john_smith ) self.assertSequenceEqual( Reporter.objects.filter(article__in=[self.a, a3]).distinct(), john_smith ) self.assertCountEqual( Reporter.objects.filter(article__headline__startswith="T"), [self.r, self.r], ) self.assertSequenceEqual( Reporter.objects.filter(article__headline__startswith="T").distinct(), john_smith, ) # Counting in the opposite direction works in conjunction with # distinct() self.assertEqual( Reporter.objects.filter(article__headline__startswith="T").count(), 2 ) self.assertEqual( Reporter.objects.filter(article__headline__startswith="T") .distinct() .count(), 1, ) # Queries can go round in circles. self.assertCountEqual( Reporter.objects.filter(article__reporter__first_name__startswith="John"), [self.r, self.r, self.r], ) self.assertSequenceEqual( Reporter.objects.filter( article__reporter__first_name__startswith="John" ).distinct(), john_smith, ) self.assertSequenceEqual( Reporter.objects.filter(article__reporter__exact=self.r).distinct(), john_smith, ) # Implied __exact also works. self.assertSequenceEqual( Reporter.objects.filter(article__reporter=self.r).distinct(), john_smith ) # It's possible to use values() calls across many-to-one relations. # (Note, too, that we clear the ordering here so as not to drag the # 'headline' field into the columns being used to determine uniqueness) d = {"reporter__first_name": "John", "reporter__last_name": "Smith"} qs = ( Article.objects.filter( reporter=self.r, ) .distinct() .order_by() .values("reporter__first_name", "reporter__last_name") ) self.assertEqual([d], list(qs)) def test_select_related(self): # Article.objects.select_related().dates() works properly when there # are multiple Articles with the same date but different foreign-key # objects (Reporters). r1 = Reporter.objects.create( first_name="Mike", last_name="Royko", email="royko@suntimes.com" ) r2 = Reporter.objects.create( first_name="John", last_name="Kass", email="jkass@tribune.com" ) Article.objects.create( headline="First", pub_date=datetime.date(1980, 4, 23), reporter=r1 ) Article.objects.create( headline="Second", pub_date=datetime.date(1980, 4, 23), reporter=r2 ) self.assertEqual( list(Article.objects.select_related().dates("pub_date", "day")), [datetime.date(1980, 4, 23), datetime.date(2005, 7, 27)], ) self.assertEqual( list(Article.objects.select_related().dates("pub_date", "month")), [datetime.date(1980, 4, 1), datetime.date(2005, 7, 1)], ) self.assertEqual( list(Article.objects.select_related().dates("pub_date", "year")), [datetime.date(1980, 1, 1), datetime.date(2005, 1, 1)], ) def test_delete(self): new_article1 = self.r.article_set.create( headline="John's second story", pub_date=datetime.date(2005, 7, 29), ) new_article2 = self.r2.article_set.create( headline="Paul's story", pub_date=datetime.date(2006, 1, 17), ) new_article3 = Article.objects.create( headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id, ) new_article4 = Article.objects.create( headline="Fourth article", pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id), ) # If you delete a reporter, their articles will be deleted. self.assertSequenceEqual( Article.objects.all(), [new_article4, new_article1, new_article2, new_article3, self.a], ) self.assertSequenceEqual( Reporter.objects.order_by("first_name"), [self.r, self.r2], ) self.r2.delete() self.assertSequenceEqual( Article.objects.all(), [new_article4, new_article1, new_article3, self.a], ) self.assertSequenceEqual(Reporter.objects.order_by("first_name"), [self.r]) # You can delete using a JOIN in the query. Reporter.objects.filter(article__headline__startswith="This").delete() self.assertSequenceEqual(Reporter.objects.all(), []) self.assertSequenceEqual(Article.objects.all(), []) def test_explicit_fk(self): # Create a new Article with get_or_create using an explicit value # for a ForeignKey. a2, created = Article.objects.get_or_create( headline="John's second test", pub_date=datetime.date(2011, 5, 7), reporter_id=self.r.id, ) self.assertTrue(created) self.assertEqual(a2.reporter.id, self.r.id) # You can specify filters containing the explicit FK value. self.assertSequenceEqual( Article.objects.filter(reporter_id__exact=self.r.id), [a2, self.a], ) # Create an Article by Paul for the same date. a3 = Article.objects.create( headline="Paul's commentary", pub_date=datetime.date(2011, 5, 7), reporter_id=self.r2.id, ) self.assertEqual(a3.reporter.id, self.r2.id) # Get should respect explicit foreign keys as well. msg = "get() returned more than one Article -- it returned 2!" with self.assertRaisesMessage(MultipleObjectsReturned, msg): Article.objects.get(reporter_id=self.r.id) self.assertEqual( repr(a3), repr( Article.objects.get( reporter_id=self.r2.id, pub_date=datetime.date(2011, 5, 7) ) ), ) def test_deepcopy_and_circular_references(self): # Regression for #12876 -- Model methods that include queries that # recursive don't cause recursion depth problems under deepcopy. self.r.cached_query = Article.objects.filter(reporter=self.r) self.assertEqual(repr(deepcopy(self.r)), "<Reporter: John Smith>") def test_manager_class_caching(self): r1 = Reporter.objects.create(first_name="Mike") r2 = Reporter.objects.create(first_name="John") # Same twice self.assertIs(r1.article_set.__class__, r1.article_set.__class__) # Same as each other self.assertIs(r1.article_set.__class__, r2.article_set.__class__) def test_create_relation_with_gettext_lazy(self): reporter = Reporter.objects.create( first_name="John", last_name="Smith", email="john.smith@example.com" ) lazy = gettext_lazy("test") reporter.article_set.create(headline=lazy, pub_date=datetime.date(2011, 6, 10)) notlazy = str(lazy) article = reporter.article_set.get() self.assertEqual(article.headline, notlazy) def test_values_list_exception(self): expected_message = ( "Cannot resolve keyword 'notafield' into field. Choices are: %s" ) reporter_fields = ", ".join(sorted(f.name for f in Reporter._meta.get_fields())) with self.assertRaisesMessage(FieldError, expected_message % reporter_fields): Article.objects.values_list("reporter__notafield") article_fields = ", ".join( ["EXTRA"] + sorted(f.name for f in Article._meta.get_fields()) ) with self.assertRaisesMessage(FieldError, expected_message % article_fields): Article.objects.extra(select={"EXTRA": "EXTRA_SELECT"}).values_list( "notafield" ) def test_fk_assignment_and_related_object_cache(self): # Tests of ForeignKey assignment and the related-object cache (see # #6886). p = Parent.objects.create(name="Parent") c = Child.objects.create(name="Child", parent=p) # Look up the object again so that we get a "fresh" object. c = Child.objects.get(name="Child") p = c.parent # Accessing the related object again returns the exactly same object. self.assertIs(c.parent, p) # But if we kill the cache, we get a new object. del c._state.fields_cache["parent"] self.assertIsNot(c.parent, p) # Assigning a new object results in that object getting cached # immediately. p2 = Parent.objects.create(name="Parent 2") c.parent = p2 self.assertIs(c.parent, p2) # Assigning None succeeds if field is null=True. p.bestchild = None self.assertIsNone(p.bestchild) # bestchild should still be None after saving. p.save() self.assertIsNone(p.bestchild) # bestchild should still be None after fetching the object again. p = Parent.objects.get(name="Parent") self.assertIsNone(p.bestchild) # Assigning None will not fail: Child.parent is null=False. setattr(c, "parent", None) # You also can't assign an object of the wrong type here msg = ( 'Cannot assign "<First: First object (1)>": "Child.parent" must ' 'be a "Parent" instance.' ) with self.assertRaisesMessage(ValueError, msg): setattr(c, "parent", First(id=1, second=1)) # You can assign None to Child.parent during object creation. Child(name="xyzzy", parent=None) # But when trying to save a Child with parent=None, the database will # raise IntegrityError. with self.assertRaises(IntegrityError), transaction.atomic(): Child.objects.create(name="xyzzy", parent=None) # Creation using keyword argument should cache the related object. p = Parent.objects.get(name="Parent") c = Child(parent=p) self.assertIs(c.parent, p) # Creation using keyword argument and unsaved related instance (#8070). p = Parent() msg = ( "save() prohibited to prevent data loss due to unsaved related object " "'parent'." ) with self.assertRaisesMessage(ValueError, msg): Child.objects.create(parent=p) with self.assertRaisesMessage(ValueError, msg): ToFieldChild.objects.create(parent=p) # Creation using attname keyword argument and an id will cause the # related object to be fetched. p = Parent.objects.get(name="Parent") c = Child(parent_id=p.id) self.assertIsNot(c.parent, p) self.assertEqual(c.parent, p) def test_save_parent_after_assign(self): category = Category(name="cats") record = Record(category=category) category.save() record.save() category.name = "dogs" with self.assertNumQueries(0): self.assertEqual(category.id, record.category_id) self.assertEqual(category.name, record.category.name) def test_save_nullable_fk_after_parent(self): parent = Parent() child = ChildNullableParent(parent=parent) parent.save() child.save() child.refresh_from_db() self.assertEqual(child.parent, parent) def test_save_nullable_fk_after_parent_with_to_field(self): parent = Parent(name="jeff") child = ToFieldChild(parent=parent) parent.save() child.save() child.refresh_from_db() self.assertEqual(child.parent, parent) self.assertEqual(child.parent_id, parent.name) def test_save_fk_after_parent_with_non_numeric_pk_set_on_child(self): parent = ParentStringPrimaryKey() child = ChildStringPrimaryKeyParent(parent=parent) child.parent.name = "jeff" parent.save() child.save() child.refresh_from_db() self.assertEqual(child.parent, parent) self.assertEqual(child.parent_id, parent.name) def test_fk_to_bigautofield(self): ch = City.objects.create(name="Chicago") District.objects.create(city=ch, name="Far South") District.objects.create(city=ch, name="North") ny = City.objects.create(name="New York", id=2**33) District.objects.create(city=ny, name="Brooklyn") District.objects.create(city=ny, name="Manhattan") def test_fk_to_smallautofield(self): us = Country.objects.create(name="United States") City.objects.create(country=us, name="Chicago") City.objects.create(country=us, name="New York") uk = Country.objects.create(name="United Kingdom", id=2**11) City.objects.create(country=uk, name="London") City.objects.create(country=uk, name="Edinburgh") def test_multiple_foreignkeys(self): # Test of multiple ForeignKeys to the same model (bug #7125). c1 = Category.objects.create(name="First") c2 = Category.objects.create(name="Second") c3 = Category.objects.create(name="Third") r1 = Record.objects.create(category=c1) r2 = Record.objects.create(category=c1) r3 = Record.objects.create(category=c2) r4 = Record.objects.create(category=c2) r5 = Record.objects.create(category=c3) Relation.objects.create(left=r1, right=r2) Relation.objects.create(left=r3, right=r4) rel = Relation.objects.create(left=r1, right=r3) Relation.objects.create(left=r5, right=r2) Relation.objects.create(left=r3, right=r2) q1 = Relation.objects.filter( left__category__name__in=["First"], right__category__name__in=["Second"] ) self.assertSequenceEqual(q1, [rel]) q2 = Category.objects.filter( record__left_set__right__category__name="Second" ).order_by("name") self.assertSequenceEqual(q2, [c1, c2]) p = Parent.objects.create(name="Parent") c = Child.objects.create(name="Child", parent=p) msg = 'Cannot assign "%r": "Child.parent" must be a "Parent" instance.' % c with self.assertRaisesMessage(ValueError, msg): Child.objects.create(name="Grandchild", parent=c) def test_fk_instantiation_outside_model(self): # Regression for #12190 -- Should be able to instantiate a FK outside # of a model, and interrogate its related field. cat = models.ForeignKey(Category, models.CASCADE) self.assertEqual("id", cat.remote_field.get_related_field().name) def test_relation_unsaved(self): Third.objects.create(name="Third 1") Third.objects.create(name="Third 2") th = Third(name="testing") # The object isn't saved and the relation cannot be used. msg = ( "'Third' instance needs to have a primary key value before this " "relationship can be used." ) with self.assertRaisesMessage(ValueError, msg): th.child_set.count() # The reverse foreign key manager can be created. self.assertEqual(th.child_set.model, Third) th.save() # Now the model is saved, so we will need to execute a query. with self.assertNumQueries(1): self.assertEqual(th.child_set.count(), 0) def test_related_object(self): public_school = School.objects.create(is_public=True) public_student = Student.objects.create(school=public_school) private_school = School.objects.create(is_public=False) private_student = Student.objects.create(school=private_school) # Only one school is available via all() due to the custom default # manager. self.assertSequenceEqual(School.objects.all(), [public_school]) self.assertEqual(public_student.school, public_school) # Make sure the base manager is used so that a student can still access # its related school even if the default manager doesn't normally # allow it. self.assertEqual(private_student.school, private_school) School._meta.base_manager_name = "objects" School._meta._expire_cache() try: private_student = Student.objects.get(pk=private_student.pk) with self.assertRaises(School.DoesNotExist): private_student.school finally: School._meta.base_manager_name = None School._meta._expire_cache() def test_hasattr_related_object(self): # The exception raised on attribute access when a related object # doesn't exist should be an instance of a subclass of `AttributeError` # refs #21563 self.assertFalse(hasattr(Article(), "reporter")) def test_create_after_prefetch(self): c = City.objects.create(name="Musical City") d1 = District.objects.create(name="Ladida", city=c) city = City.objects.prefetch_related("districts").get(id=c.id) self.assertSequenceEqual(city.districts.all(), [d1]) d2 = city.districts.create(name="Goa") self.assertSequenceEqual(city.districts.all(), [d1, d2]) def test_clear_after_prefetch(self): c = City.objects.create(name="Musical City") d = District.objects.create(name="Ladida", city=c) city = City.objects.prefetch_related("districts").get(id=c.id) self.assertSequenceEqual(city.districts.all(), [d]) city.districts.clear() self.assertSequenceEqual(city.districts.all(), []) def test_remove_after_prefetch(self): c = City.objects.create(name="Musical City") d = District.objects.create(name="Ladida", city=c) city = City.objects.prefetch_related("districts").get(id=c.id) self.assertSequenceEqual(city.districts.all(), [d]) city.districts.remove(d) self.assertSequenceEqual(city.districts.all(), [])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_exceptions/__init__.py
tests/test_exceptions/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/test_exceptions/test_validation_error.py
tests/test_exceptions/test_validation_error.py
import unittest from unittest import mock from django.core.exceptions import ValidationError class TestValidationError(unittest.TestCase): def test_messages_concatenates_error_dict_values(self): message_dict = {} exception = ValidationError(message_dict) self.assertEqual(sorted(exception.messages), []) message_dict["field1"] = ["E1", "E2"] exception = ValidationError(message_dict) self.assertEqual(sorted(exception.messages), ["E1", "E2"]) message_dict["field2"] = ["E3", "E4"] exception = ValidationError(message_dict) self.assertEqual(sorted(exception.messages), ["E1", "E2", "E3", "E4"]) def test_eq(self): error1 = ValidationError("message") error2 = ValidationError("message", code="my_code1") error3 = ValidationError("message", code="my_code2") error4 = ValidationError( "error %(parm1)s %(parm2)s", code="my_code1", params={"parm1": "val1", "parm2": "val2"}, ) error5 = ValidationError({"field1": "message", "field2": "other"}) error6 = ValidationError({"field1": "message"}) error7 = ValidationError( [ ValidationError({"field1": "field error", "field2": "other"}), "message", ] ) self.assertEqual(error1, ValidationError("message")) self.assertNotEqual(error1, ValidationError("message2")) self.assertNotEqual(error1, error2) self.assertNotEqual(error1, error4) self.assertNotEqual(error1, error5) self.assertNotEqual(error1, error6) self.assertNotEqual(error1, error7) self.assertEqual(error1, mock.ANY) self.assertEqual(error2, ValidationError("message", code="my_code1")) self.assertNotEqual(error2, ValidationError("other", code="my_code1")) self.assertNotEqual(error2, error3) self.assertNotEqual(error2, error4) self.assertNotEqual(error2, error5) self.assertNotEqual(error2, error6) self.assertNotEqual(error2, error7) self.assertEqual( error4, ValidationError( "error %(parm1)s %(parm2)s", code="my_code1", params={"parm1": "val1", "parm2": "val2"}, ), ) self.assertNotEqual( error4, ValidationError( "error %(parm1)s %(parm2)s", code="my_code2", params={"parm1": "val1", "parm2": "val2"}, ), ) self.assertNotEqual( error4, ValidationError( "error %(parm1)s %(parm2)s", code="my_code1", params={"parm2": "val2"}, ), ) self.assertNotEqual( error4, ValidationError( "error %(parm1)s %(parm2)s", code="my_code1", params={"parm2": "val1", "parm1": "val2"}, ), ) self.assertNotEqual( error4, ValidationError( "error val1 val2", code="my_code1", ), ) # params ordering is ignored. self.assertEqual( error4, ValidationError( "error %(parm1)s %(parm2)s", code="my_code1", params={"parm2": "val2", "parm1": "val1"}, ), ) self.assertEqual( error5, ValidationError({"field1": "message", "field2": "other"}), ) self.assertNotEqual( error5, ValidationError({"field1": "message", "field2": "other2"}), ) self.assertNotEqual( error5, ValidationError({"field1": "message", "field3": "other"}), ) self.assertNotEqual(error5, error6) # fields ordering is ignored. self.assertEqual( error5, ValidationError({"field2": "other", "field1": "message"}), ) self.assertNotEqual(error7, ValidationError(error7.error_list[1:])) self.assertNotEqual( ValidationError(["message"]), ValidationError([ValidationError("message", code="my_code")]), ) # messages ordering is ignored. self.assertEqual( error7, ValidationError(list(reversed(error7.error_list))), ) self.assertNotEqual(error4, ValidationError([error4])) self.assertNotEqual(ValidationError([error4]), error4) self.assertNotEqual(error4, ValidationError({"field1": error4})) self.assertNotEqual(ValidationError({"field1": error4}), error4) def test_eq_nested(self): error_dict = { "field1": ValidationError( "error %(parm1)s %(parm2)s", code="my_code", params={"parm1": "val1", "parm2": "val2"}, ), "field2": "other", } error = ValidationError(error_dict) self.assertEqual(error, ValidationError(dict(error_dict))) self.assertEqual( error, ValidationError( { "field1": ValidationError( "error %(parm1)s %(parm2)s", code="my_code", params={"parm2": "val2", "parm1": "val1"}, ), "field2": "other", } ), ) self.assertNotEqual( error, ValidationError( {**error_dict, "field2": "message"}, ), ) self.assertNotEqual( error, ValidationError( { "field1": ValidationError( "error %(parm1)s val2", code="my_code", params={"parm1": "val1"}, ), "field2": "other", } ), ) def test_hash(self): error1 = ValidationError("message") error2 = ValidationError("message", code="my_code1") error3 = ValidationError("message", code="my_code2") error4 = ValidationError( "error %(parm1)s %(parm2)s", code="my_code1", params={"parm1": "val1", "parm2": "val2"}, ) error5 = ValidationError({"field1": "message", "field2": "other"}) error6 = ValidationError({"field1": "message"}) error7 = ValidationError( [ ValidationError({"field1": "field error", "field2": "other"}), "message", ] ) self.assertEqual(hash(error1), hash(ValidationError("message"))) self.assertNotEqual(hash(error1), hash(ValidationError("message2"))) self.assertNotEqual(hash(error1), hash(error2)) self.assertNotEqual(hash(error1), hash(error4)) self.assertNotEqual(hash(error1), hash(error5)) self.assertNotEqual(hash(error1), hash(error6)) self.assertNotEqual(hash(error1), hash(error7)) self.assertEqual( hash(error2), hash(ValidationError("message", code="my_code1")), ) self.assertNotEqual( hash(error2), hash(ValidationError("other", code="my_code1")), ) self.assertNotEqual(hash(error2), hash(error3)) self.assertNotEqual(hash(error2), hash(error4)) self.assertNotEqual(hash(error2), hash(error5)) self.assertNotEqual(hash(error2), hash(error6)) self.assertNotEqual(hash(error2), hash(error7)) self.assertEqual( hash(error4), hash( ValidationError( "error %(parm1)s %(parm2)s", code="my_code1", params={"parm1": "val1", "parm2": "val2"}, ) ), ) self.assertNotEqual( hash(error4), hash( ValidationError( "error %(parm1)s %(parm2)s", code="my_code2", params={"parm1": "val1", "parm2": "val2"}, ) ), ) self.assertNotEqual( hash(error4), hash( ValidationError( "error %(parm1)s %(parm2)s", code="my_code1", params={"parm2": "val2"}, ) ), ) self.assertNotEqual( hash(error4), hash( ValidationError( "error %(parm1)s %(parm2)s", code="my_code1", params={"parm2": "val1", "parm1": "val2"}, ) ), ) self.assertNotEqual( hash(error4), hash( ValidationError( "error val1 val2", code="my_code1", ) ), ) # params ordering is ignored. self.assertEqual( hash(error4), hash( ValidationError( "error %(parm1)s %(parm2)s", code="my_code1", params={"parm2": "val2", "parm1": "val1"}, ) ), ) self.assertEqual( hash(error5), hash(ValidationError({"field1": "message", "field2": "other"})), ) self.assertNotEqual( hash(error5), hash(ValidationError({"field1": "message", "field2": "other2"})), ) self.assertNotEqual( hash(error5), hash(ValidationError({"field1": "message", "field3": "other"})), ) self.assertNotEqual(error5, error6) # fields ordering is ignored. self.assertEqual( hash(error5), hash(ValidationError({"field2": "other", "field1": "message"})), ) self.assertNotEqual( hash(error7), hash(ValidationError(error7.error_list[1:])), ) self.assertNotEqual( hash(ValidationError(["message"])), hash(ValidationError([ValidationError("message", code="my_code")])), ) # messages ordering is ignored. self.assertEqual( hash(error7), hash(ValidationError(list(reversed(error7.error_list)))), ) self.assertNotEqual(hash(error4), hash(ValidationError([error4]))) self.assertNotEqual(hash(ValidationError([error4])), hash(error4)) self.assertNotEqual( hash(error4), hash(ValidationError({"field1": error4})), ) def test_hash_nested(self): error_dict = { "field1": ValidationError( "error %(parm1)s %(parm2)s", code="my_code", params={"parm2": "val2", "parm1": "val1"}, ), "field2": "other", } error = ValidationError(error_dict) self.assertEqual(hash(error), hash(ValidationError(dict(error_dict)))) self.assertEqual( hash(error), hash( ValidationError( { "field1": ValidationError( "error %(parm1)s %(parm2)s", code="my_code", params={"parm1": "val1", "parm2": "val2"}, ), "field2": "other", } ) ), ) self.assertNotEqual( hash(error), hash( ValidationError( {**error_dict, "field2": "message"}, ) ), ) self.assertNotEqual( hash(error), hash( ValidationError( { "field1": ValidationError( "error %(parm1)s val2", code="my_code", params={"parm1": "val1"}, ), "field2": "other", } ) ), )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrate_signals/models.py
tests/migrate_signals/models.py
# This module has to exist, otherwise pre/post_migrate aren't sent for the # migrate_signals application.
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrate_signals/__init__.py
tests/migrate_signals/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrate_signals/tests.py
tests/migrate_signals/tests.py
from io import StringIO from django.apps import apps from django.core import management from django.db import migrations from django.db.models import signals from django.test import TransactionTestCase, override_settings APP_CONFIG = apps.get_app_config("migrate_signals") SIGNAL_ARGS = [ "app_config", "verbosity", "interactive", "using", "stdout", "plan", "apps", ] MIGRATE_DATABASE = "default" MIGRATE_VERBOSITY = 0 MIGRATE_INTERACTIVE = False class Receiver: def __init__(self, signal): self.call_counter = 0 self.call_args = None signal.connect(self, sender=APP_CONFIG) def __call__(self, signal, sender, **kwargs): self.call_counter += 1 self.call_args = kwargs class OneTimeReceiver: """ Special receiver for handle the fact that test runner calls migrate for several databases and several times for some of them. """ def __init__(self, signal): self.signal = signal self.call_counter = 0 self.call_args = None self.signal.connect(self, sender=APP_CONFIG) def __call__(self, signal, sender, **kwargs): # Although test runner calls migrate for several databases, # testing for only one of them is quite sufficient. if kwargs["using"] == MIGRATE_DATABASE: self.call_counter += 1 self.call_args = kwargs # we need to test only one call of migrate self.signal.disconnect(self, sender=APP_CONFIG) # We connect receiver here and not in unit test code because we need to # connect receiver before test runner creates database. That is, sequence of # actions would be: # # 1. Test runner imports this module. # 2. We connect receiver. # 3. Test runner calls migrate for create default database. # 4. Test runner execute our unit test code. pre_migrate_receiver = OneTimeReceiver(signals.pre_migrate) post_migrate_receiver = OneTimeReceiver(signals.post_migrate) class MigrateSignalTests(TransactionTestCase): available_apps = ["migrate_signals"] def test_call_time(self): self.assertEqual(pre_migrate_receiver.call_counter, 1) self.assertEqual(post_migrate_receiver.call_counter, 1) def test_args(self): pre_migrate_receiver = Receiver(signals.pre_migrate) post_migrate_receiver = Receiver(signals.post_migrate) management.call_command( "migrate", database=MIGRATE_DATABASE, verbosity=MIGRATE_VERBOSITY, interactive=MIGRATE_INTERACTIVE, stdout=StringIO("test_args"), ) for receiver in [pre_migrate_receiver, post_migrate_receiver]: with self.subTest(receiver=receiver): args = receiver.call_args self.assertEqual(receiver.call_counter, 1) self.assertEqual(set(args), set(SIGNAL_ARGS)) self.assertEqual(args["app_config"], APP_CONFIG) self.assertEqual(args["verbosity"], MIGRATE_VERBOSITY) self.assertEqual(args["interactive"], MIGRATE_INTERACTIVE) self.assertEqual(args["using"], "default") self.assertIn("test_args", args["stdout"].getvalue()) self.assertEqual(args["plan"], []) self.assertIsInstance(args["apps"], migrations.state.StateApps) @override_settings( MIGRATION_MODULES={"migrate_signals": "migrate_signals.custom_migrations"} ) def test_migrations_only(self): """ If all apps have migrations, migration signals should be sent. """ pre_migrate_receiver = Receiver(signals.pre_migrate) post_migrate_receiver = Receiver(signals.post_migrate) management.call_command( "migrate", database=MIGRATE_DATABASE, verbosity=MIGRATE_VERBOSITY, interactive=MIGRATE_INTERACTIVE, ) for receiver in [pre_migrate_receiver, post_migrate_receiver]: args = receiver.call_args self.assertEqual(receiver.call_counter, 1) self.assertEqual(set(args), set(SIGNAL_ARGS)) self.assertEqual(args["app_config"], APP_CONFIG) self.assertEqual(args["verbosity"], MIGRATE_VERBOSITY) self.assertEqual(args["interactive"], MIGRATE_INTERACTIVE) self.assertEqual(args["using"], "default") self.assertIsInstance(args["plan"][0][0], migrations.Migration) # The migration isn't applied backward. self.assertFalse(args["plan"][0][1]) self.assertIsInstance(args["apps"], migrations.state.StateApps) self.assertEqual(pre_migrate_receiver.call_args["apps"].get_models(), []) self.assertEqual( [ model._meta.label for model in post_migrate_receiver.call_args["apps"].get_models() ], ["migrate_signals.Signal"], ) # Migrating with an empty plan. pre_migrate_receiver = Receiver(signals.pre_migrate) post_migrate_receiver = Receiver(signals.post_migrate) management.call_command( "migrate", database=MIGRATE_DATABASE, verbosity=MIGRATE_VERBOSITY, interactive=MIGRATE_INTERACTIVE, ) self.assertEqual( [ model._meta.label for model in pre_migrate_receiver.call_args["apps"].get_models() ], ["migrate_signals.Signal"], ) self.assertEqual( [ model._meta.label for model in post_migrate_receiver.call_args["apps"].get_models() ], ["migrate_signals.Signal"], ) # Migrating with an empty plan and --check doesn't emit signals. pre_migrate_receiver = Receiver(signals.pre_migrate) post_migrate_receiver = Receiver(signals.post_migrate) management.call_command( "migrate", database=MIGRATE_DATABASE, verbosity=MIGRATE_VERBOSITY, interactive=MIGRATE_INTERACTIVE, check_unapplied=True, ) self.assertEqual(pre_migrate_receiver.call_counter, 0) self.assertEqual(post_migrate_receiver.call_counter, 0)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrate_signals/custom_migrations/0001_initial.py
tests/migrate_signals/custom_migrations/0001_initial.py
from django.db import migrations, models class Migration(migrations.Migration): operations = [ migrations.CreateModel( "Signal", [ ("id", models.AutoField(primary_key=True)), ], ), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrate_signals/custom_migrations/__init__.py
tests/migrate_signals/custom_migrations/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/swappable_models/models.py
tests/swappable_models/models.py
from django.db import models class Article(models.Model): title = models.CharField(max_length=100) publication_date = models.DateField() class Meta: swappable = "TEST_ARTICLE_MODEL" class AlternateArticle(models.Model): title = models.CharField(max_length=100) publication_date = models.DateField() byline = models.CharField(max_length=100)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/swappable_models/__init__.py
tests/swappable_models/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/swappable_models/tests.py
tests/swappable_models/tests.py
from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from django.core import management from django.test import TestCase, override_settings from .models import Article class SwappableModelTests(TestCase): # Limit memory usage when calling 'migrate'. available_apps = [ "swappable_models", "django.contrib.auth", "django.contrib.contenttypes", ] @override_settings(TEST_ARTICLE_MODEL="swappable_models.AlternateArticle") def test_generated_data(self): "Permissions and content types are not created for a swapped model" # Delete all permissions and content_types Permission.objects.filter(content_type__app_label="swappable_models").delete() ContentType.objects.filter(app_label="swappable_models").delete() # Re-run migrate. This will re-build the permissions and content types. management.call_command("migrate", interactive=False, verbosity=0) # Content types and permissions exist for the swapped model, # but not for the swappable model. apps_models = [ (p.content_type.app_label, p.content_type.model) for p in Permission.objects.all() ] self.assertIn(("swappable_models", "alternatearticle"), apps_models) self.assertNotIn(("swappable_models", "article"), apps_models) apps_models = [(ct.app_label, ct.model) for ct in ContentType.objects.all()] self.assertIn(("swappable_models", "alternatearticle"), apps_models) self.assertNotIn(("swappable_models", "article"), apps_models) @override_settings(TEST_ARTICLE_MODEL="swappable_models.article") def test_case_insensitive(self): "Model names are case insensitive. Model swapping honors this." Article.objects.all() self.assertIsNone(Article._meta.swapped)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/str/models.py
tests/str/models.py
""" Adding __str__() to models Although it's not a strict requirement, each model should have a ``_str__()`` method to return a "human-readable" representation of the object. Do this not only for your own sanity when dealing with the interactive prompt, but also because objects' representations are used throughout Django's automatically-generated admin. """ from django.db import models class InternationalArticle(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() def __str__(self): return self.headline
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/str/__init__.py
tests/str/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/str/tests.py
tests/str/tests.py
import datetime from django.db import models from django.test import TestCase from django.test.utils import isolate_apps from .models import InternationalArticle class SimpleTests(TestCase): def test_international(self): a = InternationalArticle.objects.create( headline="Girl wins €12.500 in lottery", pub_date=datetime.datetime(2005, 7, 28), ) self.assertEqual(str(a), "Girl wins €12.500 in lottery") @isolate_apps("str") def test_defaults(self): """ The default implementation of __str__ and __repr__ should return instances of str. """ class Default(models.Model): pass obj = Default() # Explicit call to __str__/__repr__ to make sure str()/repr() don't # coerce the returned value. self.assertIsInstance(obj.__str__(), str) self.assertIsInstance(obj.__repr__(), str) self.assertEqual(str(obj), "Default object (None)") self.assertEqual(repr(obj), "<Default: Default object (None)>") obj2 = Default(pk=100) self.assertEqual(str(obj2), "Default object (100)") self.assertEqual(repr(obj2), "<Default: Default object (100)>")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/raw_query/models.py
tests/raw_query/models.py
from django.db import models class Author(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) dob = models.DateField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Protect against annotations being passed to __init__ -- # this'll make the test suite get angry if annotations aren't # treated differently than fields. for k in kwargs: assert k in [f.attname for f in self._meta.fields], ( "Author.__init__ got an unexpected parameter: %s" % k ) class Book(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(Author, models.CASCADE) paperback = models.BooleanField(default=False) opening_line = models.TextField() class BookFkAsPk(models.Model): book = models.ForeignKey( Book, models.CASCADE, primary_key=True, db_column="not_the_default" ) class Coffee(models.Model): brand = models.CharField(max_length=255, db_column="name") price = models.DecimalField(max_digits=10, decimal_places=2, default=0) class MixedCaseIDColumn(models.Model): id = models.AutoField(primary_key=True, db_column="MiXeD_CaSe_Id") class Reviewer(models.Model): reviewed = models.ManyToManyField(Book) class FriendlyAuthor(Author): pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/raw_query/__init__.py
tests/raw_query/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/raw_query/tests.py
tests/raw_query/tests.py
from datetime import date from decimal import Decimal from django.core.exceptions import FieldDoesNotExist, FieldFetchBlocked from django.db.models import FETCH_PEERS, RAISE from django.db.models.query import RawQuerySet from django.test import TestCase, skipUnlessDBFeature from .models import ( Author, Book, BookFkAsPk, Coffee, FriendlyAuthor, MixedCaseIDColumn, Reviewer, ) class RawQueryTests(TestCase): @classmethod def setUpTestData(cls): cls.a1 = Author.objects.create( first_name="Joe", last_name="Smith", dob=date(1950, 9, 20) ) cls.a2 = Author.objects.create( first_name="Jill", last_name="Doe", dob=date(1920, 4, 2) ) cls.a3 = Author.objects.create( first_name="Bob", last_name="Smith", dob=date(1986, 1, 25) ) cls.a4 = Author.objects.create( first_name="Bill", last_name="Jones", dob=date(1932, 5, 10) ) cls.b1 = Book.objects.create( title="The awesome book", author=cls.a1, paperback=False, opening_line=( "It was a bright cold day in April and the clocks were striking " "thirteen." ), ) cls.b2 = Book.objects.create( title="The horrible book", author=cls.a1, paperback=True, opening_line=( "On an evening in the latter part of May a middle-aged man " "was walking homeward from Shaston to the village of Marlott, " "in the adjoining Vale of Blakemore, or Blackmoor." ), ) cls.b3 = Book.objects.create( title="Another awesome book", author=cls.a1, paperback=False, opening_line="A squat gray building of only thirty-four stories.", ) cls.b4 = Book.objects.create( title="Some other book", author=cls.a3, paperback=True, opening_line="It was the day my grandmother exploded.", ) cls.c1 = Coffee.objects.create(brand="dunkin doughnuts") cls.c2 = Coffee.objects.create(brand="starbucks") cls.r1 = Reviewer.objects.create() cls.r2 = Reviewer.objects.create() cls.r1.reviewed.add(cls.b2, cls.b3, cls.b4) def assertSuccessfulRawQuery( self, model, query, expected_results, expected_annotations=(), params=[], translations=None, ): """ Execute the passed query against the passed model and check the output """ results = list( model.objects.raw(query, params=params, translations=translations) ) self.assertProcessed(model, results, expected_results, expected_annotations) self.assertAnnotations(results, expected_annotations) def assertProcessed(self, model, results, orig, expected_annotations=()): """ Compare the results of a raw query against expected results """ self.assertEqual(len(results), len(orig)) for index, item in enumerate(results): orig_item = orig[index] for annotation in expected_annotations: setattr(orig_item, *annotation) for field in model._meta.fields: # All values on the model are equal self.assertEqual( getattr(item, field.attname), getattr(orig_item, field.attname) ) # This includes checking that they are the same type self.assertEqual( type(getattr(item, field.attname)), type(getattr(orig_item, field.attname)), ) def assertNoAnnotations(self, results): """ The results of a raw query contain no annotations """ self.assertAnnotations(results, ()) def assertAnnotations(self, results, expected_annotations): """ The passed raw query results contain the expected annotations """ if expected_annotations: for index, result in enumerate(results): annotation, value = expected_annotations[index] self.assertTrue(hasattr(result, annotation)) self.assertEqual(getattr(result, annotation), value) def test_rawqueryset_repr(self): queryset = RawQuerySet(raw_query="SELECT * FROM raw_query_author") self.assertEqual( repr(queryset), "<RawQuerySet: SELECT * FROM raw_query_author>" ) self.assertEqual( repr(queryset.query), "<RawQuery: SELECT * FROM raw_query_author>" ) def test_simple_raw_query(self): """ Basic test of raw query with a simple database query """ query = "SELECT * FROM raw_query_author" authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors) def test_raw_query_lazy(self): """ Raw queries are lazy: they aren't actually executed until they're iterated over. """ q = Author.objects.raw("SELECT * FROM raw_query_author") self.assertIsNone(q.query.cursor) list(q) self.assertIsNotNone(q.query.cursor) def test_FK_raw_query(self): """ Test of a simple raw query against a model containing a foreign key """ query = "SELECT * FROM raw_query_book" books = Book.objects.all() self.assertSuccessfulRawQuery(Book, query, books) def test_fk_fetch_mode_peers(self): query = "SELECT * FROM raw_query_book" books = list(Book.objects.fetch_mode(FETCH_PEERS).raw(query)) with self.assertNumQueries(1): books[0].author books[1].author def test_fk_fetch_mode_raise(self): query = "SELECT * FROM raw_query_book" books = list(Book.objects.fetch_mode(RAISE).raw(query)) msg = "Fetching of Book.author blocked." with self.assertRaisesMessage(FieldFetchBlocked, msg) as cm: books[0].author self.assertIsNone(cm.exception.__cause__) self.assertTrue(cm.exception.__suppress_context__) def test_db_column_handler(self): """ Test of a simple raw query against a model containing a field with db_column defined. """ query = "SELECT * FROM raw_query_coffee" coffees = Coffee.objects.all() self.assertSuccessfulRawQuery(Coffee, query, coffees) def test_pk_with_mixed_case_db_column(self): """ A raw query with a model that has a pk db_column with mixed case. """ query = "SELECT * FROM raw_query_mixedcaseidcolumn" queryset = MixedCaseIDColumn.objects.all() self.assertSuccessfulRawQuery(MixedCaseIDColumn, query, queryset) def test_order_handler(self): """Raw query tolerates columns being returned in any order.""" selects = ( ("dob, last_name, first_name, id"), ("last_name, dob, first_name, id"), ("first_name, last_name, dob, id"), ) for select in selects: query = "SELECT %s FROM raw_query_author" % select authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors) def test_translations(self): """ Test of raw query's optional ability to translate unexpected result column names to specific model fields """ query = ( "SELECT first_name AS first, last_name AS last, dob, id " "FROM raw_query_author" ) translations = {"first": "first_name", "last": "last_name"} authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors, translations=translations) def test_params(self): """ Test passing optional query parameters """ query = "SELECT * FROM raw_query_author WHERE first_name = %s" author = Author.objects.all()[2] params = [author.first_name] qset = Author.objects.raw(query, params=params) results = list(qset) self.assertProcessed(Author, results, [author]) self.assertNoAnnotations(results) self.assertEqual(len(results), 1) self.assertIsInstance(repr(qset), str) def test_params_none(self): query = "SELECT * FROM raw_query_author WHERE first_name like 'J%'" qset = Author.objects.raw(query, params=None) self.assertEqual(len(qset), 2) def test_escaped_percent(self): query = "SELECT * FROM raw_query_author WHERE first_name like 'J%%'" qset = Author.objects.raw(query) self.assertEqual(len(qset), 2) @skipUnlessDBFeature("supports_paramstyle_pyformat") def test_pyformat_params(self): """ Test passing optional query parameters """ query = "SELECT * FROM raw_query_author WHERE first_name = %(first)s" author = Author.objects.all()[2] params = {"first": author.first_name} qset = Author.objects.raw(query, params=params) results = list(qset) self.assertProcessed(Author, results, [author]) self.assertNoAnnotations(results) self.assertEqual(len(results), 1) self.assertIsInstance(repr(qset), str) def test_query_representation(self): """ Test representation of raw query with parameters """ query = "SELECT * FROM raw_query_author WHERE last_name = %(last)s" qset = Author.objects.raw(query, {"last": "foo"}) self.assertEqual( repr(qset), "<RawQuerySet: SELECT * FROM raw_query_author WHERE last_name = foo>", ) self.assertEqual( repr(qset.query), "<RawQuery: SELECT * FROM raw_query_author WHERE last_name = foo>", ) query = "SELECT * FROM raw_query_author WHERE last_name = %s" qset = Author.objects.raw(query, {"foo"}) self.assertEqual( repr(qset), "<RawQuerySet: SELECT * FROM raw_query_author WHERE last_name = foo>", ) self.assertEqual( repr(qset.query), "<RawQuery: SELECT * FROM raw_query_author WHERE last_name = foo>", ) def test_many_to_many(self): """ Test of a simple raw query against a model containing a m2m field """ query = "SELECT * FROM raw_query_reviewer" reviewers = Reviewer.objects.all() self.assertSuccessfulRawQuery(Reviewer, query, reviewers) def test_extra_conversions(self): """Extra translations are ignored.""" query = "SELECT * FROM raw_query_author" translations = {"something": "else"} authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors, translations=translations) def test_missing_fields(self): query = "SELECT id, first_name, dob FROM raw_query_author" for author in Author.objects.raw(query): self.assertIsNotNone(author.first_name) # last_name isn't given, but it will be retrieved on demand self.assertIsNotNone(author.last_name) def test_missing_fields_without_PK(self): query = "SELECT first_name, dob FROM raw_query_author" msg = "Raw query must include the primary key" with self.assertRaisesMessage(FieldDoesNotExist, msg): list(Author.objects.raw(query)) def test_missing_fields_fetch_mode_peers(self): query = "SELECT id, first_name, dob FROM raw_query_author" authors = list(Author.objects.fetch_mode(FETCH_PEERS).raw(query)) with self.assertNumQueries(1): authors[0].last_name authors[1].last_name def test_missing_fields_fetch_mode_raise(self): query = "SELECT id, first_name, dob FROM raw_query_author" authors = list(Author.objects.fetch_mode(RAISE).raw(query)) msg = "Fetching of Author.last_name blocked." with self.assertRaisesMessage(FieldFetchBlocked, msg) as cm: authors[0].last_name self.assertIsNone(cm.exception.__cause__) self.assertTrue(cm.exception.__suppress_context__) self.assertTrue(cm.exception.__suppress_context__) def test_annotations(self): query = ( "SELECT a.*, count(b.id) as book_count " "FROM raw_query_author a " "LEFT JOIN raw_query_book b ON a.id = b.author_id " "GROUP BY a.id, a.first_name, a.last_name, a.dob ORDER BY a.id" ) expected_annotations = ( ("book_count", 3), ("book_count", 0), ("book_count", 1), ("book_count", 0), ) authors = Author.objects.order_by("pk") self.assertSuccessfulRawQuery(Author, query, authors, expected_annotations) def test_white_space_query(self): query = " SELECT * FROM raw_query_author" authors = Author.objects.all() self.assertSuccessfulRawQuery(Author, query, authors) def test_multiple_iterations(self): query = "SELECT * FROM raw_query_author" normal_authors = Author.objects.all() raw_authors = Author.objects.raw(query) # First Iteration first_iterations = 0 for index, raw_author in enumerate(raw_authors): self.assertEqual(normal_authors[index], raw_author) first_iterations += 1 # Second Iteration second_iterations = 0 for index, raw_author in enumerate(raw_authors): self.assertEqual(normal_authors[index], raw_author) second_iterations += 1 self.assertEqual(first_iterations, second_iterations) def test_get_item(self): # Indexing on RawQuerySets query = "SELECT * FROM raw_query_author ORDER BY id ASC" third_author = Author.objects.raw(query)[2] self.assertEqual(third_author.first_name, "Bob") first_two = Author.objects.raw(query)[0:2] self.assertEqual(len(first_two), 2) with self.assertRaises(TypeError): Author.objects.raw(query)["test"] def test_inheritance(self): f = FriendlyAuthor.objects.create( first_name="Wesley", last_name="Chun", dob=date(1962, 10, 28) ) query = "SELECT * FROM raw_query_friendlyauthor" self.assertEqual([o.pk for o in FriendlyAuthor.objects.raw(query)], [f.pk]) def test_query_count(self): self.assertNumQueries( 1, list, Author.objects.raw("SELECT * FROM raw_query_author") ) def test_subquery_in_raw_sql(self): list( Book.objects.raw( "SELECT id FROM " "(SELECT * FROM raw_query_book WHERE paperback IS NOT NULL) sq" ) ) def test_db_column_name_is_used_in_raw_query(self): """ Regression test that ensures the `column` attribute on the field is used to generate the list of fields included in the query, as opposed to the `attname`. This is important when the primary key is a ForeignKey field because `attname` and `column` are not necessarily the same. """ b = BookFkAsPk.objects.create(book=self.b1) self.assertEqual( list( BookFkAsPk.objects.raw( "SELECT not_the_default FROM raw_query_bookfkaspk" ) ), [b], ) def test_decimal_parameter(self): c = Coffee.objects.create(brand="starbucks", price=20.5) qs = Coffee.objects.raw( "SELECT * FROM raw_query_coffee WHERE price >= %s", params=[Decimal(20)] ) self.assertEqual(list(qs), [c]) def test_result_caching(self): with self.assertNumQueries(1): books = Book.objects.raw("SELECT * FROM raw_query_book") list(books) list(books) def test_iterator(self): with self.assertNumQueries(2): books = Book.objects.raw("SELECT * FROM raw_query_book") list(books.iterator()) list(books.iterator()) def test_bool(self): self.assertIs(bool(Book.objects.raw("SELECT * FROM raw_query_book")), True) self.assertIs( bool(Book.objects.raw("SELECT * FROM raw_query_book WHERE id = 0")), False ) def test_len(self): self.assertEqual(len(Book.objects.raw("SELECT * FROM raw_query_book")), 4) self.assertEqual( len(Book.objects.raw("SELECT * FROM raw_query_book WHERE id = 0")), 0 )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/m2m_signals/models.py
tests/m2m_signals/models.py
from django.db import models class Part(models.Model): name = models.CharField(max_length=20) class Meta: ordering = ("name",) class Car(models.Model): name = models.CharField(max_length=20) default_parts = models.ManyToManyField(Part) optional_parts = models.ManyToManyField(Part, related_name="cars_optional") class Meta: ordering = ("name",) class SportsCar(Car): price = models.IntegerField() class Person(models.Model): name = models.CharField(max_length=20) fans = models.ManyToManyField("self", related_name="idols", symmetrical=False) friends = models.ManyToManyField("self") class Meta: ordering = ("name",)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/m2m_signals/__init__.py
tests/m2m_signals/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/m2m_signals/tests.py
tests/m2m_signals/tests.py
""" Testing signals emitted on changing m2m relations. """ from django.db import models from django.test import TestCase from .models import Car, Part, Person, SportsCar class ManyToManySignalsTest(TestCase): @classmethod def setUpTestData(cls): cls.vw = Car.objects.create(name="VW") cls.bmw = Car.objects.create(name="BMW") cls.toyota = Car.objects.create(name="Toyota") cls.wheelset = Part.objects.create(name="Wheelset") cls.doors = Part.objects.create(name="Doors") cls.engine = Part.objects.create(name="Engine") cls.airbag = Part.objects.create(name="Airbag") cls.sunroof = Part.objects.create(name="Sunroof") cls.alice = Person.objects.create(name="Alice") cls.bob = Person.objects.create(name="Bob") cls.chuck = Person.objects.create(name="Chuck") cls.daisy = Person.objects.create(name="Daisy") def setUp(self): self.m2m_changed_messages = [] def m2m_changed_signal_receiver(self, signal, sender, **kwargs): message = { "instance": kwargs["instance"], "action": kwargs["action"], "reverse": kwargs["reverse"], "model": kwargs["model"], "raw": kwargs["raw"], } if kwargs["pk_set"]: message["objects"] = list( kwargs["model"].objects.filter(pk__in=kwargs["pk_set"]) ) self.m2m_changed_messages.append(message) def tearDown(self): # disconnect all signal handlers models.signals.m2m_changed.disconnect( self.m2m_changed_signal_receiver, Car.default_parts.through ) models.signals.m2m_changed.disconnect( self.m2m_changed_signal_receiver, Car.optional_parts.through ) models.signals.m2m_changed.disconnect( self.m2m_changed_signal_receiver, Person.fans.through ) models.signals.m2m_changed.disconnect( self.m2m_changed_signal_receiver, Person.friends.through ) def _initialize_signal_car(self, add_default_parts_before_set_signal=False): """Install a listener on the two m2m relations.""" models.signals.m2m_changed.connect( self.m2m_changed_signal_receiver, Car.optional_parts.through ) if add_default_parts_before_set_signal: # adding a default part to our car - no signal listener installed self.vw.default_parts.add(self.sunroof) models.signals.m2m_changed.connect( self.m2m_changed_signal_receiver, Car.default_parts.through ) def test_pk_set_on_repeated_add_remove(self): """ m2m_changed is always fired, even for repeated calls to the same method, but the behavior of pk_sets differs by action. - For signals related to `add()`, only PKs that will actually be inserted are sent. - For `remove()` all PKs are sent, even if they will not affect the DB. """ pk_sets_sent = [] def handler(signal, sender, **kwargs): if kwargs["action"] in ["pre_add", "pre_remove"]: pk_sets_sent.append(kwargs["pk_set"]) models.signals.m2m_changed.connect(handler, Car.default_parts.through) self.vw.default_parts.add(self.wheelset) self.vw.default_parts.add(self.wheelset) self.vw.default_parts.remove(self.wheelset) self.vw.default_parts.remove(self.wheelset) expected_pk_sets = [ {self.wheelset.pk}, set(), {self.wheelset.pk}, {self.wheelset.pk}, ] self.assertEqual(pk_sets_sent, expected_pk_sets) models.signals.m2m_changed.disconnect(handler, Car.default_parts.through) def test_m2m_relations_add_remove_clear(self): expected_messages = [] self._initialize_signal_car(add_default_parts_before_set_signal=True) self.vw.default_parts.add(self.wheelset, self.doors, self.engine) expected_messages.append( { "instance": self.vw, "action": "pre_add", "reverse": False, "model": Part, "raw": False, "objects": [self.doors, self.engine, self.wheelset], } ) expected_messages.append( { "instance": self.vw, "action": "post_add", "reverse": False, "model": Part, "raw": False, "objects": [self.doors, self.engine, self.wheelset], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) # give the BMW and Toyota some doors as well self.doors.car_set.add(self.bmw, self.toyota) expected_messages.append( { "instance": self.doors, "action": "pre_add", "reverse": True, "model": Car, "raw": False, "objects": [self.bmw, self.toyota], } ) expected_messages.append( { "instance": self.doors, "action": "post_add", "reverse": True, "model": Car, "raw": False, "objects": [self.bmw, self.toyota], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) def test_m2m_relations_signals_remove_relation(self): self._initialize_signal_car() # remove the engine from the self.vw and the airbag (which is not set # but is returned) self.vw.default_parts.remove(self.engine, self.airbag) self.assertEqual( self.m2m_changed_messages, [ { "instance": self.vw, "action": "pre_remove", "reverse": False, "model": Part, "raw": False, "objects": [self.airbag, self.engine], }, { "instance": self.vw, "action": "post_remove", "reverse": False, "model": Part, "raw": False, "objects": [self.airbag, self.engine], }, ], ) def test_m2m_relations_signals_give_the_self_vw_some_optional_parts(self): expected_messages = [] self._initialize_signal_car() # give the self.vw some optional parts (second relation to same model) self.vw.optional_parts.add(self.airbag, self.sunroof) expected_messages.append( { "instance": self.vw, "action": "pre_add", "reverse": False, "model": Part, "raw": False, "objects": [self.airbag, self.sunroof], } ) expected_messages.append( { "instance": self.vw, "action": "post_add", "reverse": False, "model": Part, "raw": False, "objects": [self.airbag, self.sunroof], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) # add airbag to all the cars (even though the self.vw already has one) self.airbag.cars_optional.add(self.vw, self.bmw, self.toyota) expected_messages.append( { "instance": self.airbag, "action": "pre_add", "reverse": True, "model": Car, "raw": False, "objects": [self.bmw, self.toyota], } ) expected_messages.append( { "instance": self.airbag, "action": "post_add", "reverse": True, "model": Car, "raw": False, "objects": [self.bmw, self.toyota], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) def test_m2m_relations_signals_reverse_relation_with_custom_related_name(self): self._initialize_signal_car() # remove airbag from the self.vw (reverse relation with custom # related_name) self.airbag.cars_optional.remove(self.vw) self.assertEqual( self.m2m_changed_messages, [ { "instance": self.airbag, "action": "pre_remove", "reverse": True, "model": Car, "raw": False, "objects": [self.vw], }, { "instance": self.airbag, "action": "post_remove", "reverse": True, "model": Car, "raw": False, "objects": [self.vw], }, ], ) def test_m2m_relations_signals_clear_all_parts_of_the_self_vw(self): self._initialize_signal_car() # clear all parts of the self.vw self.vw.default_parts.clear() self.assertEqual( self.m2m_changed_messages, [ { "instance": self.vw, "action": "pre_clear", "reverse": False, "model": Part, "raw": False, }, { "instance": self.vw, "action": "post_clear", "reverse": False, "model": Part, "raw": False, }, ], ) def test_m2m_relations_signals_all_the_doors_off_of_cars(self): self._initialize_signal_car() # take all the doors off of cars self.doors.car_set.clear() self.assertEqual( self.m2m_changed_messages, [ { "instance": self.doors, "action": "pre_clear", "reverse": True, "model": Car, "raw": False, }, { "instance": self.doors, "action": "post_clear", "reverse": True, "model": Car, "raw": False, }, ], ) def test_m2m_relations_signals_reverse_relation(self): self._initialize_signal_car() # take all the airbags off of cars (clear reverse relation with custom # related_name) self.airbag.cars_optional.clear() self.assertEqual( self.m2m_changed_messages, [ { "instance": self.airbag, "action": "pre_clear", "reverse": True, "model": Car, "raw": False, }, { "instance": self.airbag, "action": "post_clear", "reverse": True, "model": Car, "raw": False, }, ], ) def test_m2m_relations_signals_alternative_ways(self): expected_messages = [] self._initialize_signal_car() # alternative ways of setting relation: self.vw.default_parts.create(name="Windows") p6 = Part.objects.get(name="Windows") expected_messages.append( { "instance": self.vw, "action": "pre_add", "reverse": False, "model": Part, "raw": False, "objects": [p6], } ) expected_messages.append( { "instance": self.vw, "action": "post_add", "reverse": False, "model": Part, "raw": False, "objects": [p6], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) # direct assignment clears the set first, then adds self.vw.default_parts.set([self.wheelset, self.doors, self.engine]) expected_messages.append( { "instance": self.vw, "action": "pre_remove", "reverse": False, "model": Part, "raw": False, "objects": [p6], } ) expected_messages.append( { "instance": self.vw, "action": "post_remove", "reverse": False, "model": Part, "raw": False, "objects": [p6], } ) expected_messages.append( { "instance": self.vw, "action": "pre_add", "reverse": False, "model": Part, "raw": False, "objects": [self.doors, self.engine, self.wheelset], } ) expected_messages.append( { "instance": self.vw, "action": "post_add", "reverse": False, "model": Part, "raw": False, "objects": [self.doors, self.engine, self.wheelset], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) def test_m2m_relations_signals_clearing_removing(self): expected_messages = [] self._initialize_signal_car(add_default_parts_before_set_signal=True) # set by clearing. self.vw.default_parts.set([self.wheelset, self.doors, self.engine], clear=True) expected_messages.append( { "instance": self.vw, "action": "pre_clear", "reverse": False, "model": Part, "raw": False, } ) expected_messages.append( { "instance": self.vw, "action": "post_clear", "reverse": False, "model": Part, "raw": False, } ) expected_messages.append( { "instance": self.vw, "action": "pre_add", "reverse": False, "model": Part, "raw": False, "objects": [self.doors, self.engine, self.wheelset], } ) expected_messages.append( { "instance": self.vw, "action": "post_add", "reverse": False, "model": Part, "raw": False, "objects": [self.doors, self.engine, self.wheelset], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) # set by only removing what's necessary. self.vw.default_parts.set([self.wheelset, self.doors], clear=False) expected_messages.append( { "instance": self.vw, "action": "pre_remove", "reverse": False, "model": Part, "raw": False, "objects": [self.engine], } ) expected_messages.append( { "instance": self.vw, "action": "post_remove", "reverse": False, "model": Part, "raw": False, "objects": [self.engine], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) def test_m2m_relations_signals_when_inheritance(self): expected_messages = [] self._initialize_signal_car(add_default_parts_before_set_signal=True) # Signals still work when model inheritance is involved c4 = SportsCar.objects.create(name="Bugatti", price="1000000") c4b = Car.objects.get(name="Bugatti") c4.default_parts.set([self.doors]) expected_messages.append( { "instance": c4, "action": "pre_add", "reverse": False, "model": Part, "raw": False, "objects": [self.doors], } ) expected_messages.append( { "instance": c4, "action": "post_add", "reverse": False, "model": Part, "raw": False, "objects": [self.doors], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) self.engine.car_set.add(c4) expected_messages.append( { "instance": self.engine, "action": "pre_add", "reverse": True, "model": Car, "raw": False, "objects": [c4b], } ) expected_messages.append( { "instance": self.engine, "action": "post_add", "reverse": True, "model": Car, "raw": False, "objects": [c4b], } ) self.assertEqual(self.m2m_changed_messages, expected_messages) def _initialize_signal_person(self): # Install a listener on the two m2m relations. models.signals.m2m_changed.connect( self.m2m_changed_signal_receiver, Person.fans.through ) models.signals.m2m_changed.connect( self.m2m_changed_signal_receiver, Person.friends.through ) def test_m2m_relations_with_self_add_friends(self): self._initialize_signal_person() self.alice.friends.set([self.bob, self.chuck]) self.assertEqual( self.m2m_changed_messages, [ { "instance": self.alice, "action": "pre_add", "reverse": False, "model": Person, "raw": False, "objects": [self.bob, self.chuck], }, { "instance": self.alice, "action": "post_add", "reverse": False, "model": Person, "raw": False, "objects": [self.bob, self.chuck], }, ], ) def test_m2m_relations_with_self_add_fan(self): self._initialize_signal_person() self.alice.fans.set([self.daisy]) self.assertEqual( self.m2m_changed_messages, [ { "instance": self.alice, "action": "pre_add", "reverse": False, "model": Person, "raw": False, "objects": [self.daisy], }, { "instance": self.alice, "action": "post_add", "reverse": False, "model": Person, "raw": False, "objects": [self.daisy], }, ], ) def test_m2m_relations_with_self_add_idols(self): self._initialize_signal_person() self.chuck.idols.set([self.alice, self.bob]) self.assertEqual( self.m2m_changed_messages, [ { "instance": self.chuck, "action": "pre_add", "reverse": True, "model": Person, "raw": False, "objects": [self.alice, self.bob], }, { "instance": self.chuck, "action": "post_add", "reverse": True, "model": Person, "raw": False, "objects": [self.alice, self.bob], }, ], ) def test_m2m_relations_set_base_raw(self): self.chuck.idols.add(self.daisy) self._initialize_signal_person() self.chuck.idols.set_base([self.alice, self.bob], raw=True) self.assertEqual( self.m2m_changed_messages, [ { "instance": self.chuck, "action": "pre_remove", "reverse": True, "model": Person, "raw": True, "objects": [self.daisy], }, { "instance": self.chuck, "action": "post_remove", "reverse": True, "model": Person, "raw": True, "objects": [self.daisy], }, { "instance": self.chuck, "action": "pre_add", "reverse": True, "model": Person, "raw": True, "objects": [self.alice, self.bob], }, { "instance": self.chuck, "action": "post_add", "reverse": True, "model": Person, "raw": True, "objects": [self.alice, self.bob], }, ], ) def test_m2m_relations_set_base_raw_clear(self): self.chuck.idols.set([self.daisy, self.bob]) self._initialize_signal_person() self.chuck.idols.set_base([self.alice, self.bob], clear=True, raw=True) self.assertEqual( self.m2m_changed_messages, [ { "instance": self.chuck, "action": "pre_clear", "reverse": True, "model": Person, "raw": True, }, { "instance": self.chuck, "action": "post_clear", "reverse": True, "model": Person, "raw": True, }, { "instance": self.chuck, "action": "pre_add", "reverse": True, "model": Person, "raw": True, "objects": [self.alice, self.bob], }, { "instance": self.chuck, "action": "post_add", "reverse": True, "model": Person, "raw": True, "objects": [self.alice, self.bob], }, ], )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false