hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
727f257001f4604d3221905feb08b53f69e46828d13e2929eef6b7dbeae434b9 | import datetime
from django.contrib.auth.models import User
from django.test import TestCase
from .models import Order, RevisionableModel, TestObject
class ExtraRegressTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.u = User.objects.create_user(
username="fred", password="secret", email="[email protected]"
)
def test_regression_7314_7372(self):
"""
Regression tests for #7314 and #7372
"""
rm = RevisionableModel.objects.create(
title="First Revision", when=datetime.datetime(2008, 9, 28, 10, 30, 0)
)
self.assertEqual(rm.pk, rm.base.pk)
rm2 = rm.new_revision()
rm2.title = "Second Revision"
rm.when = datetime.datetime(2008, 9, 28, 14, 25, 0)
rm2.save()
self.assertEqual(rm2.title, "Second Revision")
self.assertEqual(rm2.base.title, "First Revision")
self.assertNotEqual(rm2.pk, rm.pk)
self.assertEqual(rm2.base.pk, rm.pk)
# Queryset to match most recent revision:
qs = RevisionableModel.objects.extra(
where=[
"%(table)s.id IN "
"(SELECT MAX(rev.id) FROM %(table)s rev GROUP BY rev.base_id)"
% {
"table": RevisionableModel._meta.db_table,
}
]
)
self.assertQuerySetEqual(
qs,
[("Second Revision", "First Revision")],
transform=lambda r: (r.title, r.base.title),
)
# Queryset to search for string in title:
qs2 = RevisionableModel.objects.filter(title__contains="Revision")
self.assertQuerySetEqual(
qs2,
[
("First Revision", "First Revision"),
("Second Revision", "First Revision"),
],
transform=lambda r: (r.title, r.base.title),
ordered=False,
)
# Following queryset should return the most recent revision:
self.assertQuerySetEqual(
qs & qs2,
[("Second Revision", "First Revision")],
transform=lambda r: (r.title, r.base.title),
ordered=False,
)
def test_extra_stay_tied(self):
# Extra select parameters should stay tied to their corresponding
# select portions. Applies when portions are updated or otherwise
# moved around.
qs = User.objects.extra(
select={"alpha": "%s", "beta": "2", "gamma": "%s"}, select_params=(1, 3)
)
qs = qs.extra(select={"beta": 4})
qs = qs.extra(select={"alpha": "%s"}, select_params=[5])
self.assertEqual(
list(qs.filter(id=self.u.id).values("alpha", "beta", "gamma")),
[{"alpha": 5, "beta": 4, "gamma": 3}],
)
def test_regression_7957(self):
"""
Regression test for #7957: Combining extra() calls should leave the
corresponding parameters associated with the right extra() bit. I.e.
internal dictionary must remain sorted.
"""
self.assertEqual(
(
User.objects.extra(select={"alpha": "%s"}, select_params=(1,))
.extra(select={"beta": "%s"}, select_params=(2,))[0]
.alpha
),
1,
)
self.assertEqual(
(
User.objects.extra(select={"beta": "%s"}, select_params=(1,))
.extra(select={"alpha": "%s"}, select_params=(2,))[0]
.alpha
),
2,
)
def test_regression_7961(self):
"""
Regression test for #7961: When not using a portion of an
extra(...) in a query, remove any corresponding parameters from the
query as well.
"""
self.assertEqual(
list(
User.objects.extra(select={"alpha": "%s"}, select_params=(-6,))
.filter(id=self.u.id)
.values_list("id", flat=True)
),
[self.u.id],
)
def test_regression_8063(self):
"""
Regression test for #8063: limiting a query shouldn't discard any
extra() bits.
"""
qs = User.objects.extra(where=["id=%s"], params=[self.u.id])
self.assertSequenceEqual(qs, [self.u])
self.assertSequenceEqual(qs[:1], [self.u])
def test_regression_8039(self):
"""
Regression test for #8039: Ordering sometimes removed relevant tables
from extra(). This test is the critical case: ordering uses a table,
but then removes the reference because of an optimization. The table
should still be present because of the extra() call.
"""
self.assertQuerySetEqual(
(
Order.objects.extra(
where=["username=%s"], params=["fred"], tables=["auth_user"]
).order_by("created_by")
),
[],
)
def test_regression_8819(self):
"""
Regression test for #8819: Fields in the extra(select=...) list
should be available to extra(order_by=...).
"""
self.assertSequenceEqual(
User.objects.filter(pk=self.u.id)
.extra(select={"extra_field": 1})
.distinct(),
[self.u],
)
self.assertSequenceEqual(
User.objects.filter(pk=self.u.id).extra(
select={"extra_field": 1}, order_by=["extra_field"]
),
[self.u],
)
self.assertSequenceEqual(
User.objects.filter(pk=self.u.id)
.extra(select={"extra_field": 1}, order_by=["extra_field"])
.distinct(),
[self.u],
)
def test_dates_query(self):
"""
When calling the dates() method on a queryset with extra selection
columns, we can (and should) ignore those columns. They don't change
the result and cause incorrect SQL to be produced otherwise.
"""
RevisionableModel.objects.create(
title="First Revision", when=datetime.datetime(2008, 9, 28, 10, 30, 0)
)
self.assertSequenceEqual(
RevisionableModel.objects.extra(select={"the_answer": "id"}).datetimes(
"when", "month"
),
[datetime.datetime(2008, 9, 1, 0, 0)],
)
def test_values_with_extra(self):
"""
Regression test for #10256... If there is a values() clause, Extra
columns are only returned if they are explicitly mentioned.
"""
obj = TestObject(first="first", second="second", third="third")
obj.save()
self.assertEqual(
list(
TestObject.objects.extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
).values()
),
[
{
"bar": "second",
"third": "third",
"second": "second",
"whiz": "third",
"foo": "first",
"id": obj.pk,
"first": "first",
}
],
)
# Extra clauses after an empty values clause are still included
self.assertEqual(
list(
TestObject.objects.values().extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
)
),
[
{
"bar": "second",
"third": "third",
"second": "second",
"whiz": "third",
"foo": "first",
"id": obj.pk,
"first": "first",
}
],
)
# Extra columns are ignored if not mentioned in the values() clause
self.assertEqual(
list(
TestObject.objects.extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
).values("first", "second")
),
[{"second": "second", "first": "first"}],
)
# Extra columns after a non-empty values() clause are ignored
self.assertEqual(
list(
TestObject.objects.values("first", "second").extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
)
),
[{"second": "second", "first": "first"}],
)
# Extra columns can be partially returned
self.assertEqual(
list(
TestObject.objects.extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
).values("first", "second", "foo")
),
[{"second": "second", "foo": "first", "first": "first"}],
)
# Also works if only extra columns are included
self.assertEqual(
list(
TestObject.objects.extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
).values("foo", "whiz")
),
[{"foo": "first", "whiz": "third"}],
)
# Values list works the same way
# All columns are returned for an empty values_list()
self.assertEqual(
list(
TestObject.objects.extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
).values_list()
),
[("first", "second", "third", obj.pk, "first", "second", "third")],
)
# Extra columns after an empty values_list() are still included
self.assertEqual(
list(
TestObject.objects.values_list().extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
)
),
[("first", "second", "third", obj.pk, "first", "second", "third")],
)
# Extra columns ignored completely if not mentioned in values_list()
self.assertEqual(
list(
TestObject.objects.extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
).values_list("first", "second")
),
[("first", "second")],
)
# Extra columns after a non-empty values_list() clause are ignored completely
self.assertEqual(
list(
TestObject.objects.values_list("first", "second").extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
)
),
[("first", "second")],
)
self.assertEqual(
list(
TestObject.objects.extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
).values_list("second", flat=True)
),
["second"],
)
# Only the extra columns specified in the values_list() are returned
self.assertEqual(
list(
TestObject.objects.extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
).values_list("first", "second", "whiz")
),
[("first", "second", "third")],
)
# ...also works if only extra columns are included
self.assertEqual(
list(
TestObject.objects.extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
).values_list("foo", "whiz")
),
[("first", "third")],
)
self.assertEqual(
list(
TestObject.objects.extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
).values_list("whiz", flat=True)
),
["third"],
)
# ... and values are returned in the order they are specified
self.assertEqual(
list(
TestObject.objects.extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
).values_list("whiz", "foo")
),
[("third", "first")],
)
self.assertEqual(
list(
TestObject.objects.extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
).values_list("first", "id")
),
[("first", obj.pk)],
)
self.assertEqual(
list(
TestObject.objects.extra(
select={"foo": "first", "bar": "second", "whiz": "third"}
).values_list("whiz", "first", "bar", "id")
),
[("third", "first", "second", obj.pk)],
)
def test_regression_10847(self):
"""
Regression for #10847: the list of extra columns can always be
accurately evaluated. Using an inner query ensures that as_sql() is
producing correct output without requiring full evaluation and
execution of the inner query.
"""
obj = TestObject(first="first", second="second", third="third")
obj.save()
self.assertEqual(
list(TestObject.objects.extra(select={"extra": 1}).values("pk")),
[{"pk": obj.pk}],
)
self.assertSequenceEqual(
TestObject.objects.filter(
pk__in=TestObject.objects.extra(select={"extra": 1}).values("pk")
),
[obj],
)
self.assertEqual(
list(TestObject.objects.values("pk").extra(select={"extra": 1})),
[{"pk": obj.pk}],
)
self.assertSequenceEqual(
TestObject.objects.filter(
pk__in=TestObject.objects.values("pk").extra(select={"extra": 1})
),
[obj],
)
self.assertSequenceEqual(
TestObject.objects.filter(pk=obj.pk)
| TestObject.objects.extra(where=["id > %s"], params=[obj.pk]),
[obj],
)
def test_regression_17877(self):
"""
Extra WHERE clauses get correctly ANDed, even when they
contain OR operations.
"""
# Test Case 1: should appear in queryset.
t1 = TestObject.objects.create(first="a", second="a", third="a")
# Test Case 2: should appear in queryset.
t2 = TestObject.objects.create(first="b", second="a", third="a")
# Test Case 3: should not appear in queryset, bug case.
t = TestObject(first="a", second="a", third="b")
t.save()
# Test Case 4: should not appear in queryset.
t = TestObject(first="b", second="a", third="b")
t.save()
# Test Case 5: should not appear in queryset.
t = TestObject(first="b", second="b", third="a")
t.save()
# Test Case 6: should not appear in queryset, bug case.
t = TestObject(first="a", second="b", third="b")
t.save()
self.assertCountEqual(
TestObject.objects.extra(
where=["first = 'a' OR second = 'a'", "third = 'a'"],
),
[t1, t2],
)
def test_extra_values_distinct_ordering(self):
t1 = TestObject.objects.create(first="a", second="a", third="a")
t2 = TestObject.objects.create(first="a", second="b", third="b")
qs = (
TestObject.objects.extra(select={"second_extra": "second"})
.values_list("id", flat=True)
.distinct()
)
self.assertSequenceEqual(qs.order_by("second_extra"), [t1.pk, t2.pk])
self.assertSequenceEqual(qs.order_by("-second_extra"), [t2.pk, t1.pk])
# Note: the extra ordering must appear in select clause, so we get two
# non-distinct results here (this is on purpose, see #7070).
# Extra select doesn't appear in result values.
self.assertSequenceEqual(
qs.order_by("-second_extra").values_list("first"), [("a",), ("a",)]
)
|
7d3ce01187e33dbed57e4480596528130ae4a9e5b68536e772389ae69efb2d4f | from django.db import models
from django.test import TestCase
from .models import (
Book,
Car,
CustomManager,
CustomQuerySet,
DeconstructibleCustomManager,
FastCarAsBase,
FastCarAsDefault,
FunPerson,
OneToOneRestrictedModel,
Person,
PersonFromAbstract,
PersonManager,
PublishedBookManager,
RelatedModel,
RestrictedModel,
)
class CustomManagerTests(TestCase):
custom_manager_names = [
"custom_queryset_default_manager",
"custom_queryset_custom_manager",
]
@classmethod
def setUpTestData(cls):
cls.b1 = Book.published_objects.create(
title="How to program", author="Rodney Dangerfield", is_published=True
)
cls.b2 = Book.published_objects.create(
title="How to be smart", author="Albert Einstein", is_published=False
)
cls.p1 = Person.objects.create(first_name="Bugs", last_name="Bunny", fun=True)
cls.droopy = Person.objects.create(
first_name="Droopy", last_name="Dog", fun=False
)
def test_custom_manager_basic(self):
"""
Test a custom Manager method.
"""
self.assertQuerySetEqual(Person.objects.get_fun_people(), ["Bugs Bunny"], str)
def test_queryset_copied_to_default(self):
"""
The methods of a custom QuerySet are properly copied onto the
default Manager.
"""
for manager_name in self.custom_manager_names:
with self.subTest(manager_name=manager_name):
manager = getattr(Person, manager_name)
# Public methods are copied
manager.public_method()
# Private methods are not copied
with self.assertRaises(AttributeError):
manager._private_method()
def test_manager_honors_queryset_only(self):
for manager_name in self.custom_manager_names:
with self.subTest(manager_name=manager_name):
manager = getattr(Person, manager_name)
# Methods with queryset_only=False are copied even if they are private.
manager._optin_private_method()
# Methods with queryset_only=True aren't copied even if they are public.
msg = (
"%r object has no attribute 'optout_public_method'"
% manager.__class__.__name__
)
with self.assertRaisesMessage(AttributeError, msg):
manager.optout_public_method()
def test_manager_use_queryset_methods(self):
"""
Custom manager will use the queryset methods
"""
for manager_name in self.custom_manager_names:
with self.subTest(manager_name=manager_name):
manager = getattr(Person, manager_name)
queryset = manager.filter()
self.assertQuerySetEqual(queryset, ["Bugs Bunny"], str)
self.assertIs(queryset._filter_CustomQuerySet, True)
# Specialized querysets inherit from our custom queryset.
queryset = manager.values_list("first_name", flat=True).filter()
self.assertEqual(list(queryset), ["Bugs"])
self.assertIs(queryset._filter_CustomQuerySet, True)
self.assertIsInstance(queryset.values(), CustomQuerySet)
self.assertIsInstance(queryset.values().values(), CustomQuerySet)
self.assertIsInstance(queryset.values_list().values(), CustomQuerySet)
def test_init_args(self):
"""
The custom manager __init__() argument has been set.
"""
self.assertEqual(Person.custom_queryset_custom_manager.init_arg, "hello")
def test_manager_attributes(self):
"""
Custom manager method is only available on the manager and not on
querysets.
"""
Person.custom_queryset_custom_manager.manager_only()
msg = "'CustomQuerySet' object has no attribute 'manager_only'"
with self.assertRaisesMessage(AttributeError, msg):
Person.custom_queryset_custom_manager.all().manager_only()
def test_queryset_and_manager(self):
"""
Queryset method doesn't override the custom manager method.
"""
queryset = Person.custom_queryset_custom_manager.filter()
self.assertQuerySetEqual(queryset, ["Bugs Bunny"], str)
self.assertIs(queryset._filter_CustomManager, True)
def test_related_manager(self):
"""
The related managers extend the default manager.
"""
self.assertIsInstance(self.droopy.books, PublishedBookManager)
self.assertIsInstance(self.b2.authors, PersonManager)
def test_no_objects(self):
"""
The default manager, "objects", doesn't exist, because a custom one
was provided.
"""
msg = "type object 'Book' has no attribute 'objects'"
with self.assertRaisesMessage(AttributeError, msg):
Book.objects
def test_filtering(self):
"""
Custom managers respond to usual filtering methods
"""
self.assertQuerySetEqual(
Book.published_objects.all(),
[
"How to program",
],
lambda b: b.title,
)
def test_fk_related_manager(self):
Person.objects.create(
first_name="Bugs", last_name="Bunny", fun=True, favorite_book=self.b1
)
Person.objects.create(
first_name="Droopy", last_name="Dog", fun=False, favorite_book=self.b1
)
FunPerson.objects.create(
first_name="Bugs", last_name="Bunny", fun=True, favorite_book=self.b1
)
FunPerson.objects.create(
first_name="Droopy", last_name="Dog", fun=False, favorite_book=self.b1
)
self.assertQuerySetEqual(
self.b1.favorite_books.order_by("first_name").all(),
[
"Bugs",
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
self.assertQuerySetEqual(
self.b1.fun_people_favorite_books.all(),
[
"Bugs",
],
lambda c: c.first_name,
ordered=False,
)
self.assertQuerySetEqual(
self.b1.favorite_books(manager="boring_people").all(),
[
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
self.assertQuerySetEqual(
self.b1.favorite_books(manager="fun_people").all(),
[
"Bugs",
],
lambda c: c.first_name,
ordered=False,
)
def test_gfk_related_manager(self):
Person.objects.create(
first_name="Bugs", last_name="Bunny", fun=True, favorite_thing=self.b1
)
Person.objects.create(
first_name="Droopy", last_name="Dog", fun=False, favorite_thing=self.b1
)
FunPerson.objects.create(
first_name="Bugs", last_name="Bunny", fun=True, favorite_thing=self.b1
)
FunPerson.objects.create(
first_name="Droopy", last_name="Dog", fun=False, favorite_thing=self.b1
)
self.assertQuerySetEqual(
self.b1.favorite_things.all(),
[
"Bugs",
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
self.assertQuerySetEqual(
self.b1.fun_people_favorite_things.all(),
[
"Bugs",
],
lambda c: c.first_name,
ordered=False,
)
self.assertQuerySetEqual(
self.b1.favorite_things(manager="boring_people").all(),
[
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
self.assertQuerySetEqual(
self.b1.favorite_things(manager="fun_people").all(),
[
"Bugs",
],
lambda c: c.first_name,
ordered=False,
)
def test_m2m_related_manager(self):
bugs = Person.objects.create(first_name="Bugs", last_name="Bunny", fun=True)
self.b1.authors.add(bugs)
droopy = Person.objects.create(first_name="Droopy", last_name="Dog", fun=False)
self.b1.authors.add(droopy)
bugs = FunPerson.objects.create(first_name="Bugs", last_name="Bunny", fun=True)
self.b1.fun_authors.add(bugs)
droopy = FunPerson.objects.create(
first_name="Droopy", last_name="Dog", fun=False
)
self.b1.fun_authors.add(droopy)
self.assertQuerySetEqual(
self.b1.authors.order_by("first_name").all(),
[
"Bugs",
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
self.assertQuerySetEqual(
self.b1.fun_authors.order_by("first_name").all(),
[
"Bugs",
],
lambda c: c.first_name,
ordered=False,
)
self.assertQuerySetEqual(
self.b1.authors(manager="boring_people").all(),
[
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
self.assertQuerySetEqual(
self.b1.authors(manager="fun_people").all(),
[
"Bugs",
],
lambda c: c.first_name,
ordered=False,
)
def test_removal_through_default_fk_related_manager(self, bulk=True):
bugs = FunPerson.objects.create(
first_name="Bugs", last_name="Bunny", fun=True, favorite_book=self.b1
)
droopy = FunPerson.objects.create(
first_name="Droopy", last_name="Dog", fun=False, favorite_book=self.b1
)
self.b1.fun_people_favorite_books.remove(droopy, bulk=bulk)
self.assertQuerySetEqual(
FunPerson._base_manager.filter(favorite_book=self.b1),
[
"Bugs",
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
self.b1.fun_people_favorite_books.remove(bugs, bulk=bulk)
self.assertQuerySetEqual(
FunPerson._base_manager.filter(favorite_book=self.b1),
[
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
bugs.favorite_book = self.b1
bugs.save()
self.b1.fun_people_favorite_books.clear(bulk=bulk)
self.assertQuerySetEqual(
FunPerson._base_manager.filter(favorite_book=self.b1),
[
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
def test_slow_removal_through_default_fk_related_manager(self):
self.test_removal_through_default_fk_related_manager(bulk=False)
def test_removal_through_specified_fk_related_manager(self, bulk=True):
Person.objects.create(
first_name="Bugs", last_name="Bunny", fun=True, favorite_book=self.b1
)
droopy = Person.objects.create(
first_name="Droopy", last_name="Dog", fun=False, favorite_book=self.b1
)
# The fun manager DOESN'T remove boring people.
self.b1.favorite_books(manager="fun_people").remove(droopy, bulk=bulk)
self.assertQuerySetEqual(
self.b1.favorite_books(manager="boring_people").all(),
[
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
# The boring manager DOES remove boring people.
self.b1.favorite_books(manager="boring_people").remove(droopy, bulk=bulk)
self.assertQuerySetEqual(
self.b1.favorite_books(manager="boring_people").all(),
[],
lambda c: c.first_name,
ordered=False,
)
droopy.favorite_book = self.b1
droopy.save()
# The fun manager ONLY clears fun people.
self.b1.favorite_books(manager="fun_people").clear(bulk=bulk)
self.assertQuerySetEqual(
self.b1.favorite_books(manager="boring_people").all(),
[
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
self.assertQuerySetEqual(
self.b1.favorite_books(manager="fun_people").all(),
[],
lambda c: c.first_name,
ordered=False,
)
def test_slow_removal_through_specified_fk_related_manager(self):
self.test_removal_through_specified_fk_related_manager(bulk=False)
def test_removal_through_default_gfk_related_manager(self, bulk=True):
bugs = FunPerson.objects.create(
first_name="Bugs", last_name="Bunny", fun=True, favorite_thing=self.b1
)
droopy = FunPerson.objects.create(
first_name="Droopy", last_name="Dog", fun=False, favorite_thing=self.b1
)
self.b1.fun_people_favorite_things.remove(droopy, bulk=bulk)
self.assertQuerySetEqual(
FunPerson._base_manager.order_by("first_name").filter(
favorite_thing_id=self.b1.pk
),
[
"Bugs",
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
self.b1.fun_people_favorite_things.remove(bugs, bulk=bulk)
self.assertQuerySetEqual(
FunPerson._base_manager.order_by("first_name").filter(
favorite_thing_id=self.b1.pk
),
[
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
bugs.favorite_book = self.b1
bugs.save()
self.b1.fun_people_favorite_things.clear(bulk=bulk)
self.assertQuerySetEqual(
FunPerson._base_manager.order_by("first_name").filter(
favorite_thing_id=self.b1.pk
),
[
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
def test_slow_removal_through_default_gfk_related_manager(self):
self.test_removal_through_default_gfk_related_manager(bulk=False)
def test_removal_through_specified_gfk_related_manager(self, bulk=True):
Person.objects.create(
first_name="Bugs", last_name="Bunny", fun=True, favorite_thing=self.b1
)
droopy = Person.objects.create(
first_name="Droopy", last_name="Dog", fun=False, favorite_thing=self.b1
)
# The fun manager DOESN'T remove boring people.
self.b1.favorite_things(manager="fun_people").remove(droopy, bulk=bulk)
self.assertQuerySetEqual(
self.b1.favorite_things(manager="boring_people").all(),
[
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
# The boring manager DOES remove boring people.
self.b1.favorite_things(manager="boring_people").remove(droopy, bulk=bulk)
self.assertQuerySetEqual(
self.b1.favorite_things(manager="boring_people").all(),
[],
lambda c: c.first_name,
ordered=False,
)
droopy.favorite_thing = self.b1
droopy.save()
# The fun manager ONLY clears fun people.
self.b1.favorite_things(manager="fun_people").clear(bulk=bulk)
self.assertQuerySetEqual(
self.b1.favorite_things(manager="boring_people").all(),
[
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
self.assertQuerySetEqual(
self.b1.favorite_things(manager="fun_people").all(),
[],
lambda c: c.first_name,
ordered=False,
)
def test_slow_removal_through_specified_gfk_related_manager(self):
self.test_removal_through_specified_gfk_related_manager(bulk=False)
def test_removal_through_default_m2m_related_manager(self):
bugs = FunPerson.objects.create(first_name="Bugs", last_name="Bunny", fun=True)
self.b1.fun_authors.add(bugs)
droopy = FunPerson.objects.create(
first_name="Droopy", last_name="Dog", fun=False
)
self.b1.fun_authors.add(droopy)
self.b1.fun_authors.remove(droopy)
self.assertQuerySetEqual(
self.b1.fun_authors.through._default_manager.all(),
[
"Bugs",
"Droopy",
],
lambda c: c.funperson.first_name,
ordered=False,
)
self.b1.fun_authors.remove(bugs)
self.assertQuerySetEqual(
self.b1.fun_authors.through._default_manager.all(),
[
"Droopy",
],
lambda c: c.funperson.first_name,
ordered=False,
)
self.b1.fun_authors.add(bugs)
self.b1.fun_authors.clear()
self.assertQuerySetEqual(
self.b1.fun_authors.through._default_manager.all(),
[
"Droopy",
],
lambda c: c.funperson.first_name,
ordered=False,
)
def test_removal_through_specified_m2m_related_manager(self):
bugs = Person.objects.create(first_name="Bugs", last_name="Bunny", fun=True)
self.b1.authors.add(bugs)
droopy = Person.objects.create(first_name="Droopy", last_name="Dog", fun=False)
self.b1.authors.add(droopy)
# The fun manager DOESN'T remove boring people.
self.b1.authors(manager="fun_people").remove(droopy)
self.assertQuerySetEqual(
self.b1.authors(manager="boring_people").all(),
[
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
# The boring manager DOES remove boring people.
self.b1.authors(manager="boring_people").remove(droopy)
self.assertQuerySetEqual(
self.b1.authors(manager="boring_people").all(),
[],
lambda c: c.first_name,
ordered=False,
)
self.b1.authors.add(droopy)
# The fun manager ONLY clears fun people.
self.b1.authors(manager="fun_people").clear()
self.assertQuerySetEqual(
self.b1.authors(manager="boring_people").all(),
[
"Droopy",
],
lambda c: c.first_name,
ordered=False,
)
self.assertQuerySetEqual(
self.b1.authors(manager="fun_people").all(),
[],
lambda c: c.first_name,
ordered=False,
)
def test_deconstruct_default(self):
mgr = models.Manager()
as_manager, mgr_path, qs_path, args, kwargs = mgr.deconstruct()
self.assertFalse(as_manager)
self.assertEqual(mgr_path, "django.db.models.manager.Manager")
self.assertEqual(args, ())
self.assertEqual(kwargs, {})
def test_deconstruct_as_manager(self):
mgr = CustomQuerySet.as_manager()
as_manager, mgr_path, qs_path, args, kwargs = mgr.deconstruct()
self.assertTrue(as_manager)
self.assertEqual(qs_path, "custom_managers.models.CustomQuerySet")
def test_deconstruct_from_queryset(self):
mgr = DeconstructibleCustomManager("a", "b")
as_manager, mgr_path, qs_path, args, kwargs = mgr.deconstruct()
self.assertFalse(as_manager)
self.assertEqual(
mgr_path, "custom_managers.models.DeconstructibleCustomManager"
)
self.assertEqual(
args,
(
"a",
"b",
),
)
self.assertEqual(kwargs, {})
mgr = DeconstructibleCustomManager("x", "y", c=3, d=4)
as_manager, mgr_path, qs_path, args, kwargs = mgr.deconstruct()
self.assertFalse(as_manager)
self.assertEqual(
mgr_path, "custom_managers.models.DeconstructibleCustomManager"
)
self.assertEqual(
args,
(
"x",
"y",
),
)
self.assertEqual(kwargs, {"c": 3, "d": 4})
def test_deconstruct_from_queryset_failing(self):
mgr = CustomManager("arg")
msg = (
"Could not find manager BaseCustomManagerFromCustomQuerySet in "
"django.db.models.manager.\n"
"Please note that you need to inherit from managers you "
"dynamically generated with 'from_queryset()'."
)
with self.assertRaisesMessage(ValueError, msg):
mgr.deconstruct()
def test_abstract_model_with_custom_manager_name(self):
"""
A custom manager may be defined on an abstract model.
It will be inherited by the abstract model's children.
"""
PersonFromAbstract.abstract_persons.create(objects="Test")
self.assertQuerySetEqual(
PersonFromAbstract.abstract_persons.all(),
["Test"],
lambda c: c.objects,
)
class TestCars(TestCase):
def test_managers(self):
# Each model class gets a "_default_manager" attribute, which is a
# reference to the first manager defined in the class.
Car.cars.create(name="Corvette", mileage=21, top_speed=180)
Car.cars.create(name="Neon", mileage=31, top_speed=100)
self.assertQuerySetEqual(
Car._default_manager.order_by("name"),
[
"Corvette",
"Neon",
],
lambda c: c.name,
)
self.assertQuerySetEqual(
Car.cars.order_by("name"),
[
"Corvette",
"Neon",
],
lambda c: c.name,
)
# alternate manager
self.assertQuerySetEqual(
Car.fast_cars.all(),
[
"Corvette",
],
lambda c: c.name,
)
# explicit default manager
self.assertQuerySetEqual(
FastCarAsDefault.cars.order_by("name"),
[
"Corvette",
"Neon",
],
lambda c: c.name,
)
self.assertQuerySetEqual(
FastCarAsDefault._default_manager.all(),
[
"Corvette",
],
lambda c: c.name,
)
# explicit base manager
self.assertQuerySetEqual(
FastCarAsBase.cars.order_by("name"),
[
"Corvette",
"Neon",
],
lambda c: c.name,
)
self.assertQuerySetEqual(
FastCarAsBase._base_manager.all(),
[
"Corvette",
],
lambda c: c.name,
)
class CustomManagersRegressTestCase(TestCase):
def test_filtered_default_manager(self):
"""Even though the default manager filters out some records,
we must still be able to save (particularly, save by updating
existing records) those filtered instances. This is a
regression test for #8990, #9527"""
related = RelatedModel.objects.create(name="xyzzy")
obj = RestrictedModel.objects.create(name="hidden", related=related)
obj.name = "still hidden"
obj.save()
# If the hidden object wasn't seen during the save process,
# there would now be two objects in the database.
self.assertEqual(RestrictedModel.plain_manager.count(), 1)
def test_refresh_from_db_when_default_manager_filters(self):
"""
Model.refresh_from_db() works for instances hidden by the default
manager.
"""
book = Book._base_manager.create(is_published=False)
Book._base_manager.filter(pk=book.pk).update(title="Hi")
book.refresh_from_db()
self.assertEqual(book.title, "Hi")
def test_save_clears_annotations_from_base_manager(self):
"""Model.save() clears annotations from the base manager."""
self.assertEqual(Book._meta.base_manager.name, "annotated_objects")
book = Book.annotated_objects.create(title="Hunting")
Person.objects.create(
first_name="Bugs",
last_name="Bunny",
fun=True,
favorite_book=book,
favorite_thing_id=1,
)
book = Book.annotated_objects.first()
self.assertEqual(book.favorite_avg, 1) # Annotation from the manager.
book.title = "New Hunting"
# save() fails if annotations that involve related fields aren't
# cleared before the update query.
book.save()
self.assertEqual(Book.annotated_objects.first().title, "New Hunting")
def test_delete_related_on_filtered_manager(self):
"""Deleting related objects should also not be distracted by a
restricted manager on the related object. This is a regression
test for #2698."""
related = RelatedModel.objects.create(name="xyzzy")
for name, public in (("one", True), ("two", False), ("three", False)):
RestrictedModel.objects.create(name=name, is_public=public, related=related)
obj = RelatedModel.objects.get(name="xyzzy")
obj.delete()
# All of the RestrictedModel instances should have been
# deleted, since they *all* pointed to the RelatedModel. If
# the default manager is used, only the public one will be
# deleted.
self.assertEqual(len(RestrictedModel.plain_manager.all()), 0)
def test_delete_one_to_one_manager(self):
# The same test case as the last one, but for one-to-one
# models, which are implemented slightly different internally,
# so it's a different code path.
obj = RelatedModel.objects.create(name="xyzzy")
OneToOneRestrictedModel.objects.create(name="foo", is_public=False, related=obj)
obj = RelatedModel.objects.get(name="xyzzy")
obj.delete()
self.assertEqual(len(OneToOneRestrictedModel.plain_manager.all()), 0)
def test_queryset_with_custom_init(self):
"""
BaseManager.get_queryset() should use kwargs rather than args to allow
custom kwargs (#24911).
"""
qs_custom = Person.custom_init_queryset_manager.all()
qs_default = Person.objects.all()
self.assertQuerySetEqual(qs_custom, qs_default)
|
c59b9569829d3c23b472712d8d0053c3396789782c343e17c01487b7becf0aed | """
Giving models a custom manager
You can use a custom ``Manager`` in a particular model by extending the base
``Manager`` class and instantiating your custom ``Manager`` in your model.
There are two reasons you might want to customize a ``Manager``: to add extra
``Manager`` methods, and/or to modify the initial ``QuerySet`` the ``Manager``
returns.
"""
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.db import models
class PersonManager(models.Manager):
def get_fun_people(self):
return self.filter(fun=True)
class PublishedBookManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(is_published=True)
class AnnotatedBookManager(models.Manager):
def get_queryset(self):
return (
super()
.get_queryset()
.annotate(favorite_avg=models.Avg("favorite_books__favorite_thing_id"))
)
class CustomQuerySet(models.QuerySet):
def filter(self, *args, **kwargs):
queryset = super().filter(fun=True)
queryset._filter_CustomQuerySet = True
return queryset
def public_method(self, *args, **kwargs):
return self.all()
def _private_method(self, *args, **kwargs):
return self.all()
def optout_public_method(self, *args, **kwargs):
return self.all()
optout_public_method.queryset_only = True
def _optin_private_method(self, *args, **kwargs):
return self.all()
_optin_private_method.queryset_only = False
class BaseCustomManager(models.Manager):
def __init__(self, arg):
super().__init__()
self.init_arg = arg
def filter(self, *args, **kwargs):
queryset = super().filter(fun=True)
queryset._filter_CustomManager = True
return queryset
def manager_only(self):
return self.all()
CustomManager = BaseCustomManager.from_queryset(CustomQuerySet)
class CustomInitQuerySet(models.QuerySet):
# QuerySet with an __init__() method that takes an additional argument.
def __init__(
self, custom_optional_arg=None, model=None, query=None, using=None, hints=None
):
super().__init__(model=model, query=query, using=using, hints=hints)
class DeconstructibleCustomManager(BaseCustomManager.from_queryset(CustomQuerySet)):
def __init__(self, a, b, c=1, d=2):
super().__init__(a)
class FunPeopleManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(fun=True)
class BoringPeopleManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(fun=False)
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
fun = models.BooleanField(default=False)
favorite_book = models.ForeignKey(
"Book", models.SET_NULL, null=True, related_name="favorite_books"
)
favorite_thing_type = models.ForeignKey(
"contenttypes.ContentType", models.SET_NULL, null=True
)
favorite_thing_id = models.IntegerField(null=True)
favorite_thing = GenericForeignKey("favorite_thing_type", "favorite_thing_id")
objects = PersonManager()
fun_people = FunPeopleManager()
boring_people = BoringPeopleManager()
custom_queryset_default_manager = CustomQuerySet.as_manager()
custom_queryset_custom_manager = CustomManager("hello")
custom_init_queryset_manager = CustomInitQuerySet.as_manager()
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
class FunPerson(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
fun = models.BooleanField(default=True)
favorite_book = models.ForeignKey(
"Book",
models.SET_NULL,
null=True,
related_name="fun_people_favorite_books",
)
favorite_thing_type = models.ForeignKey(
"contenttypes.ContentType", models.SET_NULL, null=True
)
favorite_thing_id = models.IntegerField(null=True)
favorite_thing = GenericForeignKey("favorite_thing_type", "favorite_thing_id")
objects = FunPeopleManager()
class Book(models.Model):
title = models.CharField(max_length=50)
author = models.CharField(max_length=30)
is_published = models.BooleanField(default=False)
authors = models.ManyToManyField(Person, related_name="books")
fun_authors = models.ManyToManyField(FunPerson, related_name="books")
favorite_things = GenericRelation(
Person,
content_type_field="favorite_thing_type",
object_id_field="favorite_thing_id",
)
fun_people_favorite_things = GenericRelation(
FunPerson,
content_type_field="favorite_thing_type",
object_id_field="favorite_thing_id",
)
published_objects = PublishedBookManager()
annotated_objects = AnnotatedBookManager()
class Meta:
base_manager_name = "annotated_objects"
class FastCarManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(top_speed__gt=150)
class Car(models.Model):
name = models.CharField(max_length=10)
mileage = models.IntegerField()
top_speed = models.IntegerField(help_text="In miles per hour.")
cars = models.Manager()
fast_cars = FastCarManager()
class FastCarAsBase(Car):
class Meta:
proxy = True
base_manager_name = "fast_cars"
class FastCarAsDefault(Car):
class Meta:
proxy = True
default_manager_name = "fast_cars"
class RestrictedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(is_public=True)
class RelatedModel(models.Model):
name = models.CharField(max_length=50)
class RestrictedModel(models.Model):
name = models.CharField(max_length=50)
is_public = models.BooleanField(default=False)
related = models.ForeignKey(RelatedModel, models.CASCADE)
objects = RestrictedManager()
plain_manager = models.Manager()
class OneToOneRestrictedModel(models.Model):
name = models.CharField(max_length=50)
is_public = models.BooleanField(default=False)
related = models.OneToOneField(RelatedModel, models.CASCADE)
objects = RestrictedManager()
plain_manager = models.Manager()
class AbstractPerson(models.Model):
abstract_persons = models.Manager()
objects = models.CharField(max_length=30)
class Meta:
abstract = True
class PersonFromAbstract(AbstractPerson):
pass
|
a135f9e0fbd2eac9f7eae357d707457e85912877db777a6e5aab10b5a94b1798 | """
A series of tests to establish that the command-line management tools work as
advertised - especially with regards to the handling of the
DJANGO_SETTINGS_MODULE and default settings.py files.
"""
import os
import re
import shutil
import socket
import stat
import subprocess
import sys
import tempfile
import unittest
from io import StringIO
from unittest import mock
from django import conf, get_version
from django.conf import settings
from django.core.management import (
BaseCommand,
CommandError,
call_command,
color,
execute_from_command_line,
)
from django.core.management.commands.loaddata import Command as LoaddataCommand
from django.core.management.commands.runserver import Command as RunserverCommand
from django.core.management.commands.testserver import Command as TestserverCommand
from django.db import ConnectionHandler, connection
from django.db.migrations.recorder import MigrationRecorder
from django.test import LiveServerTestCase, SimpleTestCase, TestCase, override_settings
from django.test.utils import captured_stderr, captured_stdout
from django.urls import path
from django.utils.version import PY39
from django.views.static import serve
from . import urls
custom_templates_dir = os.path.join(os.path.dirname(__file__), "custom_templates")
SYSTEM_CHECK_MSG = "System check identified no issues"
HAS_BLACK = shutil.which("black")
class AdminScriptTestCase(SimpleTestCase):
def setUp(self):
tmpdir = tempfile.TemporaryDirectory()
self.addCleanup(tmpdir.cleanup)
# os.path.realpath() is required for temporary directories on macOS,
# where `/var` is a symlink to `/private/var`.
self.test_dir = os.path.realpath(os.path.join(tmpdir.name, "test_project"))
os.mkdir(self.test_dir)
def write_settings(self, filename, apps=None, is_dir=False, sdict=None, extra=None):
if is_dir:
settings_dir = os.path.join(self.test_dir, filename)
os.mkdir(settings_dir)
settings_file_path = os.path.join(settings_dir, "__init__.py")
else:
settings_file_path = os.path.join(self.test_dir, filename)
with open(settings_file_path, "w") as settings_file:
settings_file.write(
"# Settings file automatically generated by admin_scripts test case\n"
)
if extra:
settings_file.write("%s\n" % extra)
exports = [
"DATABASES",
"DEFAULT_AUTO_FIELD",
"ROOT_URLCONF",
"SECRET_KEY",
"USE_TZ",
]
for s in exports:
if hasattr(settings, s):
o = getattr(settings, s)
if not isinstance(o, (dict, tuple, list)):
o = "'%s'" % o
settings_file.write("%s = %s\n" % (s, o))
if apps is None:
apps = [
"django.contrib.auth",
"django.contrib.contenttypes",
"admin_scripts",
]
settings_file.write("INSTALLED_APPS = %s\n" % apps)
if sdict:
for k, v in sdict.items():
settings_file.write("%s = %s\n" % (k, v))
def _ext_backend_paths(self):
"""
Returns the paths for any external backend packages.
"""
paths = []
for backend in settings.DATABASES.values():
package = backend["ENGINE"].split(".")[0]
if package != "django":
backend_pkg = __import__(package)
backend_dir = os.path.dirname(backend_pkg.__file__)
paths.append(os.path.dirname(backend_dir))
return paths
def run_test(self, args, settings_file=None, apps=None, umask=None):
base_dir = os.path.dirname(self.test_dir)
# The base dir for Django's tests is one level up.
tests_dir = os.path.dirname(os.path.dirname(__file__))
# The base dir for Django is one level above the test dir. We don't use
# `import django` to figure that out, so we don't pick up a Django
# from site-packages or similar.
django_dir = os.path.dirname(tests_dir)
ext_backend_base_dirs = self._ext_backend_paths()
# Define a temporary environment for the subprocess
test_environ = os.environ.copy()
# Set the test environment
if settings_file:
test_environ["DJANGO_SETTINGS_MODULE"] = settings_file
elif "DJANGO_SETTINGS_MODULE" in test_environ:
del test_environ["DJANGO_SETTINGS_MODULE"]
python_path = [base_dir, django_dir, tests_dir]
python_path.extend(ext_backend_base_dirs)
test_environ["PYTHONPATH"] = os.pathsep.join(python_path)
test_environ["PYTHONWARNINGS"] = ""
p = subprocess.run(
[sys.executable, *args],
capture_output=True,
cwd=self.test_dir,
env=test_environ,
text=True,
# subprocess.run()'s umask was added in Python 3.9.
**({"umask": umask} if umask and PY39 else {}),
)
return p.stdout, p.stderr
def run_django_admin(self, args, settings_file=None, umask=None):
return self.run_test(["-m", "django", *args], settings_file, umask=umask)
def run_manage(self, args, settings_file=None, manage_py=None):
template_manage_py = (
os.path.join(os.path.dirname(__file__), manage_py)
if manage_py
else os.path.join(
os.path.dirname(conf.__file__), "project_template", "manage.py-tpl"
)
)
test_manage_py = os.path.join(self.test_dir, "manage.py")
shutil.copyfile(template_manage_py, test_manage_py)
with open(test_manage_py) as fp:
manage_py_contents = fp.read()
manage_py_contents = manage_py_contents.replace(
"{{ project_name }}", "test_project"
)
with open(test_manage_py, "w") as fp:
fp.write(manage_py_contents)
return self.run_test(["./manage.py", *args], settings_file)
def assertNoOutput(self, stream):
"Utility assertion: assert that the given stream is empty"
self.assertEqual(
len(stream), 0, "Stream should be empty: actually contains '%s'" % stream
)
def assertOutput(self, stream, msg, regex=False):
"Utility assertion: assert that the given message exists in the output"
if regex:
self.assertIsNotNone(
re.search(msg, stream),
"'%s' does not match actual output text '%s'" % (msg, stream),
)
else:
self.assertIn(
msg,
stream,
"'%s' does not match actual output text '%s'" % (msg, stream),
)
def assertNotInOutput(self, stream, msg):
"Utility assertion: assert that the given message doesn't exist in the output"
self.assertNotIn(
msg, stream, "'%s' matches actual output text '%s'" % (msg, stream)
)
##########################################################################
# DJANGO ADMIN TESTS
# This first series of test classes checks the environment processing
# of the django-admin.
##########################################################################
class DjangoAdminNoSettings(AdminScriptTestCase):
"A series of tests for django-admin when there is no settings.py file."
def test_builtin_command(self):
"""
no settings: django-admin builtin commands fail with an error when no
settings provided.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_bad_settings(self):
"""
no settings: django-admin builtin commands fail if settings file (from
argument) doesn't exist.
"""
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
"""
no settings: django-admin builtin commands fail if settings file (from
environment) doesn't exist.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_commands_with_invalid_settings(self):
"""
Commands that don't require settings succeed if the settings file
doesn't exist.
"""
args = ["startproject"]
out, err = self.run_django_admin(args, settings_file="bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "You must provide a project name", regex=True)
class DjangoAdminDefaultSettings(AdminScriptTestCase):
"""
A series of tests for django-admin when using a settings.py file that
contains the test application.
"""
def setUp(self):
super().setUp()
self.write_settings("settings.py")
def test_builtin_command(self):
"""
default: django-admin builtin commands fail with an error when no
settings provided.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_settings(self):
"""
default: django-admin builtin commands succeed if settings are provided
as argument.
"""
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
"""
default: django-admin builtin commands succeed if settings are provided
in the environment.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
"""
default: django-admin builtin commands fail if settings file (from
argument) doesn't exist.
"""
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
"""
default: django-admin builtin commands fail if settings file (from
environment) doesn't exist.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
"""
default: django-admin can't execute user commands if it isn't provided
settings.
"""
args = ["noargs_command"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No Django settings specified")
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
"""
default: django-admin can execute user commands if settings are
provided as argument.
"""
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
"""
default: django-admin can execute user commands if settings are
provided in environment.
"""
args = ["noargs_command"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase):
"""
A series of tests for django-admin when using a settings.py file that
contains the test application specified using a full path.
"""
def setUp(self):
super().setUp()
self.write_settings(
"settings.py",
[
"django.contrib.auth",
"django.contrib.contenttypes",
"admin_scripts",
"admin_scripts.complex_app",
],
)
def test_builtin_command(self):
"""
fulldefault: django-admin builtin commands fail with an error when no
settings provided.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_settings(self):
"""
fulldefault: django-admin builtin commands succeed if a settings file
is provided.
"""
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
"""
fulldefault: django-admin builtin commands succeed if the environment
contains settings.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
"""
fulldefault: django-admin builtin commands fail if settings file (from
argument) doesn't exist.
"""
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
"""
fulldefault: django-admin builtin commands fail if settings file (from
environment) doesn't exist.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
"""
fulldefault: django-admin can't execute user commands unless settings
are provided.
"""
args = ["noargs_command"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No Django settings specified")
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
"""
fulldefault: django-admin can execute user commands if settings are
provided as argument.
"""
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
"""
fulldefault: django-admin can execute user commands if settings are
provided in environment.
"""
args = ["noargs_command"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
class DjangoAdminMinimalSettings(AdminScriptTestCase):
"""
A series of tests for django-admin when using a settings.py file that
doesn't contain the test application.
"""
def setUp(self):
super().setUp()
self.write_settings(
"settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"]
)
def test_builtin_command(self):
"""
minimal: django-admin builtin commands fail with an error when no
settings provided.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_settings(self):
"""
minimal: django-admin builtin commands fail if settings are provided as
argument.
"""
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No installed app with label 'admin_scripts'.")
def test_builtin_with_environment(self):
"""
minimal: django-admin builtin commands fail if settings are provided in
the environment.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(out)
self.assertOutput(err, "No installed app with label 'admin_scripts'.")
def test_builtin_with_bad_settings(self):
"""
minimal: django-admin builtin commands fail if settings file (from
argument) doesn't exist.
"""
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
"""
minimal: django-admin builtin commands fail if settings file (from
environment) doesn't exist.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
"minimal: django-admin can't execute user commands unless settings are provided"
args = ["noargs_command"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No Django settings specified")
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
"""
minimal: django-admin can't execute user commands, even if settings are
provided as argument.
"""
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_environment(self):
"""
minimal: django-admin can't execute user commands, even if settings are
provided in environment.
"""
args = ["noargs_command"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'noargs_command'")
class DjangoAdminAlternateSettings(AdminScriptTestCase):
"""
A series of tests for django-admin when using a settings file with a name
other than 'settings.py'.
"""
def setUp(self):
super().setUp()
self.write_settings("alternate_settings.py")
def test_builtin_command(self):
"""
alternate: django-admin builtin commands fail with an error when no
settings provided.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_settings(self):
"""
alternate: django-admin builtin commands succeed if settings are
provided as argument.
"""
args = ["check", "--settings=test_project.alternate_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
"""
alternate: django-admin builtin commands succeed if settings are
provided in the environment.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.alternate_settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
"""
alternate: django-admin builtin commands fail if settings file (from
argument) doesn't exist.
"""
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
"""
alternate: django-admin builtin commands fail if settings file (from
environment) doesn't exist.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
"""
alternate: django-admin can't execute user commands unless settings
are provided.
"""
args = ["noargs_command"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No Django settings specified")
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
"""
alternate: django-admin can execute user commands if settings are
provided as argument.
"""
args = ["noargs_command", "--settings=test_project.alternate_settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
"""
alternate: django-admin can execute user commands if settings are
provided in environment.
"""
args = ["noargs_command"]
out, err = self.run_django_admin(args, "test_project.alternate_settings")
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
class DjangoAdminMultipleSettings(AdminScriptTestCase):
"""
A series of tests for django-admin when multiple settings files
(including the default 'settings.py') are available. The default settings
file is insufficient for performing the operations described, so the
alternate settings must be used by the running script.
"""
def setUp(self):
super().setUp()
self.write_settings(
"settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"]
)
self.write_settings("alternate_settings.py")
def test_builtin_command(self):
"""
alternate: django-admin builtin commands fail with an error when no
settings provided.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_settings(self):
"""
alternate: django-admin builtin commands succeed if settings are
provided as argument.
"""
args = ["check", "--settings=test_project.alternate_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
"""
alternate: django-admin builtin commands succeed if settings are
provided in the environment.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.alternate_settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
"""
alternate: django-admin builtin commands fail if settings file (from
argument) doesn't exist.
"""
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
"""
alternate: django-admin builtin commands fail if settings file (from
environment) doesn't exist.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
"""
alternate: django-admin can't execute user commands unless settings are
provided.
"""
args = ["noargs_command"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No Django settings specified")
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
"""
alternate: django-admin can execute user commands if settings are
provided as argument.
"""
args = ["noargs_command", "--settings=test_project.alternate_settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
"""
alternate: django-admin can execute user commands if settings are
provided in environment.
"""
args = ["noargs_command"]
out, err = self.run_django_admin(args, "test_project.alternate_settings")
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
class DjangoAdminSettingsDirectory(AdminScriptTestCase):
"""
A series of tests for django-admin when the settings file is in a
directory. (see #9751).
"""
def setUp(self):
super().setUp()
self.write_settings("settings", is_dir=True)
def test_setup_environ(self):
"directory: startapp creates the correct directory"
args = ["startapp", "settings_test"]
app_path = os.path.join(self.test_dir, "settings_test")
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
self.assertTrue(os.path.exists(app_path))
with open(os.path.join(app_path, "apps.py")) as f:
content = f.read()
self.assertIn("class SettingsTestConfig(AppConfig)", content)
self.assertIn(
'name = "settings_test"' if HAS_BLACK else "name = 'settings_test'",
content,
)
def test_setup_environ_custom_template(self):
"directory: startapp creates the correct directory with a custom template"
template_path = os.path.join(custom_templates_dir, "app_template")
args = ["startapp", "--template", template_path, "custom_settings_test"]
app_path = os.path.join(self.test_dir, "custom_settings_test")
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
self.assertTrue(os.path.exists(app_path))
self.assertTrue(os.path.exists(os.path.join(app_path, "api.py")))
def test_startapp_unicode_name(self):
"""startapp creates the correct directory with Unicode characters."""
args = ["startapp", "こんにちは"]
app_path = os.path.join(self.test_dir, "こんにちは")
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
self.assertTrue(os.path.exists(app_path))
with open(os.path.join(app_path, "apps.py"), encoding="utf8") as f:
content = f.read()
self.assertIn("class こんにちはConfig(AppConfig)", content)
self.assertIn('name = "こんにちは"' if HAS_BLACK else "name = 'こんにちは'", content)
def test_builtin_command(self):
"""
directory: django-admin builtin commands fail with an error when no
settings provided.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_bad_settings(self):
"""
directory: django-admin builtin commands fail if settings file (from
argument) doesn't exist.
"""
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
"""
directory: django-admin builtin commands fail if settings file (from
environment) doesn't exist.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
"""
directory: django-admin can't execute user commands unless settings are
provided.
"""
args = ["noargs_command"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No Django settings specified")
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_builtin_with_settings(self):
"""
directory: django-admin builtin commands succeed if settings are
provided as argument.
"""
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
"""
directory: django-admin builtin commands succeed if settings are
provided in the environment.
"""
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
##########################################################################
# MANAGE.PY TESTS
# This next series of test classes checks the environment processing
# of the generated manage.py script
##########################################################################
class ManageManuallyConfiguredSettings(AdminScriptTestCase):
"""Customized manage.py calling settings.configure()."""
def test_non_existent_command_output(self):
out, err = self.run_manage(
["invalid_command"], manage_py="configured_settings_manage.py"
)
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'invalid_command'")
self.assertNotInOutput(err, "No Django settings specified")
class ManageNoSettings(AdminScriptTestCase):
"A series of tests for manage.py when there is no settings.py file."
def test_builtin_command(self):
"""
no settings: manage.py builtin commands fail with an error when no
settings provided.
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(
err, r"No module named '?(test_project\.)?settings'?", regex=True
)
def test_builtin_with_bad_settings(self):
"""
no settings: manage.py builtin commands fail if settings file (from
argument) doesn't exist.
"""
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
"""
no settings: manage.py builtin commands fail if settings file (from
environment) doesn't exist.
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
class ManageDefaultSettings(AdminScriptTestCase):
"""A series of tests for manage.py when using a settings.py file that
contains the test application.
"""
def setUp(self):
super().setUp()
self.write_settings("settings.py")
def test_builtin_command(self):
"""
default: manage.py builtin commands succeed when default settings are
appropriate.
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_settings(self):
"""
default: manage.py builtin commands succeed if settings are provided as
argument.
"""
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
"""
default: manage.py builtin commands succeed if settings are provided in
the environment.
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
"""
default: manage.py builtin commands succeed if settings file (from
argument) doesn't exist.
"""
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
"""
default: manage.py builtin commands fail if settings file (from
environment) doesn't exist.
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
"""
default: manage.py can execute user commands when default settings are
appropriate.
"""
args = ["noargs_command"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_settings(self):
"""
default: manage.py can execute user commands when settings are provided
as argument.
"""
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
"""
default: manage.py can execute user commands when settings are provided
in environment.
"""
args = ["noargs_command"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
class ManageFullPathDefaultSettings(AdminScriptTestCase):
"""A series of tests for manage.py when using a settings.py file that
contains the test application specified using a full path.
"""
def setUp(self):
super().setUp()
self.write_settings(
"settings.py",
["django.contrib.auth", "django.contrib.contenttypes", "admin_scripts"],
)
def test_builtin_command(self):
"""
fulldefault: manage.py builtin commands succeed when default settings
are appropriate.
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_settings(self):
"""
fulldefault: manage.py builtin commands succeed if settings are
provided as argument.
"""
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
"""
fulldefault: manage.py builtin commands succeed if settings are
provided in the environment.
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
"""
fulldefault: manage.py builtin commands succeed if settings file (from
argument) doesn't exist.
"""
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
"""
fulldefault: manage.py builtin commands fail if settings file (from
environment) doesn't exist.
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
"""
fulldefault: manage.py can execute user commands when default settings
are appropriate.
"""
args = ["noargs_command"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_settings(self):
"""
fulldefault: manage.py can execute user commands when settings are
provided as argument.
"""
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
"""
fulldefault: manage.py can execute user commands when settings are
provided in environment.
"""
args = ["noargs_command"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
class ManageMinimalSettings(AdminScriptTestCase):
"""A series of tests for manage.py when using a settings.py file that
doesn't contain the test application.
"""
def setUp(self):
super().setUp()
self.write_settings(
"settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"]
)
def test_builtin_command(self):
"""
minimal: manage.py builtin commands fail with an error when no settings
provided.
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No installed app with label 'admin_scripts'.")
def test_builtin_with_settings(self):
"minimal: manage.py builtin commands fail if settings are provided as argument"
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No installed app with label 'admin_scripts'.")
def test_builtin_with_environment(self):
"""
minimal: manage.py builtin commands fail if settings are provided in
the environment.
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(out)
self.assertOutput(err, "No installed app with label 'admin_scripts'.")
def test_builtin_with_bad_settings(self):
"""
minimal: manage.py builtin commands fail if settings file (from
argument) doesn't exist.
"""
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
"""
minimal: manage.py builtin commands fail if settings file (from
environment) doesn't exist.
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
"minimal: manage.py can't execute user commands without appropriate settings"
args = ["noargs_command"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
"""
minimal: manage.py can't execute user commands, even if settings are
provided as argument.
"""
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_environment(self):
"""
minimal: manage.py can't execute user commands, even if settings are
provided in environment.
"""
args = ["noargs_command"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'noargs_command'")
class ManageAlternateSettings(AdminScriptTestCase):
"""A series of tests for manage.py when using a settings file
with a name other than 'settings.py'.
"""
def setUp(self):
super().setUp()
self.write_settings("alternate_settings.py")
def test_builtin_command(self):
"""
alternate: manage.py builtin commands fail with an error when no
default settings provided.
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(
err, r"No module named '?(test_project\.)?settings'?", regex=True
)
def test_builtin_with_settings(self):
"alternate: manage.py builtin commands work with settings provided as argument"
args = ["check", "--settings=alternate_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertOutput(out, SYSTEM_CHECK_MSG)
self.assertNoOutput(err)
def test_builtin_with_environment(self):
"""
alternate: manage.py builtin commands work if settings are provided in
the environment
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "alternate_settings")
self.assertOutput(out, SYSTEM_CHECK_MSG)
self.assertNoOutput(err)
def test_builtin_with_bad_settings(self):
"""
alternate: manage.py builtin commands fail if settings file (from
argument) doesn't exist.
"""
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
"""
alternate: manage.py builtin commands fail if settings file (from
environment) doesn't exist
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
"alternate: manage.py can't execute user commands without settings"
args = ["noargs_command"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(
err, r"No module named '?(test_project\.)?settings'?", regex=True
)
def test_custom_command_with_settings(self):
"""
alternate: manage.py can execute user commands if settings are provided
as argument
"""
args = ["noargs_command", "--settings=alternate_settings"]
out, err = self.run_manage(args)
self.assertOutput(
out,
"EXECUTE: noargs_command options=[('force_color', False), "
"('no_color', False), ('pythonpath', None), ('settings', "
"'alternate_settings'), ('traceback', False), ('verbosity', 1)]",
)
self.assertNoOutput(err)
def test_custom_command_with_environment(self):
"""
alternate: manage.py can execute user commands if settings are provided
in environment.
"""
args = ["noargs_command"]
out, err = self.run_manage(args, "alternate_settings")
self.assertOutput(
out,
"EXECUTE: noargs_command options=[('force_color', False), "
"('no_color', False), ('pythonpath', None), ('settings', None), "
"('traceback', False), ('verbosity', 1)]",
)
self.assertNoOutput(err)
def test_custom_command_output_color(self):
"""
alternate: manage.py output syntax color can be deactivated with the
`--no-color` option.
"""
args = ["noargs_command", "--no-color", "--settings=alternate_settings"]
out, err = self.run_manage(args)
self.assertOutput(
out,
"EXECUTE: noargs_command options=[('force_color', False), "
"('no_color', True), ('pythonpath', None), ('settings', "
"'alternate_settings'), ('traceback', False), ('verbosity', 1)]",
)
self.assertNoOutput(err)
class ManageMultipleSettings(AdminScriptTestCase):
"""A series of tests for manage.py when multiple settings files
(including the default 'settings.py') are available. The default settings
file is insufficient for performing the operations described, so the
alternate settings must be used by the running script.
"""
def setUp(self):
super().setUp()
self.write_settings(
"settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"]
)
self.write_settings("alternate_settings.py")
def test_builtin_command(self):
"""
multiple: manage.py builtin commands fail with an error when no
settings provided.
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No installed app with label 'admin_scripts'.")
def test_builtin_with_settings(self):
"""
multiple: manage.py builtin commands succeed if settings are provided
as argument.
"""
args = ["check", "--settings=alternate_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
"""
multiple: manage.py can execute builtin commands if settings are
provided in the environment.
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "alternate_settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
"""
multiple: manage.py builtin commands fail if settings file (from
argument) doesn't exist.
"""
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
"""
multiple: manage.py builtin commands fail if settings file (from
environment) doesn't exist.
"""
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
"multiple: manage.py can't execute user commands using default settings"
args = ["noargs_command"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
"""
multiple: manage.py can execute user commands if settings are provided
as argument.
"""
args = ["noargs_command", "--settings=alternate_settings"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
"""
multiple: manage.py can execute user commands if settings are provided
in environment.
"""
args = ["noargs_command"]
out, err = self.run_manage(args, "alternate_settings")
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
class ManageSettingsWithSettingsErrors(AdminScriptTestCase):
"""
Tests for manage.py when using the default settings.py file containing
runtime errors.
"""
def write_settings_with_import_error(self, filename):
settings_file_path = os.path.join(self.test_dir, filename)
with open(settings_file_path, "w") as settings_file:
settings_file.write(
"# Settings file automatically generated by admin_scripts test case\n"
)
settings_file.write(
"# The next line will cause an import error:\nimport foo42bar\n"
)
def test_import_error(self):
"""
import error: manage.py builtin commands shows useful diagnostic info
when settings with import errors is provided (#14130).
"""
self.write_settings_with_import_error("settings.py")
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named")
self.assertOutput(err, "foo42bar")
def test_attribute_error(self):
"""
manage.py builtin commands does not swallow attribute error due to bad
settings (#18845).
"""
self.write_settings("settings.py", sdict={"BAD_VAR": "INSTALLED_APPS.crash"})
args = ["collectstatic", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "AttributeError: 'list' object has no attribute 'crash'")
def test_key_error(self):
self.write_settings("settings.py", sdict={"BAD_VAR": 'DATABASES["blah"]'})
args = ["collectstatic", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "KeyError: 'blah'")
def test_help(self):
"""
Test listing available commands output note when only core commands are
available.
"""
self.write_settings(
"settings.py",
extra="from django.core.exceptions import ImproperlyConfigured\n"
"raise ImproperlyConfigured()",
)
args = ["help"]
out, err = self.run_manage(args)
self.assertOutput(out, "only Django core commands are listed")
self.assertNoOutput(err)
class ManageCheck(AdminScriptTestCase):
def test_nonexistent_app(self):
"""check reports an error on a nonexistent app in INSTALLED_APPS."""
self.write_settings(
"settings.py",
apps=["admin_scriptz.broken_app"],
sdict={"USE_I18N": False},
)
args = ["check"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "ModuleNotFoundError")
self.assertOutput(err, "No module named")
self.assertOutput(err, "admin_scriptz")
def test_broken_app(self):
"""manage.py check reports an ImportError if an app's models.py
raises one on import"""
self.write_settings("settings.py", apps=["admin_scripts.broken_app"])
args = ["check"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "ImportError")
def test_complex_app(self):
"""manage.py check does not raise an ImportError validating a
complex app with nested calls to load_app"""
self.write_settings(
"settings.py",
apps=[
"admin_scripts.complex_app",
"admin_scripts.simple_app",
"django.contrib.admin.apps.SimpleAdminConfig",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.messages",
],
sdict={
"DEBUG": True,
"MIDDLEWARE": [
"django.contrib.messages.middleware.MessageMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
],
"TEMPLATES": [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
],
},
)
args = ["check"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertEqual(out, "System check identified no issues (0 silenced).\n")
def test_app_with_import(self):
"""manage.py check does not raise errors when an app imports a base
class that itself has an abstract base."""
self.write_settings(
"settings.py",
apps=[
"admin_scripts.app_with_import",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
],
sdict={"DEBUG": True},
)
args = ["check"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertEqual(out, "System check identified no issues (0 silenced).\n")
def test_output_format(self):
"""All errors/warnings should be sorted by level and by message."""
self.write_settings(
"settings.py",
apps=[
"admin_scripts.app_raising_messages",
"django.contrib.auth",
"django.contrib.contenttypes",
],
sdict={"DEBUG": True},
)
args = ["check"]
out, err = self.run_manage(args)
expected_err = (
"SystemCheckError: System check identified some issues:\n"
"\n"
"ERRORS:\n"
"?: An error\n"
"\tHINT: Error hint\n"
"\n"
"WARNINGS:\n"
"a: Second warning\n"
"obj: First warning\n"
"\tHINT: Hint\n"
"\n"
"System check identified 3 issues (0 silenced).\n"
)
self.assertEqual(err, expected_err)
self.assertNoOutput(out)
def test_warning_does_not_halt(self):
"""
When there are only warnings or less serious messages, then Django
should not prevent user from launching their project, so `check`
command should not raise `CommandError` exception.
In this test we also test output format.
"""
self.write_settings(
"settings.py",
apps=[
"admin_scripts.app_raising_warning",
"django.contrib.auth",
"django.contrib.contenttypes",
],
sdict={"DEBUG": True},
)
args = ["check"]
out, err = self.run_manage(args)
expected_err = (
"System check identified some issues:\n" # No "CommandError: " part
"\n"
"WARNINGS:\n"
"?: A warning\n"
"\n"
"System check identified 1 issue (0 silenced).\n"
)
self.assertEqual(err, expected_err)
self.assertNoOutput(out)
class ManageRunserver(SimpleTestCase):
def setUp(self):
def monkey_run(*args, **options):
return
self.output = StringIO()
self.cmd = RunserverCommand(stdout=self.output)
self.cmd.run = monkey_run
def assertServerSettings(self, addr, port, ipv6=False, raw_ipv6=False):
self.assertEqual(self.cmd.addr, addr)
self.assertEqual(self.cmd.port, port)
self.assertEqual(self.cmd.use_ipv6, ipv6)
self.assertEqual(self.cmd._raw_ipv6, raw_ipv6)
def test_runserver_addrport(self):
call_command(self.cmd)
self.assertServerSettings("127.0.0.1", "8000")
call_command(self.cmd, addrport="1.2.3.4:8000")
self.assertServerSettings("1.2.3.4", "8000")
call_command(self.cmd, addrport="7000")
self.assertServerSettings("127.0.0.1", "7000")
@mock.patch("django.core.management.commands.runserver.run")
@mock.patch("django.core.management.base.BaseCommand.check_migrations")
def test_zero_ip_addr(self, *mocked_objects):
call_command(
"runserver",
addrport="0:8000",
use_reloader=False,
skip_checks=True,
stdout=self.output,
)
self.assertIn(
"Starting development server at http://0.0.0.0:8000/",
self.output.getvalue(),
)
@unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6")
def test_runner_addrport_ipv6(self):
call_command(self.cmd, addrport="", use_ipv6=True)
self.assertServerSettings("::1", "8000", ipv6=True, raw_ipv6=True)
call_command(self.cmd, addrport="7000", use_ipv6=True)
self.assertServerSettings("::1", "7000", ipv6=True, raw_ipv6=True)
call_command(self.cmd, addrport="[2001:0db8:1234:5678::9]:7000")
self.assertServerSettings(
"2001:0db8:1234:5678::9", "7000", ipv6=True, raw_ipv6=True
)
def test_runner_hostname(self):
call_command(self.cmd, addrport="localhost:8000")
self.assertServerSettings("localhost", "8000")
call_command(self.cmd, addrport="test.domain.local:7000")
self.assertServerSettings("test.domain.local", "7000")
@unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6")
def test_runner_hostname_ipv6(self):
call_command(self.cmd, addrport="test.domain.local:7000", use_ipv6=True)
self.assertServerSettings("test.domain.local", "7000", ipv6=True)
def test_runner_custom_defaults(self):
self.cmd.default_addr = "0.0.0.0"
self.cmd.default_port = "5000"
call_command(self.cmd)
self.assertServerSettings("0.0.0.0", "5000")
@unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6")
def test_runner_custom_defaults_ipv6(self):
self.cmd.default_addr_ipv6 = "::"
call_command(self.cmd, use_ipv6=True)
self.assertServerSettings("::", "8000", ipv6=True, raw_ipv6=True)
def test_runner_ambiguous(self):
# Only 4 characters, all of which could be in an ipv6 address
call_command(self.cmd, addrport="beef:7654")
self.assertServerSettings("beef", "7654")
# Uses only characters that could be in an ipv6 address
call_command(self.cmd, addrport="deadbeef:7654")
self.assertServerSettings("deadbeef", "7654")
def test_no_database(self):
"""
Ensure runserver.check_migrations doesn't choke on empty DATABASES.
"""
tested_connections = ConnectionHandler({})
with mock.patch(
"django.core.management.base.connections", new=tested_connections
):
self.cmd.check_migrations()
def test_readonly_database(self):
"""
runserver.check_migrations() doesn't choke when a database is read-only.
"""
with mock.patch.object(MigrationRecorder, "has_table", return_value=False):
self.cmd.check_migrations()
# You have # ...
self.assertIn("unapplied migration(s)", self.output.getvalue())
@mock.patch("django.core.management.commands.runserver.run")
@mock.patch("django.core.management.base.BaseCommand.check_migrations")
@mock.patch("django.core.management.base.BaseCommand.check")
def test_skip_checks(self, mocked_check, *mocked_objects):
call_command(
"runserver",
use_reloader=False,
skip_checks=True,
stdout=self.output,
)
self.assertNotIn("Performing system checks...", self.output.getvalue())
mocked_check.assert_not_called()
self.output.truncate(0)
call_command(
"runserver",
use_reloader=False,
skip_checks=False,
stdout=self.output,
)
self.assertIn("Performing system checks...", self.output.getvalue())
mocked_check.assert_called()
class ManageRunserverMigrationWarning(TestCase):
def setUp(self):
self.stdout = StringIO()
self.runserver_command = RunserverCommand(stdout=self.stdout)
@override_settings(INSTALLED_APPS=["admin_scripts.app_waiting_migration"])
def test_migration_warning_one_app(self):
self.runserver_command.check_migrations()
output = self.stdout.getvalue()
self.assertIn("You have 1 unapplied migration(s)", output)
self.assertIn("apply the migrations for app(s): app_waiting_migration.", output)
@override_settings(
INSTALLED_APPS=[
"admin_scripts.app_waiting_migration",
"admin_scripts.another_app_waiting_migration",
],
)
def test_migration_warning_multiple_apps(self):
self.runserver_command.check_migrations()
output = self.stdout.getvalue()
self.assertIn("You have 2 unapplied migration(s)", output)
self.assertIn(
"apply the migrations for app(s): another_app_waiting_migration, "
"app_waiting_migration.",
output,
)
class ManageRunserverEmptyAllowedHosts(AdminScriptTestCase):
def setUp(self):
super().setUp()
self.write_settings(
"settings.py",
sdict={
"ALLOWED_HOSTS": [],
"DEBUG": False,
},
)
def test_empty_allowed_hosts_error(self):
out, err = self.run_manage(["runserver"])
self.assertNoOutput(out)
self.assertOutput(
err, "CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False."
)
class ManageRunserverHelpOutput(AdminScriptTestCase):
def test_suppressed_options(self):
"""runserver doesn't support --verbosity and --trackback options."""
out, err = self.run_manage(["runserver", "--help"])
self.assertNotInOutput(out, "--verbosity")
self.assertNotInOutput(out, "--trackback")
self.assertOutput(out, "--settings")
class ManageTestserver(SimpleTestCase):
@mock.patch.object(TestserverCommand, "handle", return_value="")
def test_testserver_handle_params(self, mock_handle):
out = StringIO()
call_command("testserver", "blah.json", stdout=out)
mock_handle.assert_called_with(
"blah.json",
stdout=out,
settings=None,
pythonpath=None,
verbosity=1,
traceback=False,
addrport="",
no_color=False,
use_ipv6=False,
skip_checks=True,
interactive=True,
force_color=False,
)
@mock.patch("django.db.connection.creation.create_test_db", return_value="test_db")
@mock.patch.object(LoaddataCommand, "handle", return_value="")
@mock.patch.object(RunserverCommand, "handle", return_value="")
def test_params_to_runserver(
self, mock_runserver_handle, mock_loaddata_handle, mock_create_test_db
):
call_command("testserver", "blah.json")
mock_runserver_handle.assert_called_with(
addrport="",
force_color=False,
insecure_serving=False,
no_color=False,
pythonpath=None,
settings=None,
shutdown_message=(
"\nServer stopped.\nNote that the test database, 'test_db', "
"has not been deleted. You can explore it on your own."
),
skip_checks=True,
traceback=False,
use_ipv6=False,
use_reloader=False,
use_static_handler=True,
use_threading=connection.features.test_db_allows_multiple_connections,
verbosity=1,
)
##########################################################################
# COMMAND PROCESSING TESTS
# user-space commands are correctly handled - in particular, arguments to
# the commands are correctly parsed and processed.
##########################################################################
class ColorCommand(BaseCommand):
requires_system_checks = []
def handle(self, *args, **options):
self.stdout.write("Hello, world!", self.style.ERROR)
self.stderr.write("Hello, world!", self.style.ERROR)
class CommandTypes(AdminScriptTestCase):
"Tests for the various types of base command types that can be defined."
def setUp(self):
super().setUp()
self.write_settings("settings.py")
def test_version(self):
"version is handled as a special case"
args = ["version"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, get_version())
def test_version_alternative(self):
"--version is equivalent to version"
args1, args2 = ["version"], ["--version"]
# It's possible one outputs on stderr and the other on stdout, hence the set
self.assertEqual(set(self.run_manage(args1)), set(self.run_manage(args2)))
def test_help(self):
"help is handled as a special case"
args = ["help"]
out, err = self.run_manage(args)
self.assertOutput(
out, "Type 'manage.py help <subcommand>' for help on a specific subcommand."
)
self.assertOutput(out, "[django]")
self.assertOutput(out, "startapp")
self.assertOutput(out, "startproject")
def test_help_commands(self):
"help --commands shows the list of all available commands"
args = ["help", "--commands"]
out, err = self.run_manage(args)
self.assertNotInOutput(out, "usage:")
self.assertNotInOutput(out, "Options:")
self.assertNotInOutput(out, "[django]")
self.assertOutput(out, "startapp")
self.assertOutput(out, "startproject")
self.assertNotInOutput(out, "\n\n")
def test_help_alternative(self):
"--help is equivalent to help"
args1, args2 = ["help"], ["--help"]
self.assertEqual(self.run_manage(args1), self.run_manage(args2))
def test_help_short_altert(self):
"-h is handled as a short form of --help"
args1, args2 = ["--help"], ["-h"]
self.assertEqual(self.run_manage(args1), self.run_manage(args2))
def test_specific_help(self):
"--help can be used on a specific command"
args = ["check", "--help"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
# Command-specific options like --tag appear before options common to
# all commands like --version.
tag_location = out.find("--tag")
version_location = out.find("--version")
self.assertNotEqual(tag_location, -1)
self.assertNotEqual(version_location, -1)
self.assertLess(tag_location, version_location)
self.assertOutput(
out, "Checks the entire Django project for potential problems."
)
def test_help_default_options_with_custom_arguments(self):
args = ["base_command", "--help"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
expected_options = [
"-h",
"--option_a OPTION_A",
"--option_b OPTION_B",
"--option_c OPTION_C",
"--version",
"-v {0,1,2,3}",
"--settings SETTINGS",
"--pythonpath PYTHONPATH",
"--traceback",
"--no-color",
"--force-color",
"args ...",
]
for option in expected_options:
self.assertOutput(out, f"[{option}]")
self.assertOutput(out, "--option_a OPTION_A, -a OPTION_A")
self.assertOutput(out, "--option_b OPTION_B, -b OPTION_B")
self.assertOutput(out, "--option_c OPTION_C, -c OPTION_C")
self.assertOutput(out, "-v {0,1,2,3}, --verbosity {0,1,2,3}")
def test_color_style(self):
style = color.no_style()
self.assertEqual(style.ERROR("Hello, world!"), "Hello, world!")
style = color.make_style("nocolor")
self.assertEqual(style.ERROR("Hello, world!"), "Hello, world!")
style = color.make_style("dark")
self.assertIn("Hello, world!", style.ERROR("Hello, world!"))
self.assertNotEqual(style.ERROR("Hello, world!"), "Hello, world!")
# Default palette has color.
style = color.make_style("")
self.assertIn("Hello, world!", style.ERROR("Hello, world!"))
self.assertNotEqual(style.ERROR("Hello, world!"), "Hello, world!")
def test_command_color(self):
out = StringIO()
err = StringIO()
command = ColorCommand(stdout=out, stderr=err)
call_command(command)
if color.supports_color():
self.assertIn("Hello, world!\n", out.getvalue())
self.assertIn("Hello, world!\n", err.getvalue())
self.assertNotEqual(out.getvalue(), "Hello, world!\n")
self.assertNotEqual(err.getvalue(), "Hello, world!\n")
else:
self.assertEqual(out.getvalue(), "Hello, world!\n")
self.assertEqual(err.getvalue(), "Hello, world!\n")
def test_command_no_color(self):
"--no-color prevent colorization of the output"
out = StringIO()
err = StringIO()
command = ColorCommand(stdout=out, stderr=err, no_color=True)
call_command(command)
self.assertEqual(out.getvalue(), "Hello, world!\n")
self.assertEqual(err.getvalue(), "Hello, world!\n")
out = StringIO()
err = StringIO()
command = ColorCommand(stdout=out, stderr=err)
call_command(command, no_color=True)
self.assertEqual(out.getvalue(), "Hello, world!\n")
self.assertEqual(err.getvalue(), "Hello, world!\n")
def test_force_color_execute(self):
out = StringIO()
err = StringIO()
with mock.patch.object(sys.stdout, "isatty", lambda: False):
command = ColorCommand(stdout=out, stderr=err)
call_command(command, force_color=True)
self.assertEqual(out.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m")
self.assertEqual(err.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m")
def test_force_color_command_init(self):
out = StringIO()
err = StringIO()
with mock.patch.object(sys.stdout, "isatty", lambda: False):
command = ColorCommand(stdout=out, stderr=err, force_color=True)
call_command(command)
self.assertEqual(out.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m")
self.assertEqual(err.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m")
def test_no_color_force_color_mutually_exclusive_execute(self):
msg = "The --no-color and --force-color options can't be used together."
with self.assertRaisesMessage(CommandError, msg):
call_command(BaseCommand(), no_color=True, force_color=True)
def test_no_color_force_color_mutually_exclusive_command_init(self):
msg = "'no_color' and 'force_color' can't be used together."
with self.assertRaisesMessage(CommandError, msg):
call_command(BaseCommand(no_color=True, force_color=True))
def test_custom_stdout(self):
class Command(BaseCommand):
requires_system_checks = []
def handle(self, *args, **options):
self.stdout.write("Hello, World!")
out = StringIO()
command = Command(stdout=out)
call_command(command)
self.assertEqual(out.getvalue(), "Hello, World!\n")
out.truncate(0)
new_out = StringIO()
call_command(command, stdout=new_out)
self.assertEqual(out.getvalue(), "")
self.assertEqual(new_out.getvalue(), "Hello, World!\n")
def test_custom_stderr(self):
class Command(BaseCommand):
requires_system_checks = []
def handle(self, *args, **options):
self.stderr.write("Hello, World!")
err = StringIO()
command = Command(stderr=err)
call_command(command)
self.assertEqual(err.getvalue(), "Hello, World!\n")
err.truncate(0)
new_err = StringIO()
call_command(command, stderr=new_err)
self.assertEqual(err.getvalue(), "")
self.assertEqual(new_err.getvalue(), "Hello, World!\n")
def test_base_command(self):
"User BaseCommands can execute when a label is provided"
args = ["base_command", "testlabel"]
expected_labels = "('testlabel',)"
self._test_base_command(args, expected_labels)
def test_base_command_no_label(self):
"User BaseCommands can execute when no labels are provided"
args = ["base_command"]
expected_labels = "()"
self._test_base_command(args, expected_labels)
def test_base_command_multiple_label(self):
"User BaseCommands can execute when no labels are provided"
args = ["base_command", "testlabel", "anotherlabel"]
expected_labels = "('testlabel', 'anotherlabel')"
self._test_base_command(args, expected_labels)
def test_base_command_with_option(self):
"User BaseCommands can execute with options when a label is provided"
args = ["base_command", "testlabel", "--option_a=x"]
expected_labels = "('testlabel',)"
self._test_base_command(args, expected_labels, option_a="'x'")
def test_base_command_with_options(self):
"User BaseCommands can execute with multiple options when a label is provided"
args = ["base_command", "testlabel", "-a", "x", "--option_b=y"]
expected_labels = "('testlabel',)"
self._test_base_command(args, expected_labels, option_a="'x'", option_b="'y'")
def test_base_command_with_wrong_option(self):
"User BaseCommands outputs command usage when wrong option is specified"
args = ["base_command", "--invalid"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "usage: manage.py base_command")
self.assertOutput(err, "error: unrecognized arguments: --invalid")
def _test_base_command(self, args, labels, option_a="'1'", option_b="'2'"):
out, err = self.run_manage(args)
expected_out = (
"EXECUTE:BaseCommand labels=%s, "
"options=[('force_color', False), ('no_color', False), "
"('option_a', %s), ('option_b', %s), ('option_c', '3'), "
"('pythonpath', None), ('settings', None), ('traceback', False), "
"('verbosity', 1)]"
) % (labels, option_a, option_b)
self.assertNoOutput(err)
self.assertOutput(out, expected_out)
def test_base_run_from_argv(self):
"""
Test run_from_argv properly terminates even with custom execute() (#19665)
Also test proper traceback display.
"""
err = StringIO()
command = BaseCommand(stderr=err)
def raise_command_error(*args, **kwargs):
raise CommandError("Custom error")
command.execute = lambda args: args # This will trigger TypeError
# If the Exception is not CommandError it should always
# raise the original exception.
with self.assertRaises(TypeError):
command.run_from_argv(["", ""])
# If the Exception is CommandError and --traceback is not present
# this command should raise a SystemExit and don't print any
# traceback to the stderr.
command.execute = raise_command_error
err.truncate(0)
with self.assertRaises(SystemExit):
command.run_from_argv(["", ""])
err_message = err.getvalue()
self.assertNotIn("Traceback", err_message)
self.assertIn("CommandError", err_message)
# If the Exception is CommandError and --traceback is present
# this command should raise the original CommandError as if it
# were not a CommandError.
err.truncate(0)
with self.assertRaises(CommandError):
command.run_from_argv(["", "", "--traceback"])
def test_run_from_argv_non_ascii_error(self):
"""
Non-ASCII message of CommandError does not raise any
UnicodeDecodeError in run_from_argv.
"""
def raise_command_error(*args, **kwargs):
raise CommandError("Erreur personnalisée")
command = BaseCommand(stderr=StringIO())
command.execute = raise_command_error
with self.assertRaises(SystemExit):
command.run_from_argv(["", ""])
def test_run_from_argv_closes_connections(self):
"""
A command called from the command line should close connections after
being executed (#21255).
"""
command = BaseCommand()
command.check = lambda: []
command.handle = lambda *args, **kwargs: args
with mock.patch("django.core.management.base.connections") as mock_connections:
command.run_from_argv(["", ""])
# Test connections have been closed
self.assertTrue(mock_connections.close_all.called)
def test_noargs(self):
"NoArg Commands can be executed"
args = ["noargs_command"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(
out,
"EXECUTE: noargs_command options=[('force_color', False), "
"('no_color', False), ('pythonpath', None), ('settings', None), "
"('traceback', False), ('verbosity', 1)]",
)
def test_noargs_with_args(self):
"NoArg Commands raise an error if an argument is provided"
args = ["noargs_command", "argument"]
out, err = self.run_manage(args)
self.assertOutput(err, "error: unrecognized arguments: argument")
def test_app_command(self):
"User AppCommands can execute when a single app name is provided"
args = ["app_command", "auth"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=")
self.assertOutput(
out,
", options=[('force_color', False), ('no_color', False), "
"('pythonpath', None), ('settings', None), ('traceback', False), "
"('verbosity', 1)]",
)
def test_app_command_no_apps(self):
"User AppCommands raise an error when no app name is provided"
args = ["app_command"]
out, err = self.run_manage(args)
self.assertOutput(err, "error: Enter at least one application label.")
def test_app_command_multiple_apps(self):
"User AppCommands raise an error when multiple app names are provided"
args = ["app_command", "auth", "contenttypes"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=")
self.assertOutput(
out,
", options=[('force_color', False), ('no_color', False), "
"('pythonpath', None), ('settings', None), ('traceback', False), "
"('verbosity', 1)]",
)
self.assertOutput(
out, "EXECUTE:AppCommand name=django.contrib.contenttypes, options="
)
self.assertOutput(
out,
", options=[('force_color', False), ('no_color', False), "
"('pythonpath', None), ('settings', None), ('traceback', False), "
"('verbosity', 1)]",
)
def test_app_command_invalid_app_label(self):
"User AppCommands can execute when a single app name is provided"
args = ["app_command", "NOT_AN_APP"]
out, err = self.run_manage(args)
self.assertOutput(err, "No installed app with label 'NOT_AN_APP'.")
def test_app_command_some_invalid_app_labels(self):
"User AppCommands can execute when some of the provided app names are invalid"
args = ["app_command", "auth", "NOT_AN_APP"]
out, err = self.run_manage(args)
self.assertOutput(err, "No installed app with label 'NOT_AN_APP'.")
def test_label_command(self):
"User LabelCommands can execute when a label is provided"
args = ["label_command", "testlabel"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(
out,
"EXECUTE:LabelCommand label=testlabel, options=[('force_color', "
"False), ('no_color', False), ('pythonpath', None), ('settings', "
"None), ('traceback', False), ('verbosity', 1)]",
)
def test_label_command_no_label(self):
"User LabelCommands raise an error if no label is provided"
args = ["label_command"]
out, err = self.run_manage(args)
self.assertOutput(err, "Enter at least one label")
def test_label_command_multiple_label(self):
"User LabelCommands are executed multiple times if multiple labels are provided"
args = ["label_command", "testlabel", "anotherlabel"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(
out,
"EXECUTE:LabelCommand label=testlabel, options=[('force_color', "
"False), ('no_color', False), ('pythonpath', None), "
"('settings', None), ('traceback', False), ('verbosity', 1)]",
)
self.assertOutput(
out,
"EXECUTE:LabelCommand label=anotherlabel, options=[('force_color', "
"False), ('no_color', False), ('pythonpath', None), "
"('settings', None), ('traceback', False), ('verbosity', 1)]",
)
def test_suppress_base_options_command_help(self):
args = ["suppress_base_options_command", "--help"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "Test suppress base options command.")
self.assertNotInOutput(out, "input file")
self.assertOutput(out, "-h, --help")
self.assertNotInOutput(out, "--version")
self.assertNotInOutput(out, "--verbosity")
self.assertNotInOutput(out, "-v {0,1,2,3}")
self.assertNotInOutput(out, "--settings")
self.assertNotInOutput(out, "--pythonpath")
self.assertNotInOutput(out, "--traceback")
self.assertNotInOutput(out, "--no-color")
self.assertNotInOutput(out, "--force-color")
def test_suppress_base_options_command_defaults(self):
args = ["suppress_base_options_command"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(
out,
"EXECUTE:SuppressBaseOptionsCommand options=[('file', None), "
"('force_color', False), ('no_color', False), "
"('pythonpath', None), ('settings', None), "
"('traceback', False), ('verbosity', 1)]",
)
class Discovery(SimpleTestCase):
def test_precedence(self):
"""
Apps listed first in INSTALLED_APPS have precedence.
"""
with self.settings(
INSTALLED_APPS=[
"admin_scripts.complex_app",
"admin_scripts.simple_app",
"django.contrib.auth",
"django.contrib.contenttypes",
]
):
out = StringIO()
call_command("duplicate", stdout=out)
self.assertEqual(out.getvalue().strip(), "complex_app")
with self.settings(
INSTALLED_APPS=[
"admin_scripts.simple_app",
"admin_scripts.complex_app",
"django.contrib.auth",
"django.contrib.contenttypes",
]
):
out = StringIO()
call_command("duplicate", stdout=out)
self.assertEqual(out.getvalue().strip(), "simple_app")
class ArgumentOrder(AdminScriptTestCase):
"""Tests for 2-stage argument parsing scheme.
django-admin command arguments are parsed in 2 parts; the core arguments
(--settings, --traceback and --pythonpath) are parsed using a basic parser,
ignoring any unknown options. Then the full settings are
passed to the command parser, which extracts commands of interest to the
individual command.
"""
def setUp(self):
super().setUp()
self.write_settings(
"settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"]
)
self.write_settings("alternate_settings.py")
def test_setting_then_option(self):
"""Options passed after settings are correctly handled."""
args = [
"base_command",
"testlabel",
"--settings=alternate_settings",
"--option_a=x",
]
self._test(args)
def test_setting_then_short_option(self):
"""Short options passed after settings are correctly handled."""
args = ["base_command", "testlabel", "--settings=alternate_settings", "-a", "x"]
self._test(args)
def test_option_then_setting(self):
"""Options passed before settings are correctly handled."""
args = [
"base_command",
"testlabel",
"--option_a=x",
"--settings=alternate_settings",
]
self._test(args)
def test_short_option_then_setting(self):
"""Short options passed before settings are correctly handled."""
args = ["base_command", "testlabel", "-a", "x", "--settings=alternate_settings"]
self._test(args)
def test_option_then_setting_then_option(self):
"""Options are correctly handled when they are passed before and after
a setting."""
args = [
"base_command",
"testlabel",
"--option_a=x",
"--settings=alternate_settings",
"--option_b=y",
]
self._test(args, option_b="'y'")
def _test(self, args, option_b="'2'"):
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(
out,
"EXECUTE:BaseCommand labels=('testlabel',), options=["
"('force_color', False), ('no_color', False), ('option_a', 'x'), "
"('option_b', %s), ('option_c', '3'), ('pythonpath', None), "
"('settings', 'alternate_settings'), ('traceback', False), "
"('verbosity', 1)]" % option_b,
)
class ExecuteFromCommandLine(SimpleTestCase):
def test_program_name_from_argv(self):
"""
Program name is computed from the execute_from_command_line()'s argv
argument, not sys.argv.
"""
args = ["help", "shell"]
with captured_stdout() as out, captured_stderr() as err:
with mock.patch("sys.argv", [None] + args):
execute_from_command_line(["django-admin"] + args)
self.assertIn("usage: django-admin shell", out.getvalue())
self.assertEqual(err.getvalue(), "")
@override_settings(ROOT_URLCONF="admin_scripts.urls")
class StartProject(LiveServerTestCase, AdminScriptTestCase):
available_apps = [
"admin_scripts",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
]
def test_wrong_args(self):
"""
Passing the wrong kinds of arguments outputs an error and prints usage.
"""
out, err = self.run_django_admin(["startproject"])
self.assertNoOutput(out)
self.assertOutput(err, "usage:")
self.assertOutput(err, "You must provide a project name.")
def test_simple_project(self):
"Make sure the startproject management command creates a project"
args = ["startproject", "testproject"]
testproject_dir = os.path.join(self.test_dir, "testproject")
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertTrue(os.path.isdir(testproject_dir))
# running again..
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(
err,
"CommandError: 'testproject' conflicts with the name of an "
"existing Python module and cannot be used as a project name. "
"Please try another name.",
)
def test_invalid_project_name(self):
"Make sure the startproject management command validates a project name"
for bad_name in ("7testproject", "../testproject"):
with self.subTest(project_name=bad_name):
args = ["startproject", bad_name]
testproject_dir = os.path.join(self.test_dir, bad_name)
out, err = self.run_django_admin(args)
self.assertOutput(
err,
"Error: '%s' is not a valid project name. Please make "
"sure the name is a valid identifier." % bad_name,
)
self.assertFalse(os.path.exists(testproject_dir))
def test_importable_project_name(self):
"""
startproject validates that project name doesn't clash with existing
Python modules.
"""
bad_name = "os"
args = ["startproject", bad_name]
testproject_dir = os.path.join(self.test_dir, bad_name)
out, err = self.run_django_admin(args)
self.assertOutput(
err,
"CommandError: 'os' conflicts with the name of an existing "
"Python module and cannot be used as a project name. Please try "
"another name.",
)
self.assertFalse(os.path.exists(testproject_dir))
def test_simple_project_different_directory(self):
"""
The startproject management command creates a project in a specific
directory.
"""
args = ["startproject", "testproject", "othertestproject"]
testproject_dir = os.path.join(self.test_dir, "othertestproject")
os.mkdir(testproject_dir)
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertTrue(os.path.exists(os.path.join(testproject_dir, "manage.py")))
# running again..
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(
err,
"already exists. Overlaying a project into an existing directory "
"won't replace conflicting files.",
)
def test_custom_project_template(self):
"""
The startproject management command is able to use a different project
template.
"""
template_path = os.path.join(custom_templates_dir, "project_template")
args = ["startproject", "--template", template_path, "customtestproject"]
testproject_dir = os.path.join(self.test_dir, "customtestproject")
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertTrue(os.path.isdir(testproject_dir))
self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir")))
def test_template_dir_with_trailing_slash(self):
"Ticket 17475: Template dir passed has a trailing path separator"
template_path = os.path.join(custom_templates_dir, "project_template" + os.sep)
args = ["startproject", "--template", template_path, "customtestproject"]
testproject_dir = os.path.join(self.test_dir, "customtestproject")
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertTrue(os.path.isdir(testproject_dir))
self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir")))
def test_custom_project_template_from_tarball_by_path(self):
"""
The startproject management command is able to use a different project
template from a tarball.
"""
template_path = os.path.join(custom_templates_dir, "project_template.tgz")
args = ["startproject", "--template", template_path, "tarballtestproject"]
testproject_dir = os.path.join(self.test_dir, "tarballtestproject")
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertTrue(os.path.isdir(testproject_dir))
self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py")))
def test_custom_project_template_from_tarball_to_alternative_location(self):
"""
Startproject can use a project template from a tarball and create it in
a specified location.
"""
template_path = os.path.join(custom_templates_dir, "project_template.tgz")
args = [
"startproject",
"--template",
template_path,
"tarballtestproject",
"altlocation",
]
testproject_dir = os.path.join(self.test_dir, "altlocation")
os.mkdir(testproject_dir)
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertTrue(os.path.isdir(testproject_dir))
self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py")))
def test_custom_project_template_from_tarball_by_url(self):
"""
The startproject management command is able to use a different project
template from a tarball via a URL.
"""
template_url = "%s/custom_templates/project_template.tgz" % self.live_server_url
args = ["startproject", "--template", template_url, "urltestproject"]
testproject_dir = os.path.join(self.test_dir, "urltestproject")
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertTrue(os.path.isdir(testproject_dir))
self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py")))
def test_custom_project_template_from_tarball_by_url_django_user_agent(self):
user_agent = None
def serve_template(request, *args, **kwargs):
nonlocal user_agent
user_agent = request.headers["User-Agent"]
return serve(request, *args, **kwargs)
old_urlpatterns = urls.urlpatterns[:]
try:
urls.urlpatterns += [
path(
"user_agent_check/<path:path>",
serve_template,
{"document_root": os.path.join(urls.here, "custom_templates")},
),
]
template_url = (
f"{self.live_server_url}/user_agent_check/project_template.tgz"
)
args = ["startproject", "--template", template_url, "urltestproject"]
_, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertIn("Django/%s" % get_version(), user_agent)
finally:
urls.urlpatterns = old_urlpatterns
def test_project_template_tarball_url(self):
""" "
Startproject management command handles project template tar/zip balls
from non-canonical urls.
"""
template_url = (
"%s/custom_templates/project_template.tgz/" % self.live_server_url
)
args = ["startproject", "--template", template_url, "urltestproject"]
testproject_dir = os.path.join(self.test_dir, "urltestproject")
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertTrue(os.path.isdir(testproject_dir))
self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py")))
def test_file_without_extension(self):
"Make sure the startproject management command is able to render custom files"
template_path = os.path.join(custom_templates_dir, "project_template")
args = [
"startproject",
"--template",
template_path,
"customtestproject",
"-e",
"txt",
"-n",
"Procfile",
]
testproject_dir = os.path.join(self.test_dir, "customtestproject")
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertTrue(os.path.isdir(testproject_dir))
self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir")))
base_path = os.path.join(testproject_dir, "additional_dir")
for f in ("Procfile", "additional_file.py", "requirements.txt"):
self.assertTrue(os.path.exists(os.path.join(base_path, f)))
with open(os.path.join(base_path, f)) as fh:
self.assertEqual(
fh.read().strip(), "# some file for customtestproject test project"
)
def test_custom_project_template_context_variables(self):
"Make sure template context variables are rendered with proper values"
template_path = os.path.join(custom_templates_dir, "project_template")
args = [
"startproject",
"--template",
template_path,
"another_project",
"project_dir",
]
testproject_dir = os.path.join(self.test_dir, "project_dir")
os.mkdir(testproject_dir)
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
test_manage_py = os.path.join(testproject_dir, "manage.py")
with open(test_manage_py) as fp:
content = fp.read()
self.assertIn('project_name = "another_project"', content)
self.assertIn('project_directory = "%s"' % testproject_dir, content)
def test_no_escaping_of_project_variables(self):
"Make sure template context variables are not html escaped"
# We're using a custom command so we need the alternate settings
self.write_settings("alternate_settings.py")
template_path = os.path.join(custom_templates_dir, "project_template")
args = [
"custom_startproject",
"--template",
template_path,
"another_project",
"project_dir",
"--extra",
"<&>",
"--settings=alternate_settings",
]
testproject_dir = os.path.join(self.test_dir, "project_dir")
os.mkdir(testproject_dir)
out, err = self.run_manage(args)
self.assertNoOutput(err)
test_manage_py = os.path.join(testproject_dir, "additional_dir", "extra.py")
with open(test_manage_py) as fp:
content = fp.read()
self.assertIn("<&>", content)
def test_custom_project_destination_missing(self):
"""
Make sure an exception is raised when the provided
destination directory doesn't exist
"""
template_path = os.path.join(custom_templates_dir, "project_template")
args = [
"startproject",
"--template",
template_path,
"yet_another_project",
"project_dir2",
]
testproject_dir = os.path.join(self.test_dir, "project_dir2")
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(
err,
"Destination directory '%s' does not exist, please create it first."
% testproject_dir,
)
self.assertFalse(os.path.exists(testproject_dir))
def test_custom_project_template_with_non_ascii_templates(self):
"""
The startproject management command is able to render templates with
non-ASCII content.
"""
template_path = os.path.join(custom_templates_dir, "project_template")
args = [
"startproject",
"--template",
template_path,
"--extension=txt",
"customtestproject",
]
testproject_dir = os.path.join(self.test_dir, "customtestproject")
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertTrue(os.path.isdir(testproject_dir))
path = os.path.join(testproject_dir, "ticket-18091-non-ascii-template.txt")
with open(path, encoding="utf-8") as f:
self.assertEqual(
f.read().splitlines(False),
["Some non-ASCII text for testing ticket #18091:", "üäö €"],
)
def test_custom_project_template_hidden_directory_default_excluded(self):
"""Hidden directories are excluded by default."""
template_path = os.path.join(custom_templates_dir, "project_template")
args = [
"startproject",
"--template",
template_path,
"custom_project_template_hidden_directories",
"project_dir",
]
testproject_dir = os.path.join(self.test_dir, "project_dir")
os.mkdir(testproject_dir)
_, err = self.run_django_admin(args)
self.assertNoOutput(err)
hidden_dir = os.path.join(testproject_dir, ".hidden")
self.assertIs(os.path.exists(hidden_dir), False)
def test_custom_project_template_hidden_directory_included(self):
"""
Template context variables in hidden directories are rendered, if not
excluded.
"""
template_path = os.path.join(custom_templates_dir, "project_template")
project_name = "custom_project_template_hidden_directories_included"
args = [
"startproject",
"--template",
template_path,
project_name,
"project_dir",
"--exclude",
]
testproject_dir = os.path.join(self.test_dir, "project_dir")
os.mkdir(testproject_dir)
_, err = self.run_django_admin(args)
self.assertNoOutput(err)
render_py_path = os.path.join(testproject_dir, ".hidden", "render.py")
with open(render_py_path) as fp:
self.assertIn(
f"# The {project_name} should be rendered.",
fp.read(),
)
def test_custom_project_template_exclude_directory(self):
"""
Excluded directories (in addition to .git and __pycache__) are not
included in the project.
"""
template_path = os.path.join(custom_templates_dir, "project_template")
project_name = "custom_project_with_excluded_directories"
args = [
"startproject",
"--template",
template_path,
project_name,
"project_dir",
"--exclude",
"additional_dir",
"-x",
".hidden",
]
testproject_dir = os.path.join(self.test_dir, "project_dir")
os.mkdir(testproject_dir)
_, err = self.run_django_admin(args)
self.assertNoOutput(err)
excluded_directories = [
".hidden",
"additional_dir",
".git",
"__pycache__",
]
for directory in excluded_directories:
self.assertIs(
os.path.exists(os.path.join(testproject_dir, directory)),
False,
)
not_excluded = os.path.join(testproject_dir, project_name)
self.assertIs(os.path.exists(not_excluded), True)
@unittest.skipIf(
sys.platform == "win32",
"Windows only partially supports umasks and chmod.",
)
@unittest.skipUnless(PY39, "subprocess.run()'s umask was added in Python 3.9.")
def test_honor_umask(self):
_, err = self.run_django_admin(["startproject", "testproject"], umask=0o077)
self.assertNoOutput(err)
testproject_dir = os.path.join(self.test_dir, "testproject")
self.assertIs(os.path.isdir(testproject_dir), True)
tests = [
(["manage.py"], 0o700),
(["testproject"], 0o700),
(["testproject", "settings.py"], 0o600),
]
for paths, expected_mode in tests:
file_path = os.path.join(testproject_dir, *paths)
with self.subTest(paths[-1]):
self.assertEqual(
stat.S_IMODE(os.stat(file_path).st_mode),
expected_mode,
)
class StartApp(AdminScriptTestCase):
def test_invalid_name(self):
"""startapp validates that app name is a valid Python identifier."""
for bad_name in ("7testproject", "../testproject"):
with self.subTest(app_name=bad_name):
args = ["startapp", bad_name]
testproject_dir = os.path.join(self.test_dir, bad_name)
out, err = self.run_django_admin(args)
self.assertOutput(
err,
"CommandError: '{}' is not a valid app name. Please make "
"sure the name is a valid identifier.".format(bad_name),
)
self.assertFalse(os.path.exists(testproject_dir))
def test_importable_name(self):
"""
startapp validates that app name doesn't clash with existing Python
modules.
"""
bad_name = "os"
args = ["startapp", bad_name]
testproject_dir = os.path.join(self.test_dir, bad_name)
out, err = self.run_django_admin(args)
self.assertOutput(
err,
"CommandError: 'os' conflicts with the name of an existing "
"Python module and cannot be used as an app name. Please try "
"another name.",
)
self.assertFalse(os.path.exists(testproject_dir))
def test_invalid_target_name(self):
for bad_target in (
"invalid.dir_name",
"7invalid_dir_name",
".invalid_dir_name",
):
with self.subTest(bad_target):
_, err = self.run_django_admin(["startapp", "app", bad_target])
self.assertOutput(
err,
"CommandError: '%s' is not a valid app directory. Please "
"make sure the directory is a valid identifier." % bad_target,
)
def test_importable_target_name(self):
_, err = self.run_django_admin(["startapp", "app", "os"])
self.assertOutput(
err,
"CommandError: 'os' conflicts with the name of an existing Python "
"module and cannot be used as an app directory. Please try "
"another directory.",
)
def test_trailing_slash_in_target_app_directory_name(self):
app_dir = os.path.join(self.test_dir, "apps", "app1")
os.makedirs(app_dir)
_, err = self.run_django_admin(
["startapp", "app", os.path.join("apps", "app1", "")]
)
self.assertNoOutput(err)
self.assertIs(os.path.exists(os.path.join(app_dir, "apps.py")), True)
def test_overlaying_app(self):
# Use a subdirectory so it is outside the PYTHONPATH.
os.makedirs(os.path.join(self.test_dir, "apps/app1"))
self.run_django_admin(["startapp", "app1", "apps/app1"])
out, err = self.run_django_admin(["startapp", "app2", "apps/app1"])
self.assertOutput(
err,
"already exists. Overlaying an app into an existing directory "
"won't replace conflicting files.",
)
def test_template(self):
out, err = self.run_django_admin(["startapp", "new_app"])
self.assertNoOutput(err)
app_path = os.path.join(self.test_dir, "new_app")
self.assertIs(os.path.exists(app_path), True)
with open(os.path.join(app_path, "apps.py")) as f:
content = f.read()
self.assertIn("class NewAppConfig(AppConfig)", content)
if HAS_BLACK:
test_str = 'default_auto_field = "django.db.models.BigAutoField"'
else:
test_str = "default_auto_field = 'django.db.models.BigAutoField'"
self.assertIn(test_str, content)
self.assertIn(
'name = "new_app"' if HAS_BLACK else "name = 'new_app'",
content,
)
class DiffSettings(AdminScriptTestCase):
"""Tests for diffsettings management command."""
def test_basic(self):
"""Runs without error and emits settings diff."""
self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'})
args = ["diffsettings", "--settings=settings_to_diff"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "FOO = 'bar' ###")
# Attributes from django.conf.Settings don't appear.
self.assertNotInOutput(out, "is_overridden = ")
def test_settings_configured(self):
out, err = self.run_manage(
["diffsettings"], manage_py="configured_settings_manage.py"
)
self.assertNoOutput(err)
self.assertOutput(out, "CUSTOM = 1 ###\nDEBUG = True")
# Attributes from django.conf.UserSettingsHolder don't appear.
self.assertNotInOutput(out, "default_settings = ")
def test_dynamic_settings_configured(self):
# Custom default settings appear.
out, err = self.run_manage(
["diffsettings"], manage_py="configured_dynamic_settings_manage.py"
)
self.assertNoOutput(err)
self.assertOutput(out, "FOO = 'bar' ###")
def test_all(self):
"""The all option also shows settings with the default value."""
self.write_settings("settings_to_diff.py", sdict={"STATIC_URL": "None"})
args = ["diffsettings", "--settings=settings_to_diff", "--all"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "### STATIC_URL = None")
def test_custom_default(self):
"""
The --default option specifies an alternate settings module for
comparison.
"""
self.write_settings(
"settings_default.py", sdict={"FOO": '"foo"', "BAR": '"bar1"'}
)
self.write_settings(
"settings_to_diff.py", sdict={"FOO": '"foo"', "BAR": '"bar2"'}
)
out, err = self.run_manage(
[
"diffsettings",
"--settings=settings_to_diff",
"--default=settings_default",
]
)
self.assertNoOutput(err)
self.assertNotInOutput(out, "FOO")
self.assertOutput(out, "BAR = 'bar2'")
def test_unified(self):
"""--output=unified emits settings diff in unified mode."""
self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'})
args = ["diffsettings", "--settings=settings_to_diff", "--output=unified"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "+ FOO = 'bar'")
self.assertOutput(out, "- SECRET_KEY = ''")
self.assertOutput(out, "+ SECRET_KEY = 'django_tests_secret_key'")
self.assertNotInOutput(out, " APPEND_SLASH = True")
def test_unified_all(self):
"""
--output=unified --all emits settings diff in unified mode and includes
settings with the default value.
"""
self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'})
args = [
"diffsettings",
"--settings=settings_to_diff",
"--output=unified",
"--all",
]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, " APPEND_SLASH = True")
self.assertOutput(out, "+ FOO = 'bar'")
self.assertOutput(out, "- SECRET_KEY = ''")
class Dumpdata(AdminScriptTestCase):
"""Tests for dumpdata management command."""
def setUp(self):
super().setUp()
self.write_settings("settings.py")
def test_pks_parsing(self):
"""Regression for #20509
Test would raise an exception rather than printing an error message.
"""
args = ["dumpdata", "--pks=1"]
out, err = self.run_manage(args)
self.assertOutput(err, "You can only use --pks option with one model")
self.assertNoOutput(out)
class MainModule(AdminScriptTestCase):
"""python -m django works like django-admin."""
def test_program_name_in_help(self):
out, err = self.run_test(["-m", "django", "help"])
self.assertOutput(
out,
"Type 'python -m django help <subcommand>' for help on a specific "
"subcommand.",
)
class DjangoAdminSuggestions(AdminScriptTestCase):
def setUp(self):
super().setUp()
self.write_settings("settings.py")
def test_suggestions(self):
args = ["rnserver", "--settings=test_project.settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'rnserver'. Did you mean runserver?")
def test_no_suggestions(self):
args = ["abcdef", "--settings=test_project.settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertNotInOutput(err, "Did you mean")
|
ac3d27e2f5567a98d6ba29c57a3721fce1e0a3ea368b5a7c5a7e4aada5860f3c | from math import ceil
from operator import attrgetter
from django.core.exceptions import FieldDoesNotExist
from django.db import (
IntegrityError,
NotSupportedError,
OperationalError,
ProgrammingError,
connection,
)
from django.db.models import FileField, Value
from django.db.models.functions import Lower
from django.test import (
TestCase,
override_settings,
skipIfDBFeature,
skipUnlessDBFeature,
)
from .models import (
BigAutoFieldModel,
Country,
NoFields,
NullableFields,
Pizzeria,
ProxyCountry,
ProxyMultiCountry,
ProxyMultiProxyCountry,
ProxyProxyCountry,
RelatedModel,
Restaurant,
SmallAutoFieldModel,
State,
TwoFields,
UpsertConflict,
)
class BulkCreateTests(TestCase):
def setUp(self):
self.data = [
Country(name="United States of America", iso_two_letter="US"),
Country(name="The Netherlands", iso_two_letter="NL"),
Country(name="Germany", iso_two_letter="DE"),
Country(name="Czech Republic", iso_two_letter="CZ"),
]
def test_simple(self):
created = Country.objects.bulk_create(self.data)
self.assertEqual(created, self.data)
self.assertQuerySetEqual(
Country.objects.order_by("-name"),
[
"United States of America",
"The Netherlands",
"Germany",
"Czech Republic",
],
attrgetter("name"),
)
created = Country.objects.bulk_create([])
self.assertEqual(created, [])
self.assertEqual(Country.objects.count(), 4)
@skipUnlessDBFeature("has_bulk_insert")
def test_efficiency(self):
with self.assertNumQueries(1):
Country.objects.bulk_create(self.data)
@skipUnlessDBFeature("has_bulk_insert")
def test_long_non_ascii_text(self):
"""
Inserting non-ASCII values with a length in the range 2001 to 4000
characters, i.e. 4002 to 8000 bytes, must be set as a CLOB on Oracle
(#22144).
"""
Country.objects.bulk_create([Country(description="Ж" * 3000)])
self.assertEqual(Country.objects.count(), 1)
@skipUnlessDBFeature("has_bulk_insert")
def test_long_and_short_text(self):
Country.objects.bulk_create(
[
Country(description="a" * 4001, iso_two_letter="A"),
Country(description="a", iso_two_letter="B"),
Country(description="Ж" * 2001, iso_two_letter="C"),
Country(description="Ж", iso_two_letter="D"),
]
)
self.assertEqual(Country.objects.count(), 4)
def test_multi_table_inheritance_unsupported(self):
expected_message = "Can't bulk create a multi-table inherited model"
with self.assertRaisesMessage(ValueError, expected_message):
Pizzeria.objects.bulk_create(
[
Pizzeria(name="The Art of Pizza"),
]
)
with self.assertRaisesMessage(ValueError, expected_message):
ProxyMultiCountry.objects.bulk_create(
[
ProxyMultiCountry(name="Fillory", iso_two_letter="FL"),
]
)
with self.assertRaisesMessage(ValueError, expected_message):
ProxyMultiProxyCountry.objects.bulk_create(
[
ProxyMultiProxyCountry(name="Fillory", iso_two_letter="FL"),
]
)
def test_proxy_inheritance_supported(self):
ProxyCountry.objects.bulk_create(
[
ProxyCountry(name="Qwghlm", iso_two_letter="QW"),
Country(name="Tortall", iso_two_letter="TA"),
]
)
self.assertQuerySetEqual(
ProxyCountry.objects.all(),
{"Qwghlm", "Tortall"},
attrgetter("name"),
ordered=False,
)
ProxyProxyCountry.objects.bulk_create(
[
ProxyProxyCountry(name="Netherlands", iso_two_letter="NT"),
]
)
self.assertQuerySetEqual(
ProxyProxyCountry.objects.all(),
{
"Qwghlm",
"Tortall",
"Netherlands",
},
attrgetter("name"),
ordered=False,
)
def test_non_auto_increment_pk(self):
State.objects.bulk_create(
[State(two_letter_code=s) for s in ["IL", "NY", "CA", "ME"]]
)
self.assertQuerySetEqual(
State.objects.order_by("two_letter_code"),
[
"CA",
"IL",
"ME",
"NY",
],
attrgetter("two_letter_code"),
)
@skipUnlessDBFeature("has_bulk_insert")
def test_non_auto_increment_pk_efficiency(self):
with self.assertNumQueries(1):
State.objects.bulk_create(
[State(two_letter_code=s) for s in ["IL", "NY", "CA", "ME"]]
)
self.assertQuerySetEqual(
State.objects.order_by("two_letter_code"),
[
"CA",
"IL",
"ME",
"NY",
],
attrgetter("two_letter_code"),
)
@skipIfDBFeature("allows_auto_pk_0")
def test_zero_as_autoval(self):
"""
Zero as id for AutoField should raise exception in MySQL, because MySQL
does not allow zero for automatic primary key if the
NO_AUTO_VALUE_ON_ZERO SQL mode is not enabled.
"""
valid_country = Country(name="Germany", iso_two_letter="DE")
invalid_country = Country(id=0, name="Poland", iso_two_letter="PL")
msg = "The database backend does not accept 0 as a value for AutoField."
with self.assertRaisesMessage(ValueError, msg):
Country.objects.bulk_create([valid_country, invalid_country])
def test_batch_same_vals(self):
# SQLite had a problem where all the same-valued models were
# collapsed to one insert.
Restaurant.objects.bulk_create([Restaurant(name="foo") for i in range(0, 2)])
self.assertEqual(Restaurant.objects.count(), 2)
def test_large_batch(self):
TwoFields.objects.bulk_create(
[TwoFields(f1=i, f2=i + 1) for i in range(0, 1001)]
)
self.assertEqual(TwoFields.objects.count(), 1001)
self.assertEqual(
TwoFields.objects.filter(f1__gte=450, f1__lte=550).count(), 101
)
self.assertEqual(TwoFields.objects.filter(f2__gte=901).count(), 101)
@skipUnlessDBFeature("has_bulk_insert")
def test_large_single_field_batch(self):
# SQLite had a problem with more than 500 UNIONed selects in single
# query.
Restaurant.objects.bulk_create([Restaurant() for i in range(0, 501)])
@skipUnlessDBFeature("has_bulk_insert")
def test_large_batch_efficiency(self):
with override_settings(DEBUG=True):
connection.queries_log.clear()
TwoFields.objects.bulk_create(
[TwoFields(f1=i, f2=i + 1) for i in range(0, 1001)]
)
self.assertLess(len(connection.queries), 10)
def test_large_batch_mixed(self):
"""
Test inserting a large batch with objects having primary key set
mixed together with objects without PK set.
"""
TwoFields.objects.bulk_create(
[
TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1)
for i in range(100000, 101000)
]
)
self.assertEqual(TwoFields.objects.count(), 1000)
# We can't assume much about the ID's created, except that the above
# created IDs must exist.
id_range = range(100000, 101000, 2)
self.assertEqual(TwoFields.objects.filter(id__in=id_range).count(), 500)
self.assertEqual(TwoFields.objects.exclude(id__in=id_range).count(), 500)
@skipUnlessDBFeature("has_bulk_insert")
def test_large_batch_mixed_efficiency(self):
"""
Test inserting a large batch with objects having primary key set
mixed together with objects without PK set.
"""
with override_settings(DEBUG=True):
connection.queries_log.clear()
TwoFields.objects.bulk_create(
[
TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1)
for i in range(100000, 101000)
]
)
self.assertLess(len(connection.queries), 10)
def test_explicit_batch_size(self):
objs = [TwoFields(f1=i, f2=i) for i in range(0, 4)]
num_objs = len(objs)
TwoFields.objects.bulk_create(objs, batch_size=1)
self.assertEqual(TwoFields.objects.count(), num_objs)
TwoFields.objects.all().delete()
TwoFields.objects.bulk_create(objs, batch_size=2)
self.assertEqual(TwoFields.objects.count(), num_objs)
TwoFields.objects.all().delete()
TwoFields.objects.bulk_create(objs, batch_size=3)
self.assertEqual(TwoFields.objects.count(), num_objs)
TwoFields.objects.all().delete()
TwoFields.objects.bulk_create(objs, batch_size=num_objs)
self.assertEqual(TwoFields.objects.count(), num_objs)
def test_empty_model(self):
NoFields.objects.bulk_create([NoFields() for i in range(2)])
self.assertEqual(NoFields.objects.count(), 2)
@skipUnlessDBFeature("has_bulk_insert")
def test_explicit_batch_size_efficiency(self):
objs = [TwoFields(f1=i, f2=i) for i in range(0, 100)]
with self.assertNumQueries(2):
TwoFields.objects.bulk_create(objs, 50)
TwoFields.objects.all().delete()
with self.assertNumQueries(1):
TwoFields.objects.bulk_create(objs, len(objs))
@skipUnlessDBFeature("has_bulk_insert")
def test_explicit_batch_size_respects_max_batch_size(self):
objs = [Country(name=f"Country {i}") for i in range(1000)]
fields = ["name", "iso_two_letter", "description"]
max_batch_size = max(connection.ops.bulk_batch_size(fields, objs), 1)
with self.assertNumQueries(ceil(len(objs) / max_batch_size)):
Country.objects.bulk_create(objs, batch_size=max_batch_size + 1)
@skipUnlessDBFeature("has_bulk_insert")
def test_bulk_insert_expressions(self):
Restaurant.objects.bulk_create(
[
Restaurant(name="Sam's Shake Shack"),
Restaurant(name=Lower(Value("Betty's Beetroot Bar"))),
]
)
bbb = Restaurant.objects.filter(name="betty's beetroot bar")
self.assertEqual(bbb.count(), 1)
@skipUnlessDBFeature("has_bulk_insert")
def test_bulk_insert_nullable_fields(self):
fk_to_auto_fields = {
"auto_field": NoFields.objects.create(),
"small_auto_field": SmallAutoFieldModel.objects.create(),
"big_auto_field": BigAutoFieldModel.objects.create(),
}
# NULL can be mixed with other values in nullable fields
nullable_fields = [
field for field in NullableFields._meta.get_fields() if field.name != "id"
]
NullableFields.objects.bulk_create(
[
NullableFields(**{**fk_to_auto_fields, field.name: None})
for field in nullable_fields
]
)
self.assertEqual(NullableFields.objects.count(), len(nullable_fields))
for field in nullable_fields:
with self.subTest(field=field):
field_value = "" if isinstance(field, FileField) else None
self.assertEqual(
NullableFields.objects.filter(**{field.name: field_value}).count(),
1,
)
@skipUnlessDBFeature("can_return_rows_from_bulk_insert")
def test_set_pk_and_insert_single_item(self):
with self.assertNumQueries(1):
countries = Country.objects.bulk_create([self.data[0]])
self.assertEqual(len(countries), 1)
self.assertEqual(Country.objects.get(pk=countries[0].pk), countries[0])
@skipUnlessDBFeature("can_return_rows_from_bulk_insert")
def test_set_pk_and_query_efficiency(self):
with self.assertNumQueries(1):
countries = Country.objects.bulk_create(self.data)
self.assertEqual(len(countries), 4)
self.assertEqual(Country.objects.get(pk=countries[0].pk), countries[0])
self.assertEqual(Country.objects.get(pk=countries[1].pk), countries[1])
self.assertEqual(Country.objects.get(pk=countries[2].pk), countries[2])
self.assertEqual(Country.objects.get(pk=countries[3].pk), countries[3])
@skipUnlessDBFeature("can_return_rows_from_bulk_insert")
def test_set_state(self):
country_nl = Country(name="Netherlands", iso_two_letter="NL")
country_be = Country(name="Belgium", iso_two_letter="BE")
Country.objects.bulk_create([country_nl])
country_be.save()
# Objects save via bulk_create() and save() should have equal state.
self.assertEqual(country_nl._state.adding, country_be._state.adding)
self.assertEqual(country_nl._state.db, country_be._state.db)
def test_set_state_with_pk_specified(self):
state_ca = State(two_letter_code="CA")
state_ny = State(two_letter_code="NY")
State.objects.bulk_create([state_ca])
state_ny.save()
# Objects save via bulk_create() and save() should have equal state.
self.assertEqual(state_ca._state.adding, state_ny._state.adding)
self.assertEqual(state_ca._state.db, state_ny._state.db)
@skipIfDBFeature("supports_ignore_conflicts")
def test_ignore_conflicts_value_error(self):
message = "This database backend does not support ignoring conflicts."
with self.assertRaisesMessage(NotSupportedError, message):
TwoFields.objects.bulk_create(self.data, ignore_conflicts=True)
@skipUnlessDBFeature("supports_ignore_conflicts")
def test_ignore_conflicts_ignore(self):
data = [
TwoFields(f1=1, f2=1),
TwoFields(f1=2, f2=2),
TwoFields(f1=3, f2=3),
]
TwoFields.objects.bulk_create(data)
self.assertEqual(TwoFields.objects.count(), 3)
# With ignore_conflicts=True, conflicts are ignored.
conflicting_objects = [
TwoFields(f1=2, f2=2),
TwoFields(f1=3, f2=3),
]
TwoFields.objects.bulk_create([conflicting_objects[0]], ignore_conflicts=True)
TwoFields.objects.bulk_create(conflicting_objects, ignore_conflicts=True)
self.assertEqual(TwoFields.objects.count(), 3)
self.assertIsNone(conflicting_objects[0].pk)
self.assertIsNone(conflicting_objects[1].pk)
# New objects are created and conflicts are ignored.
new_object = TwoFields(f1=4, f2=4)
TwoFields.objects.bulk_create(
conflicting_objects + [new_object], ignore_conflicts=True
)
self.assertEqual(TwoFields.objects.count(), 4)
self.assertIsNone(new_object.pk)
# Without ignore_conflicts=True, there's a problem.
with self.assertRaises(IntegrityError):
TwoFields.objects.bulk_create(conflicting_objects)
def test_nullable_fk_after_parent(self):
parent = NoFields()
child = NullableFields(auto_field=parent, integer_field=88)
parent.save()
NullableFields.objects.bulk_create([child])
child = NullableFields.objects.get(integer_field=88)
self.assertEqual(child.auto_field, parent)
@skipUnlessDBFeature("can_return_rows_from_bulk_insert")
def test_nullable_fk_after_parent_bulk_create(self):
parent = NoFields()
child = NullableFields(auto_field=parent, integer_field=88)
NoFields.objects.bulk_create([parent])
NullableFields.objects.bulk_create([child])
child = NullableFields.objects.get(integer_field=88)
self.assertEqual(child.auto_field, parent)
def test_unsaved_parent(self):
parent = NoFields()
msg = (
"bulk_create() prohibited to prevent data loss due to unsaved "
"related object 'auto_field'."
)
with self.assertRaisesMessage(ValueError, msg):
NullableFields.objects.bulk_create([NullableFields(auto_field=parent)])
def test_invalid_batch_size_exception(self):
msg = "Batch size must be a positive integer."
with self.assertRaisesMessage(ValueError, msg):
Country.objects.bulk_create([], batch_size=-1)
@skipIfDBFeature("supports_update_conflicts")
def test_update_conflicts_unsupported(self):
msg = "This database backend does not support updating conflicts."
with self.assertRaisesMessage(NotSupportedError, msg):
Country.objects.bulk_create(self.data, update_conflicts=True)
@skipUnlessDBFeature("supports_ignore_conflicts", "supports_update_conflicts")
def test_ignore_update_conflicts_exclusive(self):
msg = "ignore_conflicts and update_conflicts are mutually exclusive"
with self.assertRaisesMessage(ValueError, msg):
Country.objects.bulk_create(
self.data,
ignore_conflicts=True,
update_conflicts=True,
)
@skipUnlessDBFeature("supports_update_conflicts")
def test_update_conflicts_no_update_fields(self):
msg = (
"Fields that will be updated when a row insertion fails on "
"conflicts must be provided."
)
with self.assertRaisesMessage(ValueError, msg):
Country.objects.bulk_create(self.data, update_conflicts=True)
@skipUnlessDBFeature("supports_update_conflicts")
@skipIfDBFeature("supports_update_conflicts_with_target")
def test_update_conflicts_unique_field_unsupported(self):
msg = (
"This database backend does not support updating conflicts with "
"specifying unique fields that can trigger the upsert."
)
with self.assertRaisesMessage(NotSupportedError, msg):
TwoFields.objects.bulk_create(
[TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2)],
update_conflicts=True,
update_fields=["f2"],
unique_fields=["f1"],
)
@skipUnlessDBFeature("supports_update_conflicts")
def test_update_conflicts_nonexistent_update_fields(self):
unique_fields = None
if connection.features.supports_update_conflicts_with_target:
unique_fields = ["f1"]
msg = "TwoFields has no field named 'nonexistent'"
with self.assertRaisesMessage(FieldDoesNotExist, msg):
TwoFields.objects.bulk_create(
[TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2)],
update_conflicts=True,
update_fields=["nonexistent"],
unique_fields=unique_fields,
)
@skipUnlessDBFeature(
"supports_update_conflicts",
"supports_update_conflicts_with_target",
)
def test_update_conflicts_unique_fields_required(self):
msg = "Unique fields that can trigger the upsert must be provided."
with self.assertRaisesMessage(ValueError, msg):
TwoFields.objects.bulk_create(
[TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2)],
update_conflicts=True,
update_fields=["f1"],
)
@skipUnlessDBFeature(
"supports_update_conflicts",
"supports_update_conflicts_with_target",
)
def test_update_conflicts_invalid_update_fields(self):
msg = "bulk_create() can only be used with concrete fields in update_fields."
# Reverse one-to-one relationship.
with self.assertRaisesMessage(ValueError, msg):
Country.objects.bulk_create(
self.data,
update_conflicts=True,
update_fields=["relatedmodel"],
unique_fields=["pk"],
)
# Many-to-many relationship.
with self.assertRaisesMessage(ValueError, msg):
RelatedModel.objects.bulk_create(
[RelatedModel(country=self.data[0])],
update_conflicts=True,
update_fields=["big_auto_fields"],
unique_fields=["country"],
)
@skipUnlessDBFeature(
"supports_update_conflicts",
"supports_update_conflicts_with_target",
)
def test_update_conflicts_pk_in_update_fields(self):
msg = "bulk_create() cannot be used with primary keys in update_fields."
with self.assertRaisesMessage(ValueError, msg):
BigAutoFieldModel.objects.bulk_create(
[BigAutoFieldModel()],
update_conflicts=True,
update_fields=["id"],
unique_fields=["id"],
)
@skipUnlessDBFeature(
"supports_update_conflicts",
"supports_update_conflicts_with_target",
)
def test_update_conflicts_invalid_unique_fields(self):
msg = "bulk_create() can only be used with concrete fields in unique_fields."
# Reverse one-to-one relationship.
with self.assertRaisesMessage(ValueError, msg):
Country.objects.bulk_create(
self.data,
update_conflicts=True,
update_fields=["name"],
unique_fields=["relatedmodel"],
)
# Many-to-many relationship.
with self.assertRaisesMessage(ValueError, msg):
RelatedModel.objects.bulk_create(
[RelatedModel(country=self.data[0])],
update_conflicts=True,
update_fields=["name"],
unique_fields=["big_auto_fields"],
)
def _test_update_conflicts_two_fields(self, unique_fields):
TwoFields.objects.bulk_create(
[
TwoFields(f1=1, f2=1, name="a"),
TwoFields(f1=2, f2=2, name="b"),
]
)
self.assertEqual(TwoFields.objects.count(), 2)
conflicting_objects = [
TwoFields(f1=1, f2=1, name="c"),
TwoFields(f1=2, f2=2, name="d"),
]
TwoFields.objects.bulk_create(
conflicting_objects,
update_conflicts=True,
unique_fields=unique_fields,
update_fields=["name"],
)
self.assertEqual(TwoFields.objects.count(), 2)
self.assertCountEqual(
TwoFields.objects.values("f1", "f2", "name"),
[
{"f1": 1, "f2": 1, "name": "c"},
{"f1": 2, "f2": 2, "name": "d"},
],
)
@skipUnlessDBFeature(
"supports_update_conflicts", "supports_update_conflicts_with_target"
)
def test_update_conflicts_two_fields_unique_fields_first(self):
self._test_update_conflicts_two_fields(["f1"])
@skipUnlessDBFeature(
"supports_update_conflicts", "supports_update_conflicts_with_target"
)
def test_update_conflicts_two_fields_unique_fields_second(self):
self._test_update_conflicts_two_fields(["f2"])
@skipUnlessDBFeature(
"supports_update_conflicts", "supports_update_conflicts_with_target"
)
def test_update_conflicts_two_fields_unique_fields_both(self):
with self.assertRaises((OperationalError, ProgrammingError)):
self._test_update_conflicts_two_fields(["f1", "f2"])
@skipUnlessDBFeature("supports_update_conflicts")
@skipIfDBFeature("supports_update_conflicts_with_target")
def test_update_conflicts_two_fields_no_unique_fields(self):
self._test_update_conflicts_two_fields([])
def _test_update_conflicts_unique_two_fields(self, unique_fields):
Country.objects.bulk_create(self.data)
self.assertEqual(Country.objects.count(), 4)
new_data = [
# Conflicting countries.
Country(
name="Germany",
iso_two_letter="DE",
description=("Germany is a country in Central Europe."),
),
Country(
name="Czech Republic",
iso_two_letter="CZ",
description=(
"The Czech Republic is a landlocked country in Central Europe."
),
),
# New countries.
Country(name="Australia", iso_two_letter="AU"),
Country(
name="Japan",
iso_two_letter="JP",
description=("Japan is an island country in East Asia."),
),
]
Country.objects.bulk_create(
new_data,
update_conflicts=True,
update_fields=["description"],
unique_fields=unique_fields,
)
self.assertEqual(Country.objects.count(), 6)
self.assertCountEqual(
Country.objects.values("iso_two_letter", "description"),
[
{"iso_two_letter": "US", "description": ""},
{"iso_two_letter": "NL", "description": ""},
{
"iso_two_letter": "DE",
"description": ("Germany is a country in Central Europe."),
},
{
"iso_two_letter": "CZ",
"description": (
"The Czech Republic is a landlocked country in Central Europe."
),
},
{"iso_two_letter": "AU", "description": ""},
{
"iso_two_letter": "JP",
"description": ("Japan is an island country in East Asia."),
},
],
)
@skipUnlessDBFeature(
"supports_update_conflicts", "supports_update_conflicts_with_target"
)
def test_update_conflicts_unique_two_fields_unique_fields_both(self):
self._test_update_conflicts_unique_two_fields(["iso_two_letter", "name"])
@skipUnlessDBFeature(
"supports_update_conflicts", "supports_update_conflicts_with_target"
)
def test_update_conflicts_unique_two_fields_unique_fields_one(self):
with self.assertRaises((OperationalError, ProgrammingError)):
self._test_update_conflicts_unique_two_fields(["iso_two_letter"])
@skipUnlessDBFeature("supports_update_conflicts")
@skipIfDBFeature("supports_update_conflicts_with_target")
def test_update_conflicts_unique_two_fields_unique_no_unique_fields(self):
self._test_update_conflicts_unique_two_fields([])
def _test_update_conflicts(self, unique_fields):
UpsertConflict.objects.bulk_create(
[
UpsertConflict(number=1, rank=1, name="John"),
UpsertConflict(number=2, rank=2, name="Mary"),
UpsertConflict(number=3, rank=3, name="Hannah"),
]
)
self.assertEqual(UpsertConflict.objects.count(), 3)
conflicting_objects = [
UpsertConflict(number=1, rank=4, name="Steve"),
UpsertConflict(number=2, rank=2, name="Olivia"),
UpsertConflict(number=3, rank=1, name="Hannah"),
]
UpsertConflict.objects.bulk_create(
conflicting_objects,
update_conflicts=True,
update_fields=["name", "rank"],
unique_fields=unique_fields,
)
self.assertEqual(UpsertConflict.objects.count(), 3)
self.assertCountEqual(
UpsertConflict.objects.values("number", "rank", "name"),
[
{"number": 1, "rank": 4, "name": "Steve"},
{"number": 2, "rank": 2, "name": "Olivia"},
{"number": 3, "rank": 1, "name": "Hannah"},
],
)
UpsertConflict.objects.bulk_create(
conflicting_objects + [UpsertConflict(number=4, rank=4, name="Mark")],
update_conflicts=True,
update_fields=["name", "rank"],
unique_fields=unique_fields,
)
self.assertEqual(UpsertConflict.objects.count(), 4)
self.assertCountEqual(
UpsertConflict.objects.values("number", "rank", "name"),
[
{"number": 1, "rank": 4, "name": "Steve"},
{"number": 2, "rank": 2, "name": "Olivia"},
{"number": 3, "rank": 1, "name": "Hannah"},
{"number": 4, "rank": 4, "name": "Mark"},
],
)
@skipUnlessDBFeature(
"supports_update_conflicts", "supports_update_conflicts_with_target"
)
def test_update_conflicts_unique_fields(self):
self._test_update_conflicts(unique_fields=["number"])
@skipUnlessDBFeature("supports_update_conflicts")
@skipIfDBFeature("supports_update_conflicts_with_target")
def test_update_conflicts_no_unique_fields(self):
self._test_update_conflicts([])
|
e4882184e6bb7be03465cc9bd32dc750580584a017a71406ffd7ec94f1520862 | """
Regression tests for Model inheritance behavior.
"""
import datetime
from operator import attrgetter
from unittest import expectedFailure
from django import forms
from django.test import TestCase
from .models import (
ArticleWithAuthor,
BachelorParty,
BirthdayParty,
BusStation,
Child,
Congressman,
DerivedM,
InternalCertificationAudit,
ItalianRestaurant,
M2MChild,
MessyBachelorParty,
ParkingLot,
ParkingLot3,
ParkingLot4A,
ParkingLot4B,
Person,
Place,
Politician,
Profile,
QualityControl,
Restaurant,
SelfRefChild,
SelfRefParent,
Senator,
Supplier,
TrainStation,
User,
Wholesaler,
)
class ModelInheritanceTest(TestCase):
def test_model_inheritance(self):
# Regression for #7350, #7202
# When you create a Parent object with a specific reference to an
# existent child instance, saving the Parent doesn't duplicate the
# child. This behavior is only activated during a raw save - it is
# mostly relevant to deserialization, but any sort of CORBA style
# 'narrow()' API would require a similar approach.
# Create a child-parent-grandparent chain
place1 = Place(name="Guido's House of Pasta", address="944 W. Fullerton")
place1.save_base(raw=True)
restaurant = Restaurant(
place_ptr=place1,
serves_hot_dogs=True,
serves_pizza=False,
)
restaurant.save_base(raw=True)
italian_restaurant = ItalianRestaurant(
restaurant_ptr=restaurant, serves_gnocchi=True
)
italian_restaurant.save_base(raw=True)
# Create a child-parent chain with an explicit parent link
place2 = Place(name="Main St", address="111 Main St")
place2.save_base(raw=True)
park = ParkingLot(parent=place2, capacity=100)
park.save_base(raw=True)
# No extra parent objects have been created.
places = list(Place.objects.all())
self.assertEqual(places, [place1, place2])
dicts = list(Restaurant.objects.values("name", "serves_hot_dogs"))
self.assertEqual(
dicts, [{"name": "Guido's House of Pasta", "serves_hot_dogs": True}]
)
dicts = list(
ItalianRestaurant.objects.values(
"name", "serves_hot_dogs", "serves_gnocchi"
)
)
self.assertEqual(
dicts,
[
{
"name": "Guido's House of Pasta",
"serves_gnocchi": True,
"serves_hot_dogs": True,
}
],
)
dicts = list(ParkingLot.objects.values("name", "capacity"))
self.assertEqual(
dicts,
[
{
"capacity": 100,
"name": "Main St",
}
],
)
# You can also update objects when using a raw save.
place1.name = "Guido's All New House of Pasta"
place1.save_base(raw=True)
restaurant.serves_hot_dogs = False
restaurant.save_base(raw=True)
italian_restaurant.serves_gnocchi = False
italian_restaurant.save_base(raw=True)
place2.name = "Derelict lot"
place2.save_base(raw=True)
park.capacity = 50
park.save_base(raw=True)
# No extra parent objects after an update, either.
places = list(Place.objects.all())
self.assertEqual(places, [place2, place1])
self.assertEqual(places[0].name, "Derelict lot")
self.assertEqual(places[1].name, "Guido's All New House of Pasta")
dicts = list(Restaurant.objects.values("name", "serves_hot_dogs"))
self.assertEqual(
dicts,
[
{
"name": "Guido's All New House of Pasta",
"serves_hot_dogs": False,
}
],
)
dicts = list(
ItalianRestaurant.objects.values(
"name", "serves_hot_dogs", "serves_gnocchi"
)
)
self.assertEqual(
dicts,
[
{
"name": "Guido's All New House of Pasta",
"serves_gnocchi": False,
"serves_hot_dogs": False,
}
],
)
dicts = list(ParkingLot.objects.values("name", "capacity"))
self.assertEqual(
dicts,
[
{
"capacity": 50,
"name": "Derelict lot",
}
],
)
# If you try to raw_save a parent attribute onto a child object,
# the attribute will be ignored.
italian_restaurant.name = "Lorenzo's Pasta Hut"
italian_restaurant.save_base(raw=True)
# Note that the name has not changed
# - name is an attribute of Place, not ItalianRestaurant
dicts = list(
ItalianRestaurant.objects.values(
"name", "serves_hot_dogs", "serves_gnocchi"
)
)
self.assertEqual(
dicts,
[
{
"name": "Guido's All New House of Pasta",
"serves_gnocchi": False,
"serves_hot_dogs": False,
}
],
)
def test_issue_7105(self):
# Regressions tests for #7105: dates() queries should be able to use
# fields from the parent model as easily as the child.
Child.objects.create(
name="child", created=datetime.datetime(2008, 6, 26, 17, 0, 0)
)
datetimes = list(Child.objects.datetimes("created", "month"))
self.assertEqual(datetimes, [datetime.datetime(2008, 6, 1, 0, 0)])
def test_issue_7276(self):
# Regression test for #7276: calling delete() on a model with
# multi-table inheritance should delete the associated rows from any
# ancestor tables, as well as any descendent objects.
place1 = Place(name="Guido's House of Pasta", address="944 W. Fullerton")
place1.save_base(raw=True)
restaurant = Restaurant(
place_ptr=place1,
serves_hot_dogs=True,
serves_pizza=False,
)
restaurant.save_base(raw=True)
italian_restaurant = ItalianRestaurant(
restaurant_ptr=restaurant, serves_gnocchi=True
)
italian_restaurant.save_base(raw=True)
ident = ItalianRestaurant.objects.all()[0].id
self.assertEqual(Place.objects.get(pk=ident), place1)
Restaurant.objects.create(
name="a",
address="xx",
serves_hot_dogs=True,
serves_pizza=False,
)
# This should delete both Restaurants, plus the related places, plus
# the ItalianRestaurant.
Restaurant.objects.all().delete()
with self.assertRaises(Place.DoesNotExist):
Place.objects.get(pk=ident)
with self.assertRaises(ItalianRestaurant.DoesNotExist):
ItalianRestaurant.objects.get(pk=ident)
def test_issue_6755(self):
"""
Regression test for #6755
"""
r = Restaurant(serves_pizza=False, serves_hot_dogs=False)
r.save()
self.assertEqual(r.id, r.place_ptr_id)
orig_id = r.id
r = Restaurant(place_ptr_id=orig_id, serves_pizza=True, serves_hot_dogs=False)
r.save()
self.assertEqual(r.id, orig_id)
self.assertEqual(r.id, r.place_ptr_id)
def test_issue_11764(self):
"""
Regression test for #11764
"""
wholesalers = list(Wholesaler.objects.select_related())
self.assertEqual(wholesalers, [])
def test_issue_7853(self):
"""
Regression test for #7853
If the parent class has a self-referential link, make sure that any
updates to that link via the child update the right table.
"""
obj = SelfRefChild.objects.create(child_data=37, parent_data=42)
obj.delete()
def test_get_next_previous_by_date(self):
"""
Regression tests for #8076
get_(next/previous)_by_date should work
"""
c1 = ArticleWithAuthor(
headline="ArticleWithAuthor 1",
author="Person 1",
pub_date=datetime.datetime(2005, 8, 1, 3, 0),
)
c1.save()
c2 = ArticleWithAuthor(
headline="ArticleWithAuthor 2",
author="Person 2",
pub_date=datetime.datetime(2005, 8, 1, 10, 0),
)
c2.save()
c3 = ArticleWithAuthor(
headline="ArticleWithAuthor 3",
author="Person 3",
pub_date=datetime.datetime(2005, 8, 2),
)
c3.save()
self.assertEqual(c1.get_next_by_pub_date(), c2)
self.assertEqual(c2.get_next_by_pub_date(), c3)
with self.assertRaises(ArticleWithAuthor.DoesNotExist):
c3.get_next_by_pub_date()
self.assertEqual(c3.get_previous_by_pub_date(), c2)
self.assertEqual(c2.get_previous_by_pub_date(), c1)
with self.assertRaises(ArticleWithAuthor.DoesNotExist):
c1.get_previous_by_pub_date()
def test_inherited_fields(self):
"""
Regression test for #8825 and #9390
Make sure all inherited fields (esp. m2m fields, in this case) appear
on the child class.
"""
m2mchildren = list(M2MChild.objects.filter(articles__isnull=False))
self.assertEqual(m2mchildren, [])
# Ordering should not include any database column more than once (this
# is most likely to occur naturally with model inheritance, so we
# check it here). Regression test for #9390. This necessarily pokes at
# the SQL string for the query, since the duplicate problems are only
# apparent at that late stage.
qs = ArticleWithAuthor.objects.order_by("pub_date", "pk")
sql = qs.query.get_compiler(qs.db).as_sql()[0]
fragment = sql[sql.find("ORDER BY") :]
pos = fragment.find("pub_date")
self.assertEqual(fragment.find("pub_date", pos + 1), -1)
def test_queryset_update_on_parent_model(self):
"""
Regression test for #10362
It is possible to call update() and only change a field in
an ancestor model.
"""
article = ArticleWithAuthor.objects.create(
author="fred",
headline="Hey there!",
pub_date=datetime.datetime(2009, 3, 1, 8, 0, 0),
)
update = ArticleWithAuthor.objects.filter(author="fred").update(
headline="Oh, no!"
)
self.assertEqual(update, 1)
update = ArticleWithAuthor.objects.filter(pk=article.pk).update(
headline="Oh, no!"
)
self.assertEqual(update, 1)
derivedm1 = DerivedM.objects.create(
customPK=44,
base_name="b1",
derived_name="d1",
)
self.assertEqual(derivedm1.customPK, 44)
self.assertEqual(derivedm1.base_name, "b1")
self.assertEqual(derivedm1.derived_name, "d1")
derivedms = list(DerivedM.objects.all())
self.assertEqual(derivedms, [derivedm1])
def test_use_explicit_o2o_to_parent_as_pk(self):
"""
The connector from child to parent need not be the pk on the child.
"""
self.assertEqual(ParkingLot3._meta.pk.name, "primary_key")
# the child->parent link
self.assertEqual(ParkingLot3._meta.get_ancestor_link(Place).name, "parent")
def test_use_explicit_o2o_to_parent_from_abstract_model(self):
self.assertEqual(ParkingLot4A._meta.pk.name, "parent")
ParkingLot4A.objects.create(
name="Parking4A",
address="21 Jump Street",
)
self.assertEqual(ParkingLot4B._meta.pk.name, "parent")
ParkingLot4A.objects.create(
name="Parking4B",
address="21 Jump Street",
)
def test_all_fields_from_abstract_base_class(self):
"""
Regression tests for #7588
"""
# All fields from an ABC, including those inherited non-abstractly
# should be available on child classes (#7588). Creating this instance
# should work without error.
QualityControl.objects.create(
headline="Problems in Django",
pub_date=datetime.datetime.now(),
quality=10,
assignee="adrian",
)
def test_abstract_base_class_m2m_relation_inheritance(self):
# many-to-many relations defined on an abstract base class are
# correctly inherited (and created) on the child class.
p1 = Person.objects.create(name="Alice")
p2 = Person.objects.create(name="Bob")
p3 = Person.objects.create(name="Carol")
p4 = Person.objects.create(name="Dave")
birthday = BirthdayParty.objects.create(name="Birthday party for Alice")
birthday.attendees.set([p1, p3])
bachelor = BachelorParty.objects.create(name="Bachelor party for Bob")
bachelor.attendees.set([p2, p4])
parties = list(p1.birthdayparty_set.all())
self.assertEqual(parties, [birthday])
parties = list(p1.bachelorparty_set.all())
self.assertEqual(parties, [])
parties = list(p2.bachelorparty_set.all())
self.assertEqual(parties, [bachelor])
# A subclass of a subclass of an abstract model doesn't get its own
# accessor.
self.assertFalse(hasattr(p2, "messybachelorparty_set"))
# ... but it does inherit the m2m from its parent
messy = MessyBachelorParty.objects.create(name="Bachelor party for Dave")
messy.attendees.set([p4])
messy_parent = messy.bachelorparty_ptr
parties = list(p4.bachelorparty_set.all())
self.assertEqual(parties, [bachelor, messy_parent])
def test_abstract_verbose_name_plural_inheritance(self):
"""
verbose_name_plural correctly inherited from ABC if inheritance chain
includes an abstract model.
"""
# Regression test for #11369: verbose_name_plural should be inherited
# from an ABC even when there are one or more intermediate
# abstract models in the inheritance chain, for consistency with
# verbose_name.
self.assertEqual(InternalCertificationAudit._meta.verbose_name_plural, "Audits")
def test_inherited_nullable_exclude(self):
obj = SelfRefChild.objects.create(child_data=37, parent_data=42)
self.assertQuerySetEqual(
SelfRefParent.objects.exclude(self_data=72), [obj.pk], attrgetter("pk")
)
self.assertQuerySetEqual(
SelfRefChild.objects.exclude(self_data=72), [obj.pk], attrgetter("pk")
)
def test_concrete_abstract_concrete_pk(self):
"""
Primary key set correctly with concrete->abstract->concrete inheritance.
"""
# Regression test for #13987: Primary key is incorrectly determined
# when more than one model has a concrete->abstract->concrete
# inheritance hierarchy.
self.assertEqual(
len(
[field for field in BusStation._meta.local_fields if field.primary_key]
),
1,
)
self.assertEqual(
len(
[
field
for field in TrainStation._meta.local_fields
if field.primary_key
]
),
1,
)
self.assertIs(BusStation._meta.pk.model, BusStation)
self.assertIs(TrainStation._meta.pk.model, TrainStation)
def test_inherited_unique_field_with_form(self):
"""
A model which has different primary key for the parent model passes
unique field checking correctly (#17615).
"""
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = "__all__"
User.objects.create(username="user_only")
p = Profile.objects.create(username="user_with_profile")
form = ProfileForm(
{"username": "user_with_profile", "extra": "hello"}, instance=p
)
self.assertTrue(form.is_valid())
def test_inheritance_joins(self):
# Test for #17502 - check that filtering through two levels of
# inheritance chain doesn't generate extra joins.
qs = ItalianRestaurant.objects.all()
self.assertEqual(str(qs.query).count("JOIN"), 2)
qs = ItalianRestaurant.objects.filter(name="foo")
self.assertEqual(str(qs.query).count("JOIN"), 2)
@expectedFailure
def test_inheritance_values_joins(self):
# It would be nice (but not too important) to skip the middle join in
# this case. Skipping is possible as nothing from the middle model is
# used in the qs and top contains direct pointer to the bottom model.
qs = ItalianRestaurant.objects.values_list("serves_gnocchi").filter(name="foo")
self.assertEqual(str(qs.query).count("JOIN"), 1)
def test_issue_21554(self):
senator = Senator.objects.create(name="John Doe", title="X", state="Y")
senator = Senator.objects.get(pk=senator.pk)
self.assertEqual(senator.name, "John Doe")
self.assertEqual(senator.title, "X")
self.assertEqual(senator.state, "Y")
def test_inheritance_resolve_columns(self):
Restaurant.objects.create(
name="Bobs Cafe",
address="Somewhere",
serves_pizza=True,
serves_hot_dogs=True,
)
p = Place.objects.select_related("restaurant")[0]
self.assertIsInstance(p.restaurant.serves_pizza, bool)
def test_inheritance_select_related(self):
# Regression test for #7246
r1 = Restaurant.objects.create(
name="Nobu", serves_hot_dogs=True, serves_pizza=False
)
r2 = Restaurant.objects.create(
name="Craft", serves_hot_dogs=False, serves_pizza=True
)
Supplier.objects.create(name="John", restaurant=r1)
Supplier.objects.create(name="Jane", restaurant=r2)
self.assertQuerySetEqual(
Supplier.objects.order_by("name").select_related(),
[
"Jane",
"John",
],
attrgetter("name"),
)
jane = Supplier.objects.order_by("name").select_related("restaurant")[0]
self.assertEqual(jane.restaurant.name, "Craft")
def test_filter_with_parent_fk(self):
r = Restaurant.objects.create()
s = Supplier.objects.create(restaurant=r)
# The mismatch between Restaurant and Place is intentional (#28175).
self.assertSequenceEqual(
Supplier.objects.filter(restaurant__in=Place.objects.all()), [s]
)
def test_ptr_accessor_assigns_state(self):
r = Restaurant.objects.create()
self.assertIs(r.place_ptr._state.adding, False)
self.assertEqual(r.place_ptr._state.db, "default")
def test_related_filtering_query_efficiency_ticket_15844(self):
r = Restaurant.objects.create(
name="Guido's House of Pasta",
address="944 W. Fullerton",
serves_hot_dogs=True,
serves_pizza=False,
)
s = Supplier.objects.create(restaurant=r)
with self.assertNumQueries(1):
self.assertSequenceEqual(Supplier.objects.filter(restaurant=r), [s])
with self.assertNumQueries(1):
self.assertSequenceEqual(r.supplier_set.all(), [s])
def test_queries_on_parent_access(self):
italian_restaurant = ItalianRestaurant.objects.create(
name="Guido's House of Pasta",
address="944 W. Fullerton",
serves_hot_dogs=True,
serves_pizza=False,
serves_gnocchi=True,
)
# No queries are made when accessing the parent objects.
italian_restaurant = ItalianRestaurant.objects.get(pk=italian_restaurant.pk)
with self.assertNumQueries(0):
restaurant = italian_restaurant.restaurant_ptr
self.assertEqual(restaurant.place_ptr.restaurant, restaurant)
self.assertEqual(restaurant.italianrestaurant, italian_restaurant)
# One query is made when accessing the parent objects when the instance
# is deferred.
italian_restaurant = ItalianRestaurant.objects.only("serves_gnocchi").get(
pk=italian_restaurant.pk
)
with self.assertNumQueries(1):
restaurant = italian_restaurant.restaurant_ptr
self.assertEqual(restaurant.place_ptr.restaurant, restaurant)
self.assertEqual(restaurant.italianrestaurant, italian_restaurant)
# No queries are made when accessing the parent objects when the
# instance has deferred a field not present in the parent table.
italian_restaurant = ItalianRestaurant.objects.defer("serves_gnocchi").get(
pk=italian_restaurant.pk
)
with self.assertNumQueries(0):
restaurant = italian_restaurant.restaurant_ptr
self.assertEqual(restaurant.place_ptr.restaurant, restaurant)
self.assertEqual(restaurant.italianrestaurant, italian_restaurant)
def test_id_field_update_on_ancestor_change(self):
place1 = Place.objects.create(name="House of Pasta", address="944 Fullerton")
place2 = Place.objects.create(name="House of Pizza", address="954 Fullerton")
place3 = Place.objects.create(name="Burger house", address="964 Fullerton")
restaurant1 = Restaurant.objects.create(
place_ptr=place1,
serves_hot_dogs=True,
serves_pizza=False,
)
restaurant2 = Restaurant.objects.create(
place_ptr=place2,
serves_hot_dogs=True,
serves_pizza=False,
)
italian_restaurant = ItalianRestaurant.objects.create(
restaurant_ptr=restaurant1,
serves_gnocchi=True,
)
# Changing the parent of a restaurant changes the restaurant's ID & PK.
restaurant1.place_ptr = place3
self.assertEqual(restaurant1.pk, place3.pk)
self.assertEqual(restaurant1.id, place3.id)
self.assertEqual(restaurant1.pk, restaurant1.id)
restaurant1.place_ptr = None
self.assertIsNone(restaurant1.pk)
self.assertIsNone(restaurant1.id)
# Changing the parent of an italian restaurant changes the restaurant's
# ID & PK.
italian_restaurant.restaurant_ptr = restaurant2
self.assertEqual(italian_restaurant.pk, restaurant2.pk)
self.assertEqual(italian_restaurant.id, restaurant2.id)
self.assertEqual(italian_restaurant.pk, italian_restaurant.id)
italian_restaurant.restaurant_ptr = None
self.assertIsNone(italian_restaurant.pk)
self.assertIsNone(italian_restaurant.id)
def test_create_new_instance_with_pk_equals_none(self):
p1 = Profile.objects.create(username="john")
p2 = User.objects.get(pk=p1.user_ptr_id).profile
# Create a new profile by setting pk = None.
p2.pk = None
p2.user_ptr_id = None
p2.username = "bill"
p2.save()
self.assertEqual(Profile.objects.count(), 2)
self.assertEqual(User.objects.get(pk=p1.user_ptr_id).username, "john")
def test_create_new_instance_with_pk_equals_none_multi_inheritance(self):
c1 = Congressman.objects.create(state="PA", name="John", title="senator 1")
c2 = Person.objects.get(pk=c1.pk).congressman
# Create a new congressman by setting pk = None.
c2.pk = None
c2.id = None
c2.politician_ptr_id = None
c2.name = "Bill"
c2.title = "senator 2"
c2.save()
self.assertEqual(Congressman.objects.count(), 2)
self.assertEqual(Person.objects.get(pk=c1.pk).name, "John")
self.assertEqual(
Politician.objects.get(pk=c1.politician_ptr_id).title,
"senator 1",
)
def test_mti_update_parent_through_child(self):
Politician.objects.create()
Congressman.objects.create()
Congressman.objects.update(title="senator 1")
self.assertEqual(Congressman.objects.get().title, "senator 1")
def test_mti_update_grand_parent_through_child(self):
Politician.objects.create()
Senator.objects.create()
Senator.objects.update(title="senator 1")
self.assertEqual(Senator.objects.get().title, "senator 1")
|
c7f6ce499618404bd67221142ce71f4da22b9a5e44074fd0459f00a3978bed21 | import datetime
from decimal import Decimal
from unittest import mock
from django.core.exceptions import FieldError
from django.db import NotSupportedError, connection
from django.db.models import (
Avg,
Case,
Count,
F,
IntegerField,
Max,
Min,
OuterRef,
Q,
RowRange,
Subquery,
Sum,
Value,
ValueRange,
When,
Window,
WindowFrame,
)
from django.db.models.fields.json import KeyTextTransform, KeyTransform
from django.db.models.functions import (
Cast,
CumeDist,
DenseRank,
ExtractYear,
FirstValue,
Lag,
LastValue,
Lead,
NthValue,
Ntile,
PercentRank,
Rank,
RowNumber,
Upper,
)
from django.db.models.lookups import Exact
from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature
from .models import Classification, Detail, Employee, PastEmployeeDepartment
@skipUnlessDBFeature("supports_over_clause")
class WindowFunctionTests(TestCase):
@classmethod
def setUpTestData(cls):
classification = Classification.objects.create()
Employee.objects.bulk_create(
[
Employee(
name=e[0],
salary=e[1],
department=e[2],
hire_date=e[3],
age=e[4],
bonus=Decimal(e[1]) / 400,
classification=classification,
)
for e in [
("Jones", 45000, "Accounting", datetime.datetime(2005, 11, 1), 20),
(
"Williams",
37000,
"Accounting",
datetime.datetime(2009, 6, 1),
20,
),
("Jenson", 45000, "Accounting", datetime.datetime(2008, 4, 1), 20),
("Adams", 50000, "Accounting", datetime.datetime(2013, 7, 1), 50),
("Smith", 55000, "Sales", datetime.datetime(2007, 6, 1), 30),
("Brown", 53000, "Sales", datetime.datetime(2009, 9, 1), 30),
("Johnson", 40000, "Marketing", datetime.datetime(2012, 3, 1), 30),
("Smith", 38000, "Marketing", datetime.datetime(2009, 10, 1), 20),
("Wilkinson", 60000, "IT", datetime.datetime(2011, 3, 1), 40),
("Moore", 34000, "IT", datetime.datetime(2013, 8, 1), 40),
("Miller", 100000, "Management", datetime.datetime(2005, 6, 1), 40),
("Johnson", 80000, "Management", datetime.datetime(2005, 7, 1), 50),
]
]
)
employees = list(Employee.objects.order_by("pk"))
PastEmployeeDepartment.objects.bulk_create(
[
PastEmployeeDepartment(employee=employees[6], department="Sales"),
PastEmployeeDepartment(employee=employees[10], department="IT"),
]
)
def test_dense_rank(self):
tests = [
ExtractYear(F("hire_date")).asc(),
F("hire_date__year").asc(),
"hire_date__year",
]
for order_by in tests:
with self.subTest(order_by=order_by):
qs = Employee.objects.annotate(
rank=Window(expression=DenseRank(), order_by=order_by),
)
self.assertQuerySetEqual(
qs,
[
("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 1),
("Miller", 100000, "Management", datetime.date(2005, 6, 1), 1),
("Johnson", 80000, "Management", datetime.date(2005, 7, 1), 1),
("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 2),
("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 3),
("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 4),
("Brown", 53000, "Sales", datetime.date(2009, 9, 1), 4),
("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 4),
("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 5),
("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), 6),
("Moore", 34000, "IT", datetime.date(2013, 8, 1), 7),
("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), 7),
],
lambda entry: (
entry.name,
entry.salary,
entry.department,
entry.hire_date,
entry.rank,
),
ordered=False,
)
def test_department_salary(self):
qs = Employee.objects.annotate(
department_sum=Window(
expression=Sum("salary"),
partition_by=F("department"),
order_by=[F("hire_date").asc()],
)
).order_by("department", "department_sum")
self.assertQuerySetEqual(
qs,
[
("Jones", "Accounting", 45000, 45000),
("Jenson", "Accounting", 45000, 90000),
("Williams", "Accounting", 37000, 127000),
("Adams", "Accounting", 50000, 177000),
("Wilkinson", "IT", 60000, 60000),
("Moore", "IT", 34000, 94000),
("Miller", "Management", 100000, 100000),
("Johnson", "Management", 80000, 180000),
("Smith", "Marketing", 38000, 38000),
("Johnson", "Marketing", 40000, 78000),
("Smith", "Sales", 55000, 55000),
("Brown", "Sales", 53000, 108000),
],
lambda entry: (
entry.name,
entry.department,
entry.salary,
entry.department_sum,
),
)
def test_rank(self):
"""
Rank the employees based on the year they're were hired. Since there
are multiple employees hired in different years, this will contain
gaps.
"""
qs = Employee.objects.annotate(
rank=Window(
expression=Rank(),
order_by=F("hire_date__year").asc(),
)
)
self.assertQuerySetEqual(
qs,
[
("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 1),
("Miller", 100000, "Management", datetime.date(2005, 6, 1), 1),
("Johnson", 80000, "Management", datetime.date(2005, 7, 1), 1),
("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 4),
("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 5),
("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 6),
("Brown", 53000, "Sales", datetime.date(2009, 9, 1), 6),
("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 6),
("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 9),
("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), 10),
("Moore", 34000, "IT", datetime.date(2013, 8, 1), 11),
("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), 11),
],
lambda entry: (
entry.name,
entry.salary,
entry.department,
entry.hire_date,
entry.rank,
),
ordered=False,
)
def test_row_number(self):
"""
The row number window function computes the number based on the order
in which the tuples were inserted. Depending on the backend,
Oracle requires an ordering-clause in the Window expression.
"""
qs = Employee.objects.annotate(
row_number=Window(
expression=RowNumber(),
order_by=F("pk").asc(),
)
).order_by("pk")
self.assertQuerySetEqual(
qs,
[
("Jones", "Accounting", 1),
("Williams", "Accounting", 2),
("Jenson", "Accounting", 3),
("Adams", "Accounting", 4),
("Smith", "Sales", 5),
("Brown", "Sales", 6),
("Johnson", "Marketing", 7),
("Smith", "Marketing", 8),
("Wilkinson", "IT", 9),
("Moore", "IT", 10),
("Miller", "Management", 11),
("Johnson", "Management", 12),
],
lambda entry: (entry.name, entry.department, entry.row_number),
)
def test_row_number_no_ordering(self):
"""
The row number window function computes the number based on the order
in which the tuples were inserted.
"""
# Add a default ordering for consistent results across databases.
qs = Employee.objects.annotate(
row_number=Window(
expression=RowNumber(),
)
).order_by("pk")
self.assertQuerySetEqual(
qs,
[
("Jones", "Accounting", 1),
("Williams", "Accounting", 2),
("Jenson", "Accounting", 3),
("Adams", "Accounting", 4),
("Smith", "Sales", 5),
("Brown", "Sales", 6),
("Johnson", "Marketing", 7),
("Smith", "Marketing", 8),
("Wilkinson", "IT", 9),
("Moore", "IT", 10),
("Miller", "Management", 11),
("Johnson", "Management", 12),
],
lambda entry: (entry.name, entry.department, entry.row_number),
)
def test_avg_salary_department(self):
qs = Employee.objects.annotate(
avg_salary=Window(
expression=Avg("salary"),
order_by=F("department").asc(),
partition_by="department",
)
).order_by("department", "-salary", "name")
self.assertQuerySetEqual(
qs,
[
("Adams", 50000, "Accounting", 44250.00),
("Jenson", 45000, "Accounting", 44250.00),
("Jones", 45000, "Accounting", 44250.00),
("Williams", 37000, "Accounting", 44250.00),
("Wilkinson", 60000, "IT", 47000.00),
("Moore", 34000, "IT", 47000.00),
("Miller", 100000, "Management", 90000.00),
("Johnson", 80000, "Management", 90000.00),
("Johnson", 40000, "Marketing", 39000.00),
("Smith", 38000, "Marketing", 39000.00),
("Smith", 55000, "Sales", 54000.00),
("Brown", 53000, "Sales", 54000.00),
],
transform=lambda row: (
row.name,
row.salary,
row.department,
row.avg_salary,
),
)
def test_lag(self):
"""
Compute the difference between an employee's salary and the next
highest salary in the employee's department. Return None if the
employee has the lowest salary.
"""
qs = Employee.objects.annotate(
lag=Window(
expression=Lag(expression="salary", offset=1),
partition_by=F("department"),
order_by=[F("salary").asc(), F("name").asc()],
)
).order_by("department", F("salary").asc(), F("name").asc())
self.assertQuerySetEqual(
qs,
[
("Williams", 37000, "Accounting", None),
("Jenson", 45000, "Accounting", 37000),
("Jones", 45000, "Accounting", 45000),
("Adams", 50000, "Accounting", 45000),
("Moore", 34000, "IT", None),
("Wilkinson", 60000, "IT", 34000),
("Johnson", 80000, "Management", None),
("Miller", 100000, "Management", 80000),
("Smith", 38000, "Marketing", None),
("Johnson", 40000, "Marketing", 38000),
("Brown", 53000, "Sales", None),
("Smith", 55000, "Sales", 53000),
],
transform=lambda row: (row.name, row.salary, row.department, row.lag),
)
def test_lag_decimalfield(self):
qs = Employee.objects.annotate(
lag=Window(
expression=Lag(expression="bonus", offset=1),
partition_by=F("department"),
order_by=[F("bonus").asc(), F("name").asc()],
)
).order_by("department", F("bonus").asc(), F("name").asc())
self.assertQuerySetEqual(
qs,
[
("Williams", 92.5, "Accounting", None),
("Jenson", 112.5, "Accounting", 92.5),
("Jones", 112.5, "Accounting", 112.5),
("Adams", 125, "Accounting", 112.5),
("Moore", 85, "IT", None),
("Wilkinson", 150, "IT", 85),
("Johnson", 200, "Management", None),
("Miller", 250, "Management", 200),
("Smith", 95, "Marketing", None),
("Johnson", 100, "Marketing", 95),
("Brown", 132.5, "Sales", None),
("Smith", 137.5, "Sales", 132.5),
],
transform=lambda row: (row.name, row.bonus, row.department, row.lag),
)
def test_first_value(self):
qs = Employee.objects.annotate(
first_value=Window(
expression=FirstValue("salary"),
partition_by=F("department"),
order_by=F("hire_date").asc(),
)
).order_by("department", "hire_date")
self.assertQuerySetEqual(
qs,
[
("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 45000),
("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 45000),
("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 45000),
("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), 45000),
("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 60000),
("Moore", 34000, "IT", datetime.date(2013, 8, 1), 60000),
("Miller", 100000, "Management", datetime.date(2005, 6, 1), 100000),
("Johnson", 80000, "Management", datetime.date(2005, 7, 1), 100000),
("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 38000),
("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), 38000),
("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 55000),
("Brown", 53000, "Sales", datetime.date(2009, 9, 1), 55000),
],
lambda row: (
row.name,
row.salary,
row.department,
row.hire_date,
row.first_value,
),
)
def test_last_value(self):
qs = Employee.objects.annotate(
last_value=Window(
expression=LastValue("hire_date"),
partition_by=F("department"),
order_by=F("hire_date").asc(),
)
)
self.assertQuerySetEqual(
qs,
[
(
"Adams",
"Accounting",
datetime.date(2013, 7, 1),
50000,
datetime.date(2013, 7, 1),
),
(
"Jenson",
"Accounting",
datetime.date(2008, 4, 1),
45000,
datetime.date(2008, 4, 1),
),
(
"Jones",
"Accounting",
datetime.date(2005, 11, 1),
45000,
datetime.date(2005, 11, 1),
),
(
"Williams",
"Accounting",
datetime.date(2009, 6, 1),
37000,
datetime.date(2009, 6, 1),
),
(
"Moore",
"IT",
datetime.date(2013, 8, 1),
34000,
datetime.date(2013, 8, 1),
),
(
"Wilkinson",
"IT",
datetime.date(2011, 3, 1),
60000,
datetime.date(2011, 3, 1),
),
(
"Miller",
"Management",
datetime.date(2005, 6, 1),
100000,
datetime.date(2005, 6, 1),
),
(
"Johnson",
"Management",
datetime.date(2005, 7, 1),
80000,
datetime.date(2005, 7, 1),
),
(
"Johnson",
"Marketing",
datetime.date(2012, 3, 1),
40000,
datetime.date(2012, 3, 1),
),
(
"Smith",
"Marketing",
datetime.date(2009, 10, 1),
38000,
datetime.date(2009, 10, 1),
),
(
"Brown",
"Sales",
datetime.date(2009, 9, 1),
53000,
datetime.date(2009, 9, 1),
),
(
"Smith",
"Sales",
datetime.date(2007, 6, 1),
55000,
datetime.date(2007, 6, 1),
),
],
transform=lambda row: (
row.name,
row.department,
row.hire_date,
row.salary,
row.last_value,
),
ordered=False,
)
def test_function_list_of_values(self):
qs = (
Employee.objects.annotate(
lead=Window(
expression=Lead(expression="salary"),
order_by=[F("hire_date").asc(), F("name").desc()],
partition_by="department",
)
)
.values_list("name", "salary", "department", "hire_date", "lead")
.order_by("department", F("hire_date").asc(), F("name").desc())
)
self.assertNotIn("GROUP BY", str(qs.query))
self.assertSequenceEqual(
qs,
[
("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 45000),
("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 37000),
("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 50000),
("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), None),
("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 34000),
("Moore", 34000, "IT", datetime.date(2013, 8, 1), None),
("Miller", 100000, "Management", datetime.date(2005, 6, 1), 80000),
("Johnson", 80000, "Management", datetime.date(2005, 7, 1), None),
("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 40000),
("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), None),
("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 53000),
("Brown", 53000, "Sales", datetime.date(2009, 9, 1), None),
],
)
def test_min_department(self):
"""An alternative way to specify a query for FirstValue."""
qs = Employee.objects.annotate(
min_salary=Window(
expression=Min("salary"),
partition_by=F("department"),
order_by=[F("salary").asc(), F("name").asc()],
)
).order_by("department", "salary", "name")
self.assertQuerySetEqual(
qs,
[
("Williams", "Accounting", 37000, 37000),
("Jenson", "Accounting", 45000, 37000),
("Jones", "Accounting", 45000, 37000),
("Adams", "Accounting", 50000, 37000),
("Moore", "IT", 34000, 34000),
("Wilkinson", "IT", 60000, 34000),
("Johnson", "Management", 80000, 80000),
("Miller", "Management", 100000, 80000),
("Smith", "Marketing", 38000, 38000),
("Johnson", "Marketing", 40000, 38000),
("Brown", "Sales", 53000, 53000),
("Smith", "Sales", 55000, 53000),
],
lambda row: (row.name, row.department, row.salary, row.min_salary),
)
def test_max_per_year(self):
"""
Find the maximum salary awarded in the same year as the
employee was hired, regardless of the department.
"""
qs = Employee.objects.annotate(
max_salary_year=Window(
expression=Max("salary"),
order_by=ExtractYear("hire_date").asc(),
partition_by=ExtractYear("hire_date"),
)
).order_by(ExtractYear("hire_date"), "salary")
self.assertQuerySetEqual(
qs,
[
("Jones", "Accounting", 45000, 2005, 100000),
("Johnson", "Management", 80000, 2005, 100000),
("Miller", "Management", 100000, 2005, 100000),
("Smith", "Sales", 55000, 2007, 55000),
("Jenson", "Accounting", 45000, 2008, 45000),
("Williams", "Accounting", 37000, 2009, 53000),
("Smith", "Marketing", 38000, 2009, 53000),
("Brown", "Sales", 53000, 2009, 53000),
("Wilkinson", "IT", 60000, 2011, 60000),
("Johnson", "Marketing", 40000, 2012, 40000),
("Moore", "IT", 34000, 2013, 50000),
("Adams", "Accounting", 50000, 2013, 50000),
],
lambda row: (
row.name,
row.department,
row.salary,
row.hire_date.year,
row.max_salary_year,
),
)
def test_cume_dist(self):
"""
Compute the cumulative distribution for the employees based on the
salary in increasing order. Equal to rank/total number of rows (12).
"""
qs = Employee.objects.annotate(
cume_dist=Window(
expression=CumeDist(),
order_by=F("salary").asc(),
)
).order_by("salary", "name")
# Round result of cume_dist because Oracle uses greater precision.
self.assertQuerySetEqual(
qs,
[
("Moore", "IT", 34000, 0.0833333333),
("Williams", "Accounting", 37000, 0.1666666667),
("Smith", "Marketing", 38000, 0.25),
("Johnson", "Marketing", 40000, 0.3333333333),
("Jenson", "Accounting", 45000, 0.5),
("Jones", "Accounting", 45000, 0.5),
("Adams", "Accounting", 50000, 0.5833333333),
("Brown", "Sales", 53000, 0.6666666667),
("Smith", "Sales", 55000, 0.75),
("Wilkinson", "IT", 60000, 0.8333333333),
("Johnson", "Management", 80000, 0.9166666667),
("Miller", "Management", 100000, 1),
],
lambda row: (
row.name,
row.department,
row.salary,
round(row.cume_dist, 10),
),
)
def test_nthvalue(self):
qs = Employee.objects.annotate(
nth_value=Window(
expression=NthValue(expression="salary", nth=2),
order_by=[F("hire_date").asc(), F("name").desc()],
partition_by=F("department"),
)
).order_by("department", "hire_date", "name")
self.assertQuerySetEqual(
qs,
[
("Jones", "Accounting", datetime.date(2005, 11, 1), 45000, None),
("Jenson", "Accounting", datetime.date(2008, 4, 1), 45000, 45000),
("Williams", "Accounting", datetime.date(2009, 6, 1), 37000, 45000),
("Adams", "Accounting", datetime.date(2013, 7, 1), 50000, 45000),
("Wilkinson", "IT", datetime.date(2011, 3, 1), 60000, None),
("Moore", "IT", datetime.date(2013, 8, 1), 34000, 34000),
("Miller", "Management", datetime.date(2005, 6, 1), 100000, None),
("Johnson", "Management", datetime.date(2005, 7, 1), 80000, 80000),
("Smith", "Marketing", datetime.date(2009, 10, 1), 38000, None),
("Johnson", "Marketing", datetime.date(2012, 3, 1), 40000, 40000),
("Smith", "Sales", datetime.date(2007, 6, 1), 55000, None),
("Brown", "Sales", datetime.date(2009, 9, 1), 53000, 53000),
],
lambda row: (
row.name,
row.department,
row.hire_date,
row.salary,
row.nth_value,
),
)
def test_lead(self):
"""
Determine what the next person hired in the same department makes.
Because the dataset is ambiguous, the name is also part of the
ordering clause. No default is provided, so None/NULL should be
returned.
"""
qs = Employee.objects.annotate(
lead=Window(
expression=Lead(expression="salary"),
order_by=[F("hire_date").asc(), F("name").desc()],
partition_by="department",
)
).order_by("department", F("hire_date").asc(), F("name").desc())
self.assertQuerySetEqual(
qs,
[
("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 45000),
("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 37000),
("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 50000),
("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), None),
("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 34000),
("Moore", 34000, "IT", datetime.date(2013, 8, 1), None),
("Miller", 100000, "Management", datetime.date(2005, 6, 1), 80000),
("Johnson", 80000, "Management", datetime.date(2005, 7, 1), None),
("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 40000),
("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), None),
("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 53000),
("Brown", 53000, "Sales", datetime.date(2009, 9, 1), None),
],
transform=lambda row: (
row.name,
row.salary,
row.department,
row.hire_date,
row.lead,
),
)
def test_lead_offset(self):
"""
Determine what the person hired after someone makes. Due to
ambiguity, the name is also included in the ordering.
"""
qs = Employee.objects.annotate(
lead=Window(
expression=Lead("salary", offset=2),
partition_by="department",
order_by=F("hire_date").asc(),
)
)
self.assertQuerySetEqual(
qs,
[
("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 37000),
("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 50000),
("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), None),
("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), None),
("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), None),
("Moore", 34000, "IT", datetime.date(2013, 8, 1), None),
("Johnson", 80000, "Management", datetime.date(2005, 7, 1), None),
("Miller", 100000, "Management", datetime.date(2005, 6, 1), None),
("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), None),
("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), None),
("Smith", 55000, "Sales", datetime.date(2007, 6, 1), None),
("Brown", 53000, "Sales", datetime.date(2009, 9, 1), None),
],
transform=lambda row: (
row.name,
row.salary,
row.department,
row.hire_date,
row.lead,
),
ordered=False,
)
@skipUnlessDBFeature("supports_default_in_lead_lag")
def test_lead_default(self):
qs = Employee.objects.annotate(
lead_default=Window(
expression=Lead(expression="salary", offset=5, default=60000),
partition_by=F("department"),
order_by=F("department").asc(),
)
)
self.assertEqual(
list(qs.values_list("lead_default", flat=True).distinct()), [60000]
)
def test_ntile(self):
"""
Compute the group for each of the employees across the entire company,
based on how high the salary is for them. There are twelve employees
so it divides evenly into four groups.
"""
qs = Employee.objects.annotate(
ntile=Window(
expression=Ntile(num_buckets=4),
order_by="-salary",
)
).order_by("ntile", "-salary", "name")
self.assertQuerySetEqual(
qs,
[
("Miller", "Management", 100000, 1),
("Johnson", "Management", 80000, 1),
("Wilkinson", "IT", 60000, 1),
("Smith", "Sales", 55000, 2),
("Brown", "Sales", 53000, 2),
("Adams", "Accounting", 50000, 2),
("Jenson", "Accounting", 45000, 3),
("Jones", "Accounting", 45000, 3),
("Johnson", "Marketing", 40000, 3),
("Smith", "Marketing", 38000, 4),
("Williams", "Accounting", 37000, 4),
("Moore", "IT", 34000, 4),
],
lambda x: (x.name, x.department, x.salary, x.ntile),
)
def test_percent_rank(self):
"""
Calculate the percentage rank of the employees across the entire
company based on salary and name (in case of ambiguity).
"""
qs = Employee.objects.annotate(
percent_rank=Window(
expression=PercentRank(),
order_by=[F("salary").asc(), F("name").asc()],
)
).order_by("percent_rank")
# Round to account for precision differences among databases.
self.assertQuerySetEqual(
qs,
[
("Moore", "IT", 34000, 0.0),
("Williams", "Accounting", 37000, 0.0909090909),
("Smith", "Marketing", 38000, 0.1818181818),
("Johnson", "Marketing", 40000, 0.2727272727),
("Jenson", "Accounting", 45000, 0.3636363636),
("Jones", "Accounting", 45000, 0.4545454545),
("Adams", "Accounting", 50000, 0.5454545455),
("Brown", "Sales", 53000, 0.6363636364),
("Smith", "Sales", 55000, 0.7272727273),
("Wilkinson", "IT", 60000, 0.8181818182),
("Johnson", "Management", 80000, 0.9090909091),
("Miller", "Management", 100000, 1.0),
],
transform=lambda row: (
row.name,
row.department,
row.salary,
round(row.percent_rank, 10),
),
)
def test_nth_returns_null(self):
"""
Find the nth row of the data set. None is returned since there are
fewer than 20 rows in the test data.
"""
qs = Employee.objects.annotate(
nth_value=Window(
expression=NthValue("salary", nth=20), order_by=F("salary").asc()
)
)
self.assertEqual(
list(qs.values_list("nth_value", flat=True).distinct()), [None]
)
def test_multiple_partitioning(self):
"""
Find the maximum salary for each department for people hired in the
same year.
"""
qs = Employee.objects.annotate(
max=Window(
expression=Max("salary"),
partition_by=[F("department"), F("hire_date__year")],
)
).order_by("department", "hire_date", "name")
self.assertQuerySetEqual(
qs,
[
("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 45000),
("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 45000),
("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 37000),
("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), 50000),
("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 60000),
("Moore", 34000, "IT", datetime.date(2013, 8, 1), 34000),
("Miller", 100000, "Management", datetime.date(2005, 6, 1), 100000),
("Johnson", 80000, "Management", datetime.date(2005, 7, 1), 100000),
("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 38000),
("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), 40000),
("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 55000),
("Brown", 53000, "Sales", datetime.date(2009, 9, 1), 53000),
],
transform=lambda row: (
row.name,
row.salary,
row.department,
row.hire_date,
row.max,
),
)
def test_multiple_ordering(self):
"""
Accumulate the salaries over the departments based on hire_date.
If two people were hired on the same date in the same department, the
ordering clause will render a different result for those people.
"""
qs = Employee.objects.annotate(
sum=Window(
expression=Sum("salary"),
partition_by="department",
order_by=[F("hire_date").asc(), F("name").asc()],
)
).order_by("department", "sum")
self.assertQuerySetEqual(
qs,
[
("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 45000),
("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 90000),
("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 127000),
("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), 177000),
("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 60000),
("Moore", 34000, "IT", datetime.date(2013, 8, 1), 94000),
("Miller", 100000, "Management", datetime.date(2005, 6, 1), 100000),
("Johnson", 80000, "Management", datetime.date(2005, 7, 1), 180000),
("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 38000),
("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), 78000),
("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 55000),
("Brown", 53000, "Sales", datetime.date(2009, 9, 1), 108000),
],
transform=lambda row: (
row.name,
row.salary,
row.department,
row.hire_date,
row.sum,
),
)
def test_related_ordering_with_count(self):
qs = Employee.objects.annotate(
department_sum=Window(
expression=Sum("salary"),
partition_by=F("department"),
order_by=["classification__code"],
)
)
self.assertEqual(qs.count(), 12)
def test_filter(self):
qs = Employee.objects.annotate(
department_salary_rank=Window(
Rank(), partition_by="department", order_by="-salary"
),
department_avg_age_diff=(
Window(Avg("age"), partition_by="department") - F("age")
),
).order_by("department", "name")
# Direct window reference.
self.assertQuerySetEqual(
qs.filter(department_salary_rank=1),
["Adams", "Wilkinson", "Miller", "Johnson", "Smith"],
lambda employee: employee.name,
)
# Through a combined expression containing a window.
self.assertQuerySetEqual(
qs.filter(department_avg_age_diff__gt=0),
["Jenson", "Jones", "Williams", "Miller", "Smith"],
lambda employee: employee.name,
)
# Intersection of multiple windows.
self.assertQuerySetEqual(
qs.filter(department_salary_rank=1, department_avg_age_diff__gt=0),
["Miller"],
lambda employee: employee.name,
)
# Union of multiple windows.
self.assertQuerySetEqual(
qs.filter(Q(department_salary_rank=1) | Q(department_avg_age_diff__gt=0)),
[
"Adams",
"Jenson",
"Jones",
"Williams",
"Wilkinson",
"Miller",
"Johnson",
"Smith",
"Smith",
],
lambda employee: employee.name,
)
def test_filter_conditional_annotation(self):
qs = (
Employee.objects.annotate(
rank=Window(Rank(), partition_by="department", order_by="-salary"),
case_first_rank=Case(
When(rank=1, then=True),
default=False,
),
q_first_rank=Q(rank=1),
)
.order_by("name")
.values_list("name", flat=True)
)
for annotation in ["case_first_rank", "q_first_rank"]:
with self.subTest(annotation=annotation):
self.assertSequenceEqual(
qs.filter(**{annotation: True}),
["Adams", "Johnson", "Miller", "Smith", "Wilkinson"],
)
def test_filter_conditional_expression(self):
qs = (
Employee.objects.filter(
Exact(Window(Rank(), partition_by="department", order_by="-salary"), 1)
)
.order_by("name")
.values_list("name", flat=True)
)
self.assertSequenceEqual(
qs, ["Adams", "Johnson", "Miller", "Smith", "Wilkinson"]
)
def test_filter_column_ref_rhs(self):
qs = (
Employee.objects.annotate(
max_dept_salary=Window(Max("salary"), partition_by="department")
)
.filter(max_dept_salary=F("salary"))
.order_by("name")
.values_list("name", flat=True)
)
self.assertSequenceEqual(
qs, ["Adams", "Johnson", "Miller", "Smith", "Wilkinson"]
)
def test_filter_values(self):
qs = (
Employee.objects.annotate(
department_salary_rank=Window(
Rank(), partition_by="department", order_by="-salary"
),
)
.order_by("department", "name")
.values_list(Upper("name"), flat=True)
)
self.assertSequenceEqual(
qs.filter(department_salary_rank=1),
["ADAMS", "WILKINSON", "MILLER", "JOHNSON", "SMITH"],
)
def test_filter_alias(self):
qs = Employee.objects.alias(
department_avg_age_diff=(
Window(Avg("age"), partition_by="department") - F("age")
),
).order_by("department", "name")
self.assertQuerySetEqual(
qs.filter(department_avg_age_diff__gt=0),
["Jenson", "Jones", "Williams", "Miller", "Smith"],
lambda employee: employee.name,
)
def test_filter_select_related(self):
qs = (
Employee.objects.alias(
department_avg_age_diff=(
Window(Avg("age"), partition_by="department") - F("age")
),
)
.select_related("classification")
.filter(department_avg_age_diff__gt=0)
.order_by("department", "name")
)
self.assertQuerySetEqual(
qs,
["Jenson", "Jones", "Williams", "Miller", "Smith"],
lambda employee: employee.name,
)
with self.assertNumQueries(0):
qs[0].classification
def test_exclude(self):
qs = Employee.objects.annotate(
department_salary_rank=Window(
Rank(), partition_by="department", order_by="-salary"
),
department_avg_age_diff=(
Window(Avg("age"), partition_by="department") - F("age")
),
).order_by("department", "name")
# Direct window reference.
self.assertQuerySetEqual(
qs.exclude(department_salary_rank__gt=1),
["Adams", "Wilkinson", "Miller", "Johnson", "Smith"],
lambda employee: employee.name,
)
# Through a combined expression containing a window.
self.assertQuerySetEqual(
qs.exclude(department_avg_age_diff__lte=0),
["Jenson", "Jones", "Williams", "Miller", "Smith"],
lambda employee: employee.name,
)
# Union of multiple windows.
self.assertQuerySetEqual(
qs.exclude(
Q(department_salary_rank__gt=1) | Q(department_avg_age_diff__lte=0)
),
["Miller"],
lambda employee: employee.name,
)
# Intersection of multiple windows.
self.assertQuerySetEqual(
qs.exclude(department_salary_rank__gt=1, department_avg_age_diff__lte=0),
[
"Adams",
"Jenson",
"Jones",
"Williams",
"Wilkinson",
"Miller",
"Johnson",
"Smith",
"Smith",
],
lambda employee: employee.name,
)
def test_heterogeneous_filter(self):
qs = (
Employee.objects.annotate(
department_salary_rank=Window(
Rank(), partition_by="department", order_by="-salary"
),
)
.order_by("name")
.values_list("name", flat=True)
)
# Heterogeneous filter between window function and aggregates pushes
# the WHERE clause to the QUALIFY outer query.
self.assertSequenceEqual(
qs.filter(
department_salary_rank=1, department__in=["Accounting", "Management"]
),
["Adams", "Miller"],
)
self.assertSequenceEqual(
qs.filter(
Q(department_salary_rank=1)
| Q(department__in=["Accounting", "Management"])
),
[
"Adams",
"Jenson",
"Johnson",
"Johnson",
"Jones",
"Miller",
"Smith",
"Wilkinson",
"Williams",
],
)
# Heterogeneous filter between window function and aggregates pushes
# the HAVING clause to the QUALIFY outer query.
qs = qs.annotate(past_department_count=Count("past_departments"))
self.assertSequenceEqual(
qs.filter(department_salary_rank=1, past_department_count__gte=1),
["Johnson", "Miller"],
)
self.assertSequenceEqual(
qs.filter(Q(department_salary_rank=1) | Q(past_department_count__gte=1)),
["Adams", "Johnson", "Miller", "Smith", "Wilkinson"],
)
def test_limited_filter(self):
"""
A query filtering against a window function have its limit applied
after window filtering takes place.
"""
self.assertQuerySetEqual(
Employee.objects.annotate(
department_salary_rank=Window(
Rank(), partition_by="department", order_by="-salary"
)
)
.filter(department_salary_rank=1)
.order_by("department")[0:3],
["Adams", "Wilkinson", "Miller"],
lambda employee: employee.name,
)
def test_filter_count(self):
self.assertEqual(
Employee.objects.annotate(
department_salary_rank=Window(
Rank(), partition_by="department", order_by="-salary"
)
)
.filter(department_salary_rank=1)
.count(),
5,
)
@skipUnlessDBFeature("supports_frame_range_fixed_distance")
def test_range_n_preceding_and_following(self):
qs = Employee.objects.annotate(
sum=Window(
expression=Sum("salary"),
order_by=F("salary").asc(),
partition_by="department",
frame=ValueRange(start=-2, end=2),
)
)
self.assertIn("RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING", str(qs.query))
self.assertQuerySetEqual(
qs,
[
("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 37000),
("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 90000),
("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 90000),
("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), 50000),
("Brown", 53000, "Sales", datetime.date(2009, 9, 1), 53000),
("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 55000),
("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), 40000),
("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 38000),
("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 60000),
("Moore", 34000, "IT", datetime.date(2013, 8, 1), 34000),
("Miller", 100000, "Management", datetime.date(2005, 6, 1), 100000),
("Johnson", 80000, "Management", datetime.date(2005, 7, 1), 80000),
],
transform=lambda row: (
row.name,
row.salary,
row.department,
row.hire_date,
row.sum,
),
ordered=False,
)
def test_range_unbound(self):
"""A query with RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING."""
qs = Employee.objects.annotate(
sum=Window(
expression=Sum("salary"),
partition_by="age",
order_by=[F("age").asc()],
frame=ValueRange(start=None, end=None),
)
).order_by("department", "hire_date", "name")
self.assertIn(
"RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING", str(qs.query)
)
self.assertQuerySetEqual(
qs,
[
("Jones", "Accounting", 45000, datetime.date(2005, 11, 1), 165000),
("Jenson", "Accounting", 45000, datetime.date(2008, 4, 1), 165000),
("Williams", "Accounting", 37000, datetime.date(2009, 6, 1), 165000),
("Adams", "Accounting", 50000, datetime.date(2013, 7, 1), 130000),
("Wilkinson", "IT", 60000, datetime.date(2011, 3, 1), 194000),
("Moore", "IT", 34000, datetime.date(2013, 8, 1), 194000),
("Miller", "Management", 100000, datetime.date(2005, 6, 1), 194000),
("Johnson", "Management", 80000, datetime.date(2005, 7, 1), 130000),
("Smith", "Marketing", 38000, datetime.date(2009, 10, 1), 165000),
("Johnson", "Marketing", 40000, datetime.date(2012, 3, 1), 148000),
("Smith", "Sales", 55000, datetime.date(2007, 6, 1), 148000),
("Brown", "Sales", 53000, datetime.date(2009, 9, 1), 148000),
],
transform=lambda row: (
row.name,
row.department,
row.salary,
row.hire_date,
row.sum,
),
)
def test_subquery_row_range_rank(self):
qs = Employee.objects.annotate(
highest_avg_salary_date=Subquery(
Employee.objects.filter(
department=OuterRef("department"),
)
.annotate(
avg_salary=Window(
expression=Avg("salary"),
order_by=[F("hire_date").asc()],
frame=RowRange(start=-1, end=1),
),
)
.order_by("-avg_salary", "hire_date")
.values("hire_date")[:1],
),
).order_by("department", "name")
self.assertQuerySetEqual(
qs,
[
("Adams", "Accounting", datetime.date(2005, 11, 1)),
("Jenson", "Accounting", datetime.date(2005, 11, 1)),
("Jones", "Accounting", datetime.date(2005, 11, 1)),
("Williams", "Accounting", datetime.date(2005, 11, 1)),
("Moore", "IT", datetime.date(2011, 3, 1)),
("Wilkinson", "IT", datetime.date(2011, 3, 1)),
("Johnson", "Management", datetime.date(2005, 6, 1)),
("Miller", "Management", datetime.date(2005, 6, 1)),
("Johnson", "Marketing", datetime.date(2009, 10, 1)),
("Smith", "Marketing", datetime.date(2009, 10, 1)),
("Brown", "Sales", datetime.date(2007, 6, 1)),
("Smith", "Sales", datetime.date(2007, 6, 1)),
],
transform=lambda row: (
row.name,
row.department,
row.highest_avg_salary_date,
),
)
def test_row_range_rank(self):
"""
A query with ROWS BETWEEN UNBOUNDED PRECEDING AND 3 FOLLOWING.
The resulting sum is the sum of the three next (if they exist) and all
previous rows according to the ordering clause.
"""
qs = Employee.objects.annotate(
sum=Window(
expression=Sum("salary"),
order_by=[F("hire_date").asc(), F("name").desc()],
frame=RowRange(start=None, end=3),
)
).order_by("sum", "hire_date")
self.assertIn("ROWS BETWEEN UNBOUNDED PRECEDING AND 3 FOLLOWING", str(qs.query))
self.assertQuerySetEqual(
qs,
[
("Miller", 100000, "Management", datetime.date(2005, 6, 1), 280000),
("Johnson", 80000, "Management", datetime.date(2005, 7, 1), 325000),
("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 362000),
("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 415000),
("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 453000),
("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 513000),
("Brown", 53000, "Sales", datetime.date(2009, 9, 1), 553000),
("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 603000),
("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 637000),
("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), 637000),
("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), 637000),
("Moore", 34000, "IT", datetime.date(2013, 8, 1), 637000),
],
transform=lambda row: (
row.name,
row.salary,
row.department,
row.hire_date,
row.sum,
),
)
@skipUnlessDBFeature("can_distinct_on_fields")
def test_distinct_window_function(self):
"""
Window functions are not aggregates, and hence a query to filter out
duplicates may be useful.
"""
qs = (
Employee.objects.annotate(
sum=Window(
expression=Sum("salary"),
partition_by=ExtractYear("hire_date"),
order_by=ExtractYear("hire_date"),
),
year=ExtractYear("hire_date"),
)
.filter(sum__gte=45000)
.values("year", "sum")
.distinct("year")
.order_by("year")
)
results = [
{"year": 2005, "sum": 225000},
{"year": 2007, "sum": 55000},
{"year": 2008, "sum": 45000},
{"year": 2009, "sum": 128000},
{"year": 2011, "sum": 60000},
{"year": 2013, "sum": 84000},
]
for idx, val in zip(range(len(results)), results):
with self.subTest(result=val):
self.assertEqual(qs[idx], val)
def test_fail_update(self):
"""Window expressions can't be used in an UPDATE statement."""
msg = (
"Window expressions are not allowed in this query (salary=<Window: "
"Max(Col(expressions_window_employee, expressions_window.Employee.salary)) "
"OVER (PARTITION BY Col(expressions_window_employee, "
"expressions_window.Employee.department))>)."
)
with self.assertRaisesMessage(FieldError, msg):
Employee.objects.filter(department="Management").update(
salary=Window(expression=Max("salary"), partition_by="department"),
)
def test_fail_insert(self):
"""Window expressions can't be used in an INSERT statement."""
msg = (
"Window expressions are not allowed in this query (salary=<Window: "
"Sum(Value(10000), order_by=OrderBy(F(pk), descending=False)) OVER ()"
)
with self.assertRaisesMessage(FieldError, msg):
Employee.objects.create(
name="Jameson",
department="Management",
hire_date=datetime.date(2007, 7, 1),
salary=Window(expression=Sum(Value(10000), order_by=F("pk").asc())),
)
def test_window_expression_within_subquery(self):
subquery_qs = Employee.objects.annotate(
highest=Window(
FirstValue("id"),
partition_by=F("department"),
order_by=F("salary").desc(),
)
).values("highest")
highest_salary = Employee.objects.filter(pk__in=subquery_qs)
self.assertCountEqual(
highest_salary.values("department", "salary"),
[
{"department": "Accounting", "salary": 50000},
{"department": "Sales", "salary": 55000},
{"department": "Marketing", "salary": 40000},
{"department": "IT", "salary": 60000},
{"department": "Management", "salary": 100000},
],
)
@skipUnlessDBFeature("supports_json_field")
def test_key_transform(self):
Detail.objects.bulk_create(
[
Detail(value={"department": "IT", "name": "Smith", "salary": 37000}),
Detail(value={"department": "IT", "name": "Nowak", "salary": 32000}),
Detail(value={"department": "HR", "name": "Brown", "salary": 50000}),
Detail(value={"department": "HR", "name": "Smith", "salary": 55000}),
Detail(value={"department": "PR", "name": "Moore", "salary": 90000}),
]
)
tests = [
(KeyTransform("department", "value"), KeyTransform("name", "value")),
(F("value__department"), F("value__name")),
]
for partition_by, order_by in tests:
with self.subTest(partition_by=partition_by, order_by=order_by):
qs = Detail.objects.annotate(
department_sum=Window(
expression=Sum(
Cast(
KeyTextTransform("salary", "value"),
output_field=IntegerField(),
)
),
partition_by=[partition_by],
order_by=[order_by],
)
).order_by("value__department", "department_sum")
self.assertQuerySetEqual(
qs,
[
("Brown", "HR", 50000, 50000),
("Smith", "HR", 55000, 105000),
("Nowak", "IT", 32000, 32000),
("Smith", "IT", 37000, 69000),
("Moore", "PR", 90000, 90000),
],
lambda entry: (
entry.value["name"],
entry.value["department"],
entry.value["salary"],
entry.department_sum,
),
)
def test_invalid_start_value_range(self):
msg = "start argument must be a negative integer, zero, or None, but got '3'."
with self.assertRaisesMessage(ValueError, msg):
list(
Employee.objects.annotate(
test=Window(
expression=Sum("salary"),
order_by=F("hire_date").asc(),
frame=ValueRange(start=3),
)
)
)
def test_invalid_end_value_range(self):
msg = "end argument must be a positive integer, zero, or None, but got '-3'."
with self.assertRaisesMessage(ValueError, msg):
list(
Employee.objects.annotate(
test=Window(
expression=Sum("salary"),
order_by=F("hire_date").asc(),
frame=ValueRange(end=-3),
)
)
)
def test_invalid_type_end_value_range(self):
msg = "end argument must be a positive integer, zero, or None, but got 'a'."
with self.assertRaisesMessage(ValueError, msg):
list(
Employee.objects.annotate(
test=Window(
expression=Sum("salary"),
order_by=F("hire_date").asc(),
frame=ValueRange(end="a"),
)
)
)
def test_invalid_type_start_value_range(self):
msg = "start argument must be a negative integer, zero, or None, but got 'a'."
with self.assertRaisesMessage(ValueError, msg):
list(
Employee.objects.annotate(
test=Window(
expression=Sum("salary"),
frame=ValueRange(start="a"),
)
)
)
def test_invalid_type_end_row_range(self):
msg = "end argument must be a positive integer, zero, or None, but got 'a'."
with self.assertRaisesMessage(ValueError, msg):
list(
Employee.objects.annotate(
test=Window(
expression=Sum("salary"),
frame=RowRange(end="a"),
)
)
)
@skipUnlessDBFeature("only_supports_unbounded_with_preceding_and_following")
def test_unsupported_range_frame_start(self):
msg = (
"%s only supports UNBOUNDED together with PRECEDING and FOLLOWING."
% connection.display_name
)
with self.assertRaisesMessage(NotSupportedError, msg):
list(
Employee.objects.annotate(
test=Window(
expression=Sum("salary"),
order_by=F("hire_date").asc(),
frame=ValueRange(start=-1),
)
)
)
@skipUnlessDBFeature("only_supports_unbounded_with_preceding_and_following")
def test_unsupported_range_frame_end(self):
msg = (
"%s only supports UNBOUNDED together with PRECEDING and FOLLOWING."
% connection.display_name
)
with self.assertRaisesMessage(NotSupportedError, msg):
list(
Employee.objects.annotate(
test=Window(
expression=Sum("salary"),
order_by=F("hire_date").asc(),
frame=ValueRange(end=1),
)
)
)
def test_invalid_type_start_row_range(self):
msg = "start argument must be a negative integer, zero, or None, but got 'a'."
with self.assertRaisesMessage(ValueError, msg):
list(
Employee.objects.annotate(
test=Window(
expression=Sum("salary"),
order_by=F("hire_date").asc(),
frame=RowRange(start="a"),
)
)
)
def test_invalid_filter(self):
msg = (
"Heterogeneous disjunctive predicates against window functions are not "
"implemented when performing conditional aggregation."
)
qs = Employee.objects.annotate(
window=Window(Rank()),
past_dept_cnt=Count("past_departments"),
)
with self.assertRaisesMessage(NotImplementedError, msg):
list(qs.filter(Q(window=1) | Q(department="Accounting")))
with self.assertRaisesMessage(NotImplementedError, msg):
list(qs.exclude(window=1, department="Accounting"))
class WindowUnsupportedTests(TestCase):
def test_unsupported_backend(self):
msg = "This backend does not support window expressions."
with mock.patch.object(connection.features, "supports_over_clause", False):
with self.assertRaisesMessage(NotSupportedError, msg):
Employee.objects.annotate(
dense_rank=Window(expression=DenseRank())
).get()
class NonQueryWindowTests(SimpleTestCase):
def test_window_repr(self):
self.assertEqual(
repr(Window(expression=Sum("salary"), partition_by="department")),
"<Window: Sum(F(salary)) OVER (PARTITION BY F(department))>",
)
self.assertEqual(
repr(Window(expression=Avg("salary"), order_by=F("department").asc())),
"<Window: Avg(F(salary)) OVER (OrderByList(OrderBy(F(department), "
"descending=False)))>",
)
def test_window_frame_repr(self):
self.assertEqual(
repr(RowRange(start=-1)),
"<RowRange: ROWS BETWEEN 1 PRECEDING AND UNBOUNDED FOLLOWING>",
)
self.assertEqual(
repr(ValueRange(start=None, end=1)),
"<ValueRange: RANGE BETWEEN UNBOUNDED PRECEDING AND 1 FOLLOWING>",
)
self.assertEqual(
repr(ValueRange(start=0, end=0)),
"<ValueRange: RANGE BETWEEN CURRENT ROW AND CURRENT ROW>",
)
self.assertEqual(
repr(RowRange(start=0, end=0)),
"<RowRange: ROWS BETWEEN CURRENT ROW AND CURRENT ROW>",
)
def test_empty_group_by_cols(self):
window = Window(expression=Sum("pk"))
self.assertEqual(window.get_group_by_cols(), [])
self.assertFalse(window.contains_aggregate)
def test_frame_empty_group_by_cols(self):
frame = WindowFrame()
self.assertEqual(frame.get_group_by_cols(), [])
def test_frame_window_frame_notimplemented(self):
frame = WindowFrame()
msg = "Subclasses must implement window_frame_start_end()."
with self.assertRaisesMessage(NotImplementedError, msg):
frame.window_frame_start_end(None, None, None)
def test_invalid_order_by(self):
msg = (
"Window.order_by must be either a string reference to a field, an "
"expression, or a list or tuple of them."
)
with self.assertRaisesMessage(ValueError, msg):
Window(expression=Sum("power"), order_by={"-horse"})
def test_invalid_source_expression(self):
msg = "Expression 'Upper' isn't compatible with OVER clauses."
with self.assertRaisesMessage(ValueError, msg):
Window(expression=Upper("name"))
|
98de2b580701eaa0b86f59210bdd68b6b5353578e371c73e548f439cc787d96e | from django.db import models
class Classification(models.Model):
code = models.CharField(max_length=10)
class Employee(models.Model):
name = models.CharField(max_length=40, blank=False, null=False)
salary = models.PositiveIntegerField()
department = models.CharField(max_length=40, blank=False, null=False)
hire_date = models.DateField(blank=False, null=False)
age = models.IntegerField(blank=False, null=False)
classification = models.ForeignKey(
"Classification", on_delete=models.CASCADE, null=True
)
bonus = models.DecimalField(decimal_places=2, max_digits=15, null=True)
class PastEmployeeDepartment(models.Model):
employee = models.ForeignKey(
Employee, related_name="past_departments", on_delete=models.CASCADE
)
department = models.CharField(max_length=40, blank=False, null=False)
class Detail(models.Model):
value = models.JSONField()
class Meta:
required_db_features = {"supports_json_field"}
|
59ae2bdc6a0826dd421d8585528a2d41ff0f6443cbcd7c167fb5e1d913fbe955 | from datetime import datetime
from operator import attrgetter
from django.core.exceptions import FieldError
from django.db.models import (
CharField,
Count,
DateTimeField,
F,
Max,
OuterRef,
Subquery,
Value,
)
from django.db.models.functions import Upper
from django.test import TestCase
from .models import (
Article,
Author,
ChildArticle,
OrderedByExpression,
OrderedByExpressionChild,
OrderedByExpressionGrandChild,
OrderedByFArticle,
Reference,
)
class OrderingTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.a1 = Article.objects.create(
headline="Article 1", pub_date=datetime(2005, 7, 26)
)
cls.a2 = Article.objects.create(
headline="Article 2", pub_date=datetime(2005, 7, 27)
)
cls.a3 = Article.objects.create(
headline="Article 3", pub_date=datetime(2005, 7, 27)
)
cls.a4 = Article.objects.create(
headline="Article 4", pub_date=datetime(2005, 7, 28)
)
cls.author_1 = Author.objects.create(name="Name 1")
cls.author_2 = Author.objects.create(name="Name 2")
for i in range(2):
Author.objects.create()
def test_default_ordering(self):
"""
By default, Article.objects.all() orders by pub_date descending, then
headline ascending.
"""
self.assertQuerySetEqual(
Article.objects.all(),
[
"Article 4",
"Article 2",
"Article 3",
"Article 1",
],
attrgetter("headline"),
)
# Getting a single item should work too:
self.assertEqual(Article.objects.all()[0], self.a4)
def test_default_ordering_override(self):
"""
Override ordering with order_by, which is in the same format as the
ordering attribute in models.
"""
self.assertQuerySetEqual(
Article.objects.order_by("headline"),
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.order_by("pub_date", "-headline"),
[
"Article 1",
"Article 3",
"Article 2",
"Article 4",
],
attrgetter("headline"),
)
def test_default_ordering_override_unknown_field(self):
"""
Attempts to override default ordering on related models with an unknown
field should result in an error.
"""
msg = (
"Cannot resolve keyword 'unknown_field' into field. Choices are: "
"article, author, editor, editor_id, id, name"
)
with self.assertRaisesMessage(FieldError, msg):
list(Article.objects.order_by("author__unknown_field"))
def test_order_by_override(self):
"""
Only the last order_by has any effect (since they each override any
previous ordering).
"""
self.assertQuerySetEqual(
Article.objects.order_by("id"),
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.order_by("id").order_by("-headline"),
[
"Article 4",
"Article 3",
"Article 2",
"Article 1",
],
attrgetter("headline"),
)
def test_order_by_nulls_first_and_last(self):
msg = "nulls_first and nulls_last are mutually exclusive"
with self.assertRaisesMessage(ValueError, msg):
Article.objects.order_by(
F("author").desc(nulls_last=True, nulls_first=True)
)
def assertQuerySetEqualReversible(self, queryset, sequence):
self.assertSequenceEqual(queryset, sequence)
self.assertSequenceEqual(queryset.reverse(), list(reversed(sequence)))
def test_order_by_nulls_last(self):
Article.objects.filter(headline="Article 3").update(author=self.author_1)
Article.objects.filter(headline="Article 4").update(author=self.author_2)
# asc and desc are chainable with nulls_last.
self.assertQuerySetEqualReversible(
Article.objects.order_by(F("author").desc(nulls_last=True), "headline"),
[self.a4, self.a3, self.a1, self.a2],
)
self.assertQuerySetEqualReversible(
Article.objects.order_by(F("author").asc(nulls_last=True), "headline"),
[self.a3, self.a4, self.a1, self.a2],
)
self.assertQuerySetEqualReversible(
Article.objects.order_by(
Upper("author__name").desc(nulls_last=True), "headline"
),
[self.a4, self.a3, self.a1, self.a2],
)
self.assertQuerySetEqualReversible(
Article.objects.order_by(
Upper("author__name").asc(nulls_last=True), "headline"
),
[self.a3, self.a4, self.a1, self.a2],
)
def test_order_by_nulls_first(self):
Article.objects.filter(headline="Article 3").update(author=self.author_1)
Article.objects.filter(headline="Article 4").update(author=self.author_2)
# asc and desc are chainable with nulls_first.
self.assertQuerySetEqualReversible(
Article.objects.order_by(F("author").asc(nulls_first=True), "headline"),
[self.a1, self.a2, self.a3, self.a4],
)
self.assertQuerySetEqualReversible(
Article.objects.order_by(F("author").desc(nulls_first=True), "headline"),
[self.a1, self.a2, self.a4, self.a3],
)
self.assertQuerySetEqualReversible(
Article.objects.order_by(
Upper("author__name").asc(nulls_first=True), "headline"
),
[self.a1, self.a2, self.a3, self.a4],
)
self.assertQuerySetEqualReversible(
Article.objects.order_by(
Upper("author__name").desc(nulls_first=True), "headline"
),
[self.a1, self.a2, self.a4, self.a3],
)
def test_orders_nulls_first_on_filtered_subquery(self):
Article.objects.filter(headline="Article 1").update(author=self.author_1)
Article.objects.filter(headline="Article 2").update(author=self.author_1)
Article.objects.filter(headline="Article 4").update(author=self.author_2)
Author.objects.filter(name__isnull=True).delete()
author_3 = Author.objects.create(name="Name 3")
article_subquery = (
Article.objects.filter(
author=OuterRef("pk"),
headline__icontains="Article",
)
.order_by()
.values("author")
.annotate(
last_date=Max("pub_date"),
)
.values("last_date")
)
self.assertQuerySetEqualReversible(
Author.objects.annotate(
last_date=Subquery(article_subquery, output_field=DateTimeField())
)
.order_by(F("last_date").asc(nulls_first=True))
.distinct(),
[author_3, self.author_1, self.author_2],
)
def test_stop_slicing(self):
"""
Use the 'stop' part of slicing notation to limit the results.
"""
self.assertQuerySetEqual(
Article.objects.order_by("headline")[:2],
[
"Article 1",
"Article 2",
],
attrgetter("headline"),
)
def test_stop_start_slicing(self):
"""
Use the 'stop' and 'start' parts of slicing notation to offset the
result list.
"""
self.assertQuerySetEqual(
Article.objects.order_by("headline")[1:3],
[
"Article 2",
"Article 3",
],
attrgetter("headline"),
)
def test_random_ordering(self):
"""
Use '?' to order randomly.
"""
self.assertEqual(len(list(Article.objects.order_by("?"))), 4)
def test_reversed_ordering(self):
"""
Ordering can be reversed using the reverse() method on a queryset.
This allows you to extract things like "the last two items" (reverse
and then take the first two).
"""
self.assertQuerySetEqual(
Article.objects.reverse()[:2],
[
"Article 1",
"Article 3",
],
attrgetter("headline"),
)
def test_reverse_ordering_pure(self):
qs1 = Article.objects.order_by(F("headline").asc())
qs2 = qs1.reverse()
self.assertQuerySetEqual(
qs2,
[
"Article 4",
"Article 3",
"Article 2",
"Article 1",
],
attrgetter("headline"),
)
self.assertQuerySetEqual(
qs1,
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
def test_reverse_meta_ordering_pure(self):
Article.objects.create(
headline="Article 5",
pub_date=datetime(2005, 7, 30),
author=self.author_1,
second_author=self.author_2,
)
Article.objects.create(
headline="Article 5",
pub_date=datetime(2005, 7, 30),
author=self.author_2,
second_author=self.author_1,
)
self.assertQuerySetEqual(
Article.objects.filter(headline="Article 5").reverse(),
["Name 2", "Name 1"],
attrgetter("author.name"),
)
self.assertQuerySetEqual(
Article.objects.filter(headline="Article 5"),
["Name 1", "Name 2"],
attrgetter("author.name"),
)
def test_no_reordering_after_slicing(self):
msg = "Cannot reverse a query once a slice has been taken."
qs = Article.objects.all()[0:2]
with self.assertRaisesMessage(TypeError, msg):
qs.reverse()
with self.assertRaisesMessage(TypeError, msg):
qs.last()
def test_extra_ordering(self):
"""
Ordering can be based on fields included from an 'extra' clause
"""
self.assertQuerySetEqual(
Article.objects.extra(
select={"foo": "pub_date"}, order_by=["foo", "headline"]
),
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
def test_extra_ordering_quoting(self):
"""
If the extra clause uses an SQL keyword for a name, it will be
protected by quoting.
"""
self.assertQuerySetEqual(
Article.objects.extra(
select={"order": "pub_date"}, order_by=["order", "headline"]
),
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
def test_extra_ordering_with_table_name(self):
self.assertQuerySetEqual(
Article.objects.extra(order_by=["ordering_article.headline"]),
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.extra(order_by=["-ordering_article.headline"]),
[
"Article 4",
"Article 3",
"Article 2",
"Article 1",
],
attrgetter("headline"),
)
def test_order_by_pk(self):
"""
'pk' works as an ordering option in Meta.
"""
self.assertEqual(
[a.pk for a in Author.objects.all()],
[a.pk for a in Author.objects.order_by("-pk")],
)
def test_order_by_fk_attname(self):
"""
ordering by a foreign key by its attribute name prevents the query
from inheriting its related model ordering option (#19195).
"""
authors = list(Author.objects.order_by("id"))
for i in range(1, 5):
author = authors[i - 1]
article = getattr(self, "a%d" % (5 - i))
article.author = author
article.save(update_fields={"author"})
self.assertQuerySetEqual(
Article.objects.order_by("author_id"),
[
"Article 4",
"Article 3",
"Article 2",
"Article 1",
],
attrgetter("headline"),
)
def test_order_by_self_referential_fk(self):
self.a1.author = Author.objects.create(editor=self.author_1)
self.a1.save()
self.a2.author = Author.objects.create(editor=self.author_2)
self.a2.save()
self.assertQuerySetEqual(
Article.objects.filter(author__isnull=False).order_by("author__editor"),
["Article 2", "Article 1"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(author__isnull=False).order_by("author__editor_id"),
["Article 1", "Article 2"],
attrgetter("headline"),
)
def test_order_by_f_expression(self):
self.assertQuerySetEqual(
Article.objects.order_by(F("headline")),
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.order_by(F("headline").asc()),
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.order_by(F("headline").desc()),
[
"Article 4",
"Article 3",
"Article 2",
"Article 1",
],
attrgetter("headline"),
)
def test_order_by_f_expression_duplicates(self):
"""
A column may only be included once (the first occurrence) so we check
to ensure there are no duplicates by inspecting the SQL.
"""
qs = Article.objects.order_by(F("headline").asc(), F("headline").desc())
sql = str(qs.query).upper()
fragment = sql[sql.find("ORDER BY") :]
self.assertEqual(fragment.count("HEADLINE"), 1)
self.assertQuerySetEqual(
qs,
[
"Article 1",
"Article 2",
"Article 3",
"Article 4",
],
attrgetter("headline"),
)
qs = Article.objects.order_by(F("headline").desc(), F("headline").asc())
sql = str(qs.query).upper()
fragment = sql[sql.find("ORDER BY") :]
self.assertEqual(fragment.count("HEADLINE"), 1)
self.assertQuerySetEqual(
qs,
[
"Article 4",
"Article 3",
"Article 2",
"Article 1",
],
attrgetter("headline"),
)
def test_order_by_constant_value(self):
# Order by annotated constant from selected columns.
qs = Article.objects.annotate(
constant=Value("1", output_field=CharField()),
).order_by("constant", "-headline")
self.assertSequenceEqual(qs, [self.a4, self.a3, self.a2, self.a1])
# Order by annotated constant which is out of selected columns.
self.assertSequenceEqual(
qs.values_list("headline", flat=True),
[
"Article 4",
"Article 3",
"Article 2",
"Article 1",
],
)
# Order by constant.
qs = Article.objects.order_by(Value("1", output_field=CharField()), "-headline")
self.assertSequenceEqual(qs, [self.a4, self.a3, self.a2, self.a1])
def test_related_ordering_duplicate_table_reference(self):
"""
An ordering referencing a model with an ordering referencing a model
multiple time no circular reference should be detected (#24654).
"""
first_author = Author.objects.create()
second_author = Author.objects.create()
self.a1.author = first_author
self.a1.second_author = second_author
self.a1.save()
self.a2.author = second_author
self.a2.second_author = first_author
self.a2.save()
r1 = Reference.objects.create(article_id=self.a1.pk)
r2 = Reference.objects.create(article_id=self.a2.pk)
self.assertSequenceEqual(Reference.objects.all(), [r2, r1])
def test_default_ordering_by_f_expression(self):
"""F expressions can be used in Meta.ordering."""
articles = OrderedByFArticle.objects.all()
articles.filter(headline="Article 2").update(author=self.author_2)
articles.filter(headline="Article 3").update(author=self.author_1)
self.assertQuerySetEqual(
articles,
["Article 1", "Article 4", "Article 3", "Article 2"],
attrgetter("headline"),
)
def test_order_by_ptr_field_with_default_ordering_by_expression(self):
ca1 = ChildArticle.objects.create(
headline="h2",
pub_date=datetime(2005, 7, 27),
author=self.author_2,
)
ca2 = ChildArticle.objects.create(
headline="h2",
pub_date=datetime(2005, 7, 27),
author=self.author_1,
)
ca3 = ChildArticle.objects.create(
headline="h3",
pub_date=datetime(2005, 7, 27),
author=self.author_1,
)
ca4 = ChildArticle.objects.create(headline="h1", pub_date=datetime(2005, 7, 28))
articles = ChildArticle.objects.order_by("article_ptr")
self.assertSequenceEqual(articles, [ca4, ca2, ca1, ca3])
def test_default_ordering_does_not_affect_group_by(self):
Article.objects.exclude(headline="Article 4").update(author=self.author_1)
Article.objects.filter(headline="Article 4").update(author=self.author_2)
articles = Article.objects.values("author").annotate(count=Count("author"))
self.assertCountEqual(
articles,
[
{"author": self.author_1.pk, "count": 3},
{"author": self.author_2.pk, "count": 1},
],
)
def test_order_by_parent_fk_with_expression_in_default_ordering(self):
p3 = OrderedByExpression.objects.create(name="oBJ 3")
p2 = OrderedByExpression.objects.create(name="OBJ 2")
p1 = OrderedByExpression.objects.create(name="obj 1")
c3 = OrderedByExpressionChild.objects.create(parent=p3)
c2 = OrderedByExpressionChild.objects.create(parent=p2)
c1 = OrderedByExpressionChild.objects.create(parent=p1)
self.assertSequenceEqual(
OrderedByExpressionChild.objects.order_by("parent"),
[c1, c2, c3],
)
def test_order_by_grandparent_fk_with_expression_in_default_ordering(self):
p3 = OrderedByExpression.objects.create(name="oBJ 3")
p2 = OrderedByExpression.objects.create(name="OBJ 2")
p1 = OrderedByExpression.objects.create(name="obj 1")
c3 = OrderedByExpressionChild.objects.create(parent=p3)
c2 = OrderedByExpressionChild.objects.create(parent=p2)
c1 = OrderedByExpressionChild.objects.create(parent=p1)
g3 = OrderedByExpressionGrandChild.objects.create(parent=c3)
g2 = OrderedByExpressionGrandChild.objects.create(parent=c2)
g1 = OrderedByExpressionGrandChild.objects.create(parent=c1)
self.assertSequenceEqual(
OrderedByExpressionGrandChild.objects.order_by("parent"),
[g1, g2, g3],
)
|
784b1270e378292b4d28c3dc0eb0bf27931c29edc70d0c034585cfe15a19055e | from datetime import datetime
from django.test import TestCase
from .models import Article, Reporter, Writer
class M2MIntermediaryTests(TestCase):
def test_intermediary(self):
r1 = Reporter.objects.create(first_name="John", last_name="Smith")
r2 = Reporter.objects.create(first_name="Jane", last_name="Doe")
a = Article.objects.create(
headline="This is a test", pub_date=datetime(2005, 7, 27)
)
w1 = Writer.objects.create(reporter=r1, article=a, position="Main writer")
w2 = Writer.objects.create(reporter=r2, article=a, position="Contributor")
self.assertQuerySetEqual(
a.writer_set.select_related().order_by("-position"),
[
("John Smith", "Main writer"),
("Jane Doe", "Contributor"),
],
lambda w: (str(w.reporter), w.position),
)
self.assertEqual(w1.reporter, r1)
self.assertEqual(w2.reporter, r2)
self.assertEqual(w1.article, a)
self.assertEqual(w2.article, a)
self.assertQuerySetEqual(
r1.writer_set.all(),
[("John Smith", "Main writer")],
lambda w: (str(w.reporter), w.position),
)
|
ae68dd88d9201eb4da7d84f0c4bb6c04a5a5c480fb8213a39606d1033fb81f1a | import datetime
import os
from decimal import Decimal
from unittest import mock, skipUnless
from django import forms
from django.core.exceptions import (
NON_FIELD_ERRORS,
FieldError,
ImproperlyConfigured,
ValidationError,
)
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import connection, models
from django.db.models.query import EmptyQuerySet
from django.forms.models import (
ModelFormMetaclass,
construct_instance,
fields_for_model,
model_to_dict,
modelform_factory,
)
from django.template import Context, Template
from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature
from django.test.utils import isolate_apps
from .models import (
Article,
ArticleStatus,
Author,
Author1,
Award,
BetterWriter,
BigInt,
Book,
Category,
Character,
Colour,
ColourfulItem,
CustomErrorMessage,
CustomFF,
CustomFieldForExclusionModel,
DateTimePost,
DerivedBook,
DerivedPost,
Dice,
Document,
ExplicitPK,
FilePathModel,
FlexibleDatePost,
Homepage,
ImprovedArticle,
ImprovedArticleWithParentLink,
Inventory,
NullableUniqueCharFieldModel,
Number,
Person,
Photo,
Post,
Price,
Product,
Publication,
PublicationDefaults,
StrictAssignmentAll,
StrictAssignmentFieldSpecific,
Student,
StumpJoke,
TextFile,
Triple,
Writer,
WriterProfile,
test_images,
)
if test_images:
from .models import ImageFile, NoExtensionImageFile, OptionalImageFile
class ImageFileForm(forms.ModelForm):
class Meta:
model = ImageFile
fields = "__all__"
class OptionalImageFileForm(forms.ModelForm):
class Meta:
model = OptionalImageFile
fields = "__all__"
class NoExtensionImageFileForm(forms.ModelForm):
class Meta:
model = NoExtensionImageFile
fields = "__all__"
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = "__all__"
class PriceForm(forms.ModelForm):
class Meta:
model = Price
fields = "__all__"
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = "__all__"
class DerivedBookForm(forms.ModelForm):
class Meta:
model = DerivedBook
fields = "__all__"
class ExplicitPKForm(forms.ModelForm):
class Meta:
model = ExplicitPK
fields = (
"key",
"desc",
)
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = "__all__"
class DerivedPostForm(forms.ModelForm):
class Meta:
model = DerivedPost
fields = "__all__"
class CustomWriterForm(forms.ModelForm):
name = forms.CharField(required=False)
class Meta:
model = Writer
fields = "__all__"
class BaseCategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = "__all__"
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = "__all__"
class RoykoForm(forms.ModelForm):
class Meta:
model = Writer
fields = "__all__"
class ArticleStatusForm(forms.ModelForm):
class Meta:
model = ArticleStatus
fields = "__all__"
class InventoryForm(forms.ModelForm):
class Meta:
model = Inventory
fields = "__all__"
class SelectInventoryForm(forms.Form):
items = forms.ModelMultipleChoiceField(
Inventory.objects.all(), to_field_name="barcode"
)
class CustomFieldForExclusionForm(forms.ModelForm):
class Meta:
model = CustomFieldForExclusionModel
fields = ["name", "markup"]
class TextFileForm(forms.ModelForm):
class Meta:
model = TextFile
fields = "__all__"
class BigIntForm(forms.ModelForm):
class Meta:
model = BigInt
fields = "__all__"
class ModelFormWithMedia(forms.ModelForm):
class Media:
js = ("/some/form/javascript",)
css = {"all": ("/some/form/css",)}
class Meta:
model = TextFile
fields = "__all__"
class CustomErrorMessageForm(forms.ModelForm):
name1 = forms.CharField(error_messages={"invalid": "Form custom error message."})
class Meta:
fields = "__all__"
model = CustomErrorMessage
class ModelFormBaseTest(TestCase):
def test_base_form(self):
self.assertEqual(list(BaseCategoryForm.base_fields), ["name", "slug", "url"])
def test_no_model_class(self):
class NoModelModelForm(forms.ModelForm):
pass
with self.assertRaisesMessage(
ValueError, "ModelForm has no model class specified."
):
NoModelModelForm()
def test_empty_fields_to_fields_for_model(self):
"""
An argument of fields=() to fields_for_model should return an empty dictionary
"""
field_dict = fields_for_model(Person, fields=())
self.assertEqual(len(field_dict), 0)
def test_empty_fields_on_modelform(self):
"""
No fields on a ModelForm should actually result in no fields.
"""
class EmptyPersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ()
form = EmptyPersonForm()
self.assertEqual(len(form.fields), 0)
def test_empty_fields_to_construct_instance(self):
"""
No fields should be set on a model instance if construct_instance
receives fields=().
"""
form = modelform_factory(Person, fields="__all__")({"name": "John Doe"})
self.assertTrue(form.is_valid())
instance = construct_instance(form, Person(), fields=())
self.assertEqual(instance.name, "")
def test_blank_with_null_foreign_key_field(self):
"""
#13776 -- ModelForm's with models having a FK set to null=False and
required=False should be valid.
"""
class FormForTestingIsValid(forms.ModelForm):
class Meta:
model = Student
fields = "__all__"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["character"].required = False
char = Character.objects.create(
username="user", last_action=datetime.datetime.today()
)
data = {"study": "Engineering"}
data2 = {"study": "Engineering", "character": char.pk}
# form is valid because required=False for field 'character'
f1 = FormForTestingIsValid(data)
self.assertTrue(f1.is_valid())
f2 = FormForTestingIsValid(data2)
self.assertTrue(f2.is_valid())
obj = f2.save()
self.assertEqual(obj.character, char)
def test_blank_false_with_null_true_foreign_key_field(self):
"""
A ModelForm with a model having ForeignKey(blank=False, null=True)
and the form field set to required=False should allow the field to be
unset.
"""
class AwardForm(forms.ModelForm):
class Meta:
model = Award
fields = "__all__"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["character"].required = False
character = Character.objects.create(
username="user", last_action=datetime.datetime.today()
)
award = Award.objects.create(name="Best sprinter", character=character)
data = {"name": "Best tester", "character": ""} # remove character
form = AwardForm(data=data, instance=award)
self.assertTrue(form.is_valid())
award = form.save()
self.assertIsNone(award.character)
def test_blank_foreign_key_with_radio(self):
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ["author"]
widgets = {"author": forms.RadioSelect()}
writer = Writer.objects.create(name="Joe Doe")
form = BookForm()
self.assertEqual(
list(form.fields["author"].choices),
[
("", "---------"),
(writer.pk, "Joe Doe"),
],
)
def test_non_blank_foreign_key_with_radio(self):
class AwardForm(forms.ModelForm):
class Meta:
model = Award
fields = ["character"]
widgets = {"character": forms.RadioSelect()}
character = Character.objects.create(
username="user",
last_action=datetime.datetime.today(),
)
form = AwardForm()
self.assertEqual(
list(form.fields["character"].choices),
[(character.pk, "user")],
)
def test_save_blank_false_with_required_false(self):
"""
A ModelForm with a model with a field set to blank=False and the form
field set to required=False should allow the field to be unset.
"""
obj = Writer.objects.create(name="test")
form = CustomWriterForm(data={"name": ""}, instance=obj)
self.assertTrue(form.is_valid())
obj = form.save()
self.assertEqual(obj.name, "")
def test_save_blank_null_unique_charfield_saves_null(self):
form_class = modelform_factory(
model=NullableUniqueCharFieldModel, fields="__all__"
)
empty_value = (
"" if connection.features.interprets_empty_strings_as_nulls else None
)
data = {
"codename": "",
"email": "",
"slug": "",
"url": "",
}
form = form_class(data=data)
self.assertTrue(form.is_valid())
form.save()
self.assertEqual(form.instance.codename, empty_value)
self.assertEqual(form.instance.email, empty_value)
self.assertEqual(form.instance.slug, empty_value)
self.assertEqual(form.instance.url, empty_value)
# Save a second form to verify there isn't a unique constraint violation.
form = form_class(data=data)
self.assertTrue(form.is_valid())
form.save()
self.assertEqual(form.instance.codename, empty_value)
self.assertEqual(form.instance.email, empty_value)
self.assertEqual(form.instance.slug, empty_value)
self.assertEqual(form.instance.url, empty_value)
def test_missing_fields_attribute(self):
message = (
"Creating a ModelForm without either the 'fields' attribute "
"or the 'exclude' attribute is prohibited; form "
"MissingFieldsForm needs updating."
)
with self.assertRaisesMessage(ImproperlyConfigured, message):
class MissingFieldsForm(forms.ModelForm):
class Meta:
model = Category
def test_extra_fields(self):
class ExtraFields(BaseCategoryForm):
some_extra_field = forms.BooleanField()
self.assertEqual(
list(ExtraFields.base_fields), ["name", "slug", "url", "some_extra_field"]
)
def test_extra_field_model_form(self):
with self.assertRaisesMessage(FieldError, "no-field"):
class ExtraPersonForm(forms.ModelForm):
"""ModelForm with an extra field"""
age = forms.IntegerField()
class Meta:
model = Person
fields = ("name", "no-field")
def test_extra_declared_field_model_form(self):
class ExtraPersonForm(forms.ModelForm):
"""ModelForm with an extra field"""
age = forms.IntegerField()
class Meta:
model = Person
fields = ("name", "age")
def test_extra_field_modelform_factory(self):
with self.assertRaisesMessage(
FieldError, "Unknown field(s) (no-field) specified for Person"
):
modelform_factory(Person, fields=["no-field", "name"])
def test_replace_field(self):
class ReplaceField(forms.ModelForm):
url = forms.BooleanField()
class Meta:
model = Category
fields = "__all__"
self.assertIsInstance(
ReplaceField.base_fields["url"], forms.fields.BooleanField
)
def test_replace_field_variant_2(self):
# Should have the same result as before,
# but 'fields' attribute specified differently
class ReplaceField(forms.ModelForm):
url = forms.BooleanField()
class Meta:
model = Category
fields = ["url"]
self.assertIsInstance(
ReplaceField.base_fields["url"], forms.fields.BooleanField
)
def test_replace_field_variant_3(self):
# Should have the same result as before,
# but 'fields' attribute specified differently
class ReplaceField(forms.ModelForm):
url = forms.BooleanField()
class Meta:
model = Category
fields = [] # url will still appear, since it is explicit above
self.assertIsInstance(
ReplaceField.base_fields["url"], forms.fields.BooleanField
)
def test_override_field(self):
class WriterForm(forms.ModelForm):
book = forms.CharField(required=False)
class Meta:
model = Writer
fields = "__all__"
wf = WriterForm({"name": "Richard Lockridge"})
self.assertTrue(wf.is_valid())
def test_limit_nonexistent_field(self):
expected_msg = "Unknown field(s) (nonexistent) specified for Category"
with self.assertRaisesMessage(FieldError, expected_msg):
class InvalidCategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = ["nonexistent"]
def test_limit_fields_with_string(self):
msg = (
"CategoryForm.Meta.fields cannot be a string. Did you mean to type: "
"('url',)?"
)
with self.assertRaisesMessage(TypeError, msg):
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = "url" # note the missing comma
def test_exclude_fields(self):
class ExcludeFields(forms.ModelForm):
class Meta:
model = Category
exclude = ["url"]
self.assertEqual(list(ExcludeFields.base_fields), ["name", "slug"])
def test_exclude_nonexistent_field(self):
class ExcludeFields(forms.ModelForm):
class Meta:
model = Category
exclude = ["nonexistent"]
self.assertEqual(list(ExcludeFields.base_fields), ["name", "slug", "url"])
def test_exclude_fields_with_string(self):
msg = (
"CategoryForm.Meta.exclude cannot be a string. Did you mean to type: "
"('url',)?"
)
with self.assertRaisesMessage(TypeError, msg):
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
exclude = "url" # note the missing comma
def test_exclude_and_validation(self):
# This Price instance generated by this form is not valid because the quantity
# field is required, but the form is valid because the field is excluded from
# the form. This is for backwards compatibility.
class PriceFormWithoutQuantity(forms.ModelForm):
class Meta:
model = Price
exclude = ("quantity",)
form = PriceFormWithoutQuantity({"price": "6.00"})
self.assertTrue(form.is_valid())
price = form.save(commit=False)
msg = "{'quantity': ['This field cannot be null.']}"
with self.assertRaisesMessage(ValidationError, msg):
price.full_clean()
# The form should not validate fields that it doesn't contain even if they are
# specified using 'fields', not 'exclude'.
class PriceFormWithoutQuantity(forms.ModelForm):
class Meta:
model = Price
fields = ("price",)
form = PriceFormWithoutQuantity({"price": "6.00"})
self.assertTrue(form.is_valid())
# The form should still have an instance of a model that is not complete and
# not saved into a DB yet.
self.assertEqual(form.instance.price, Decimal("6.00"))
self.assertIsNone(form.instance.quantity)
self.assertIsNone(form.instance.pk)
def test_confused_form(self):
class ConfusedForm(forms.ModelForm):
"""Using 'fields' *and* 'exclude'. Not sure why you'd want to do
this, but uh, "be liberal in what you accept" and all.
"""
class Meta:
model = Category
fields = ["name", "url"]
exclude = ["url"]
self.assertEqual(list(ConfusedForm.base_fields), ["name"])
def test_mixmodel_form(self):
class MixModelForm(BaseCategoryForm):
"""Don't allow more than one 'model' definition in the
inheritance hierarchy. Technically, it would generate a valid
form, but the fact that the resulting save method won't deal with
multiple objects is likely to trip up people not familiar with the
mechanics.
"""
class Meta:
model = Article
fields = "__all__"
# MixModelForm is now an Article-related thing, because MixModelForm.Meta
# overrides BaseCategoryForm.Meta.
self.assertEqual(
list(MixModelForm.base_fields),
[
"headline",
"slug",
"pub_date",
"writer",
"article",
"categories",
"status",
],
)
def test_article_form(self):
self.assertEqual(
list(ArticleForm.base_fields),
[
"headline",
"slug",
"pub_date",
"writer",
"article",
"categories",
"status",
],
)
def test_bad_form(self):
# First class with a Meta class wins...
class BadForm(ArticleForm, BaseCategoryForm):
pass
self.assertEqual(
list(BadForm.base_fields),
[
"headline",
"slug",
"pub_date",
"writer",
"article",
"categories",
"status",
],
)
def test_invalid_meta_model(self):
class InvalidModelForm(forms.ModelForm):
class Meta:
pass # no model
# Can't create new form
msg = "ModelForm has no model class specified."
with self.assertRaisesMessage(ValueError, msg):
InvalidModelForm()
# Even if you provide a model instance
with self.assertRaisesMessage(ValueError, msg):
InvalidModelForm(instance=Category)
def test_subcategory_form(self):
class SubCategoryForm(BaseCategoryForm):
"""Subclassing without specifying a Meta on the class will use
the parent's Meta (or the first parent in the MRO if there are
multiple parent classes).
"""
pass
self.assertEqual(list(SubCategoryForm.base_fields), ["name", "slug", "url"])
def test_subclassmeta_form(self):
class SomeCategoryForm(forms.ModelForm):
checkbox = forms.BooleanField()
class Meta:
model = Category
fields = "__all__"
class SubclassMeta(SomeCategoryForm):
"""We can also subclass the Meta inner class to change the fields
list.
"""
class Meta(SomeCategoryForm.Meta):
exclude = ["url"]
self.assertHTMLEqual(
str(SubclassMeta()),
'<div><label for="id_name">Name:</label>'
'<input type="text" name="name" maxlength="20" required id="id_name">'
'</div><div><label for="id_slug">Slug:</label><input type="text" '
'name="slug" maxlength="20" required id="id_slug"></div><div>'
'<label for="id_checkbox">Checkbox:</label>'
'<input type="checkbox" name="checkbox" required id="id_checkbox"></div>',
)
def test_orderfields_form(self):
class OrderFields(forms.ModelForm):
class Meta:
model = Category
fields = ["url", "name"]
self.assertEqual(list(OrderFields.base_fields), ["url", "name"])
self.assertHTMLEqual(
str(OrderFields()),
'<div><label for="id_url">The URL:</label>'
'<input type="text" name="url" maxlength="40" required id="id_url">'
'</div><div><label for="id_name">Name:</label><input type="text" '
'name="name" maxlength="20" required id="id_name"></div>',
)
def test_orderfields2_form(self):
class OrderFields2(forms.ModelForm):
class Meta:
model = Category
fields = ["slug", "url", "name"]
exclude = ["url"]
self.assertEqual(list(OrderFields2.base_fields), ["slug", "name"])
def test_default_populated_on_optional_field(self):
class PubForm(forms.ModelForm):
mode = forms.CharField(max_length=255, required=False)
class Meta:
model = PublicationDefaults
fields = ("mode",)
# Empty data uses the model field default.
mf1 = PubForm({})
self.assertEqual(mf1.errors, {})
m1 = mf1.save(commit=False)
self.assertEqual(m1.mode, "di")
self.assertEqual(m1._meta.get_field("mode").get_default(), "di")
# Blank data doesn't use the model field default.
mf2 = PubForm({"mode": ""})
self.assertEqual(mf2.errors, {})
m2 = mf2.save(commit=False)
self.assertEqual(m2.mode, "")
def test_default_not_populated_on_non_empty_value_in_cleaned_data(self):
class PubForm(forms.ModelForm):
mode = forms.CharField(max_length=255, required=False)
mocked_mode = None
def clean(self):
self.cleaned_data["mode"] = self.mocked_mode
return self.cleaned_data
class Meta:
model = PublicationDefaults
fields = ("mode",)
pub_form = PubForm({})
pub_form.mocked_mode = "de"
pub = pub_form.save(commit=False)
self.assertEqual(pub.mode, "de")
# Default should be populated on an empty value in cleaned_data.
default_mode = "di"
for empty_value in pub_form.fields["mode"].empty_values:
with self.subTest(empty_value=empty_value):
pub_form = PubForm({})
pub_form.mocked_mode = empty_value
pub = pub_form.save(commit=False)
self.assertEqual(pub.mode, default_mode)
def test_default_not_populated_on_optional_checkbox_input(self):
class PubForm(forms.ModelForm):
class Meta:
model = PublicationDefaults
fields = ("active",)
# Empty data doesn't use the model default because CheckboxInput
# doesn't have a value in HTML form submission.
mf1 = PubForm({})
self.assertEqual(mf1.errors, {})
m1 = mf1.save(commit=False)
self.assertIs(m1.active, False)
self.assertIsInstance(mf1.fields["active"].widget, forms.CheckboxInput)
self.assertIs(m1._meta.get_field("active").get_default(), True)
def test_default_not_populated_on_checkboxselectmultiple(self):
class PubForm(forms.ModelForm):
mode = forms.CharField(required=False, widget=forms.CheckboxSelectMultiple)
class Meta:
model = PublicationDefaults
fields = ("mode",)
# Empty data doesn't use the model default because an unchecked
# CheckboxSelectMultiple doesn't have a value in HTML form submission.
mf1 = PubForm({})
self.assertEqual(mf1.errors, {})
m1 = mf1.save(commit=False)
self.assertEqual(m1.mode, "")
self.assertEqual(m1._meta.get_field("mode").get_default(), "di")
def test_default_not_populated_on_selectmultiple(self):
class PubForm(forms.ModelForm):
mode = forms.CharField(required=False, widget=forms.SelectMultiple)
class Meta:
model = PublicationDefaults
fields = ("mode",)
# Empty data doesn't use the model default because an unselected
# SelectMultiple doesn't have a value in HTML form submission.
mf1 = PubForm({})
self.assertEqual(mf1.errors, {})
m1 = mf1.save(commit=False)
self.assertEqual(m1.mode, "")
self.assertEqual(m1._meta.get_field("mode").get_default(), "di")
def test_prefixed_form_with_default_field(self):
class PubForm(forms.ModelForm):
prefix = "form-prefix"
class Meta:
model = PublicationDefaults
fields = ("mode",)
mode = "de"
self.assertNotEqual(
mode, PublicationDefaults._meta.get_field("mode").get_default()
)
mf1 = PubForm({"form-prefix-mode": mode})
self.assertEqual(mf1.errors, {})
m1 = mf1.save(commit=False)
self.assertEqual(m1.mode, mode)
def test_renderer_kwarg(self):
custom = object()
self.assertIs(ProductForm(renderer=custom).renderer, custom)
def test_default_splitdatetime_field(self):
class PubForm(forms.ModelForm):
datetime_published = forms.SplitDateTimeField(required=False)
class Meta:
model = PublicationDefaults
fields = ("datetime_published",)
mf1 = PubForm({})
self.assertEqual(mf1.errors, {})
m1 = mf1.save(commit=False)
self.assertEqual(m1.datetime_published, datetime.datetime(2000, 1, 1))
mf2 = PubForm(
{"datetime_published_0": "2010-01-01", "datetime_published_1": "0:00:00"}
)
self.assertEqual(mf2.errors, {})
m2 = mf2.save(commit=False)
self.assertEqual(m2.datetime_published, datetime.datetime(2010, 1, 1))
def test_default_filefield(self):
class PubForm(forms.ModelForm):
class Meta:
model = PublicationDefaults
fields = ("file",)
mf1 = PubForm({})
self.assertEqual(mf1.errors, {})
m1 = mf1.save(commit=False)
self.assertEqual(m1.file.name, "default.txt")
mf2 = PubForm({}, {"file": SimpleUploadedFile("name", b"foo")})
self.assertEqual(mf2.errors, {})
m2 = mf2.save(commit=False)
self.assertEqual(m2.file.name, "name")
def test_default_selectdatewidget(self):
class PubForm(forms.ModelForm):
date_published = forms.DateField(
required=False, widget=forms.SelectDateWidget
)
class Meta:
model = PublicationDefaults
fields = ("date_published",)
mf1 = PubForm({})
self.assertEqual(mf1.errors, {})
m1 = mf1.save(commit=False)
self.assertEqual(m1.date_published, datetime.date.today())
mf2 = PubForm(
{
"date_published_year": "2010",
"date_published_month": "1",
"date_published_day": "1",
}
)
self.assertEqual(mf2.errors, {})
m2 = mf2.save(commit=False)
self.assertEqual(m2.date_published, datetime.date(2010, 1, 1))
class FieldOverridesByFormMetaForm(forms.ModelForm):
class Meta:
model = Category
fields = ["name", "url", "slug"]
widgets = {
"name": forms.Textarea,
"url": forms.TextInput(attrs={"class": "url"}),
}
labels = {
"name": "Title",
}
help_texts = {
"slug": "Watch out! Letters, numbers, underscores and hyphens only.",
}
error_messages = {
"slug": {
"invalid": (
"Didn't you read the help text? "
"We said letters, numbers, underscores and hyphens only!"
)
}
}
field_classes = {
"url": forms.URLField,
}
class TestFieldOverridesByFormMeta(SimpleTestCase):
def test_widget_overrides(self):
form = FieldOverridesByFormMetaForm()
self.assertHTMLEqual(
str(form["name"]),
'<textarea id="id_name" rows="10" cols="40" name="name" maxlength="20" '
"required></textarea>",
)
self.assertHTMLEqual(
str(form["url"]),
'<input id="id_url" type="text" class="url" name="url" maxlength="40" '
"required>",
)
self.assertHTMLEqual(
str(form["slug"]),
'<input id="id_slug" type="text" name="slug" maxlength="20" required>',
)
def test_label_overrides(self):
form = FieldOverridesByFormMetaForm()
self.assertHTMLEqual(
str(form["name"].label_tag()),
'<label for="id_name">Title:</label>',
)
self.assertHTMLEqual(
str(form["url"].label_tag()),
'<label for="id_url">The URL:</label>',
)
self.assertHTMLEqual(
str(form["slug"].label_tag()),
'<label for="id_slug">Slug:</label>',
)
self.assertHTMLEqual(
form["name"].legend_tag(),
'<legend for="id_name">Title:</legend>',
)
self.assertHTMLEqual(
form["url"].legend_tag(),
'<legend for="id_url">The URL:</legend>',
)
self.assertHTMLEqual(
form["slug"].legend_tag(),
'<legend for="id_slug">Slug:</legend>',
)
def test_help_text_overrides(self):
form = FieldOverridesByFormMetaForm()
self.assertEqual(
form["slug"].help_text,
"Watch out! Letters, numbers, underscores and hyphens only.",
)
def test_error_messages_overrides(self):
form = FieldOverridesByFormMetaForm(
data={
"name": "Category",
"url": "http://www.example.com/category/",
"slug": "!%#*@",
}
)
form.full_clean()
error = [
"Didn't you read the help text? "
"We said letters, numbers, underscores and hyphens only!",
]
self.assertEqual(form.errors, {"slug": error})
def test_field_type_overrides(self):
form = FieldOverridesByFormMetaForm()
self.assertIs(Category._meta.get_field("url").__class__, models.CharField)
self.assertIsInstance(form.fields["url"], forms.URLField)
class IncompleteCategoryFormWithFields(forms.ModelForm):
"""
A form that replaces the model's url field with a custom one. This should
prevent the model field's validation from being called.
"""
url = forms.CharField(required=False)
class Meta:
fields = ("name", "slug")
model = Category
class IncompleteCategoryFormWithExclude(forms.ModelForm):
"""
A form that replaces the model's url field with a custom one. This should
prevent the model field's validation from being called.
"""
url = forms.CharField(required=False)
class Meta:
exclude = ["url"]
model = Category
class ValidationTest(SimpleTestCase):
def test_validates_with_replaced_field_not_specified(self):
form = IncompleteCategoryFormWithFields(
data={"name": "some name", "slug": "some-slug"}
)
self.assertIs(form.is_valid(), True)
def test_validates_with_replaced_field_excluded(self):
form = IncompleteCategoryFormWithExclude(
data={"name": "some name", "slug": "some-slug"}
)
self.assertIs(form.is_valid(), True)
def test_notrequired_overrides_notblank(self):
form = CustomWriterForm({})
self.assertIs(form.is_valid(), True)
class UniqueTest(TestCase):
"""
unique/unique_together validation.
"""
@classmethod
def setUpTestData(cls):
cls.writer = Writer.objects.create(name="Mike Royko")
def test_simple_unique(self):
form = ProductForm({"slug": "teddy-bear-blue"})
self.assertTrue(form.is_valid())
obj = form.save()
form = ProductForm({"slug": "teddy-bear-blue"})
self.assertEqual(len(form.errors), 1)
self.assertEqual(
form.errors["slug"], ["Product with this Slug already exists."]
)
form = ProductForm({"slug": "teddy-bear-blue"}, instance=obj)
self.assertTrue(form.is_valid())
def test_unique_together(self):
"""ModelForm test of unique_together constraint"""
form = PriceForm({"price": "6.00", "quantity": "1"})
self.assertTrue(form.is_valid())
form.save()
form = PriceForm({"price": "6.00", "quantity": "1"})
self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 1)
self.assertEqual(
form.errors["__all__"],
["Price with this Price and Quantity already exists."],
)
def test_unique_together_exclusion(self):
"""
Forms don't validate unique_together constraints when only part of the
constraint is included in the form's fields. This allows using
form.save(commit=False) and then assigning the missing field(s) to the
model instance.
"""
class BookForm(forms.ModelForm):
class Meta:
model = DerivedBook
fields = ("isbn", "suffix1")
# The unique_together is on suffix1/suffix2 but only suffix1 is part
# of the form. The fields must have defaults, otherwise they'll be
# skipped by other logic.
self.assertEqual(DerivedBook._meta.unique_together, (("suffix1", "suffix2"),))
for name in ("suffix1", "suffix2"):
with self.subTest(name=name):
field = DerivedBook._meta.get_field(name)
self.assertEqual(field.default, 0)
# The form fails validation with "Derived book with this Suffix1 and
# Suffix2 already exists." if the unique_together validation isn't
# skipped.
DerivedBook.objects.create(isbn="12345")
form = BookForm({"isbn": "56789", "suffix1": "0"})
self.assertTrue(form.is_valid(), form.errors)
def test_multiple_field_unique_together(self):
"""
When the same field is involved in multiple unique_together
constraints, we need to make sure we don't remove the data for it
before doing all the validation checking (not just failing after
the first one).
"""
class TripleForm(forms.ModelForm):
class Meta:
model = Triple
fields = "__all__"
Triple.objects.create(left=1, middle=2, right=3)
form = TripleForm({"left": "1", "middle": "2", "right": "3"})
self.assertFalse(form.is_valid())
form = TripleForm({"left": "1", "middle": "3", "right": "1"})
self.assertTrue(form.is_valid())
@skipUnlessDBFeature("supports_nullable_unique_constraints")
def test_unique_null(self):
title = "I May Be Wrong But I Doubt It"
form = BookForm({"title": title, "author": self.writer.pk})
self.assertTrue(form.is_valid())
form.save()
form = BookForm({"title": title, "author": self.writer.pk})
self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 1)
self.assertEqual(
form.errors["__all__"], ["Book with this Title and Author already exists."]
)
form = BookForm({"title": title})
self.assertTrue(form.is_valid())
form.save()
form = BookForm({"title": title})
self.assertTrue(form.is_valid())
def test_inherited_unique(self):
title = "Boss"
Book.objects.create(title=title, author=self.writer, special_id=1)
form = DerivedBookForm(
{
"title": "Other",
"author": self.writer.pk,
"special_id": "1",
"isbn": "12345",
}
)
self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 1)
self.assertEqual(
form.errors["special_id"], ["Book with this Special id already exists."]
)
def test_inherited_unique_together(self):
title = "Boss"
form = BookForm({"title": title, "author": self.writer.pk})
self.assertTrue(form.is_valid())
form.save()
form = DerivedBookForm(
{"title": title, "author": self.writer.pk, "isbn": "12345"}
)
self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 1)
self.assertEqual(
form.errors["__all__"], ["Book with this Title and Author already exists."]
)
def test_abstract_inherited_unique(self):
title = "Boss"
isbn = "12345"
DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn)
form = DerivedBookForm(
{
"title": "Other",
"author": self.writer.pk,
"isbn": isbn,
"suffix1": "1",
"suffix2": "2",
}
)
self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 1)
self.assertEqual(
form.errors["isbn"], ["Derived book with this Isbn already exists."]
)
def test_abstract_inherited_unique_together(self):
title = "Boss"
isbn = "12345"
DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn)
form = DerivedBookForm(
{
"title": "Other",
"author": self.writer.pk,
"isbn": "9876",
"suffix1": "0",
"suffix2": "0",
}
)
self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 1)
self.assertEqual(
form.errors["__all__"],
["Derived book with this Suffix1 and Suffix2 already exists."],
)
def test_explicitpk_unspecified(self):
"""Test for primary_key being in the form and failing validation."""
form = ExplicitPKForm({"key": "", "desc": ""})
self.assertFalse(form.is_valid())
def test_explicitpk_unique(self):
"""Ensure keys and blank character strings are tested for uniqueness."""
form = ExplicitPKForm({"key": "key1", "desc": ""})
self.assertTrue(form.is_valid())
form.save()
form = ExplicitPKForm({"key": "key1", "desc": ""})
self.assertFalse(form.is_valid())
if connection.features.interprets_empty_strings_as_nulls:
self.assertEqual(len(form.errors), 1)
self.assertEqual(
form.errors["key"], ["Explicit pk with this Key already exists."]
)
else:
self.assertEqual(len(form.errors), 3)
self.assertEqual(
form.errors["__all__"],
["Explicit pk with this Key and Desc already exists."],
)
self.assertEqual(
form.errors["desc"], ["Explicit pk with this Desc already exists."]
)
self.assertEqual(
form.errors["key"], ["Explicit pk with this Key already exists."]
)
def test_unique_for_date(self):
p = Post.objects.create(
title="Django 1.0 is released",
slug="Django 1.0",
subtitle="Finally",
posted=datetime.date(2008, 9, 3),
)
form = PostForm({"title": "Django 1.0 is released", "posted": "2008-09-03"})
self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 1)
self.assertEqual(
form.errors["title"], ["Title must be unique for Posted date."]
)
form = PostForm({"title": "Work on Django 1.1 begins", "posted": "2008-09-03"})
self.assertTrue(form.is_valid())
form = PostForm({"title": "Django 1.0 is released", "posted": "2008-09-04"})
self.assertTrue(form.is_valid())
form = PostForm({"slug": "Django 1.0", "posted": "2008-01-01"})
self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 1)
self.assertEqual(form.errors["slug"], ["Slug must be unique for Posted year."])
form = PostForm({"subtitle": "Finally", "posted": "2008-09-30"})
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors["subtitle"], ["Subtitle must be unique for Posted month."]
)
data = {
"subtitle": "Finally",
"title": "Django 1.0 is released",
"slug": "Django 1.0",
"posted": "2008-09-03",
}
form = PostForm(data, instance=p)
self.assertTrue(form.is_valid())
form = PostForm({"title": "Django 1.0 is released"})
self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 1)
self.assertEqual(form.errors["posted"], ["This field is required."])
def test_unique_for_date_in_exclude(self):
"""
If the date for unique_for_* constraints is excluded from the
ModelForm (in this case 'posted' has editable=False, then the
constraint should be ignored.
"""
class DateTimePostForm(forms.ModelForm):
class Meta:
model = DateTimePost
fields = "__all__"
DateTimePost.objects.create(
title="Django 1.0 is released",
slug="Django 1.0",
subtitle="Finally",
posted=datetime.datetime(2008, 9, 3, 10, 10, 1),
)
# 'title' has unique_for_date='posted'
form = DateTimePostForm(
{"title": "Django 1.0 is released", "posted": "2008-09-03"}
)
self.assertTrue(form.is_valid())
# 'slug' has unique_for_year='posted'
form = DateTimePostForm({"slug": "Django 1.0", "posted": "2008-01-01"})
self.assertTrue(form.is_valid())
# 'subtitle' has unique_for_month='posted'
form = DateTimePostForm({"subtitle": "Finally", "posted": "2008-09-30"})
self.assertTrue(form.is_valid())
def test_inherited_unique_for_date(self):
p = Post.objects.create(
title="Django 1.0 is released",
slug="Django 1.0",
subtitle="Finally",
posted=datetime.date(2008, 9, 3),
)
form = DerivedPostForm(
{"title": "Django 1.0 is released", "posted": "2008-09-03"}
)
self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 1)
self.assertEqual(
form.errors["title"], ["Title must be unique for Posted date."]
)
form = DerivedPostForm(
{"title": "Work on Django 1.1 begins", "posted": "2008-09-03"}
)
self.assertTrue(form.is_valid())
form = DerivedPostForm(
{"title": "Django 1.0 is released", "posted": "2008-09-04"}
)
self.assertTrue(form.is_valid())
form = DerivedPostForm({"slug": "Django 1.0", "posted": "2008-01-01"})
self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 1)
self.assertEqual(form.errors["slug"], ["Slug must be unique for Posted year."])
form = DerivedPostForm({"subtitle": "Finally", "posted": "2008-09-30"})
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors["subtitle"], ["Subtitle must be unique for Posted month."]
)
data = {
"subtitle": "Finally",
"title": "Django 1.0 is released",
"slug": "Django 1.0",
"posted": "2008-09-03",
}
form = DerivedPostForm(data, instance=p)
self.assertTrue(form.is_valid())
def test_unique_for_date_with_nullable_date(self):
class FlexDatePostForm(forms.ModelForm):
class Meta:
model = FlexibleDatePost
fields = "__all__"
p = FlexibleDatePost.objects.create(
title="Django 1.0 is released",
slug="Django 1.0",
subtitle="Finally",
posted=datetime.date(2008, 9, 3),
)
form = FlexDatePostForm({"title": "Django 1.0 is released"})
self.assertTrue(form.is_valid())
form = FlexDatePostForm({"slug": "Django 1.0"})
self.assertTrue(form.is_valid())
form = FlexDatePostForm({"subtitle": "Finally"})
self.assertTrue(form.is_valid())
data = {
"subtitle": "Finally",
"title": "Django 1.0 is released",
"slug": "Django 1.0",
}
form = FlexDatePostForm(data, instance=p)
self.assertTrue(form.is_valid())
def test_override_unique_message(self):
class CustomProductForm(ProductForm):
class Meta(ProductForm.Meta):
error_messages = {
"slug": {
"unique": "%(model_name)s's %(field_label)s not unique.",
}
}
Product.objects.create(slug="teddy-bear-blue")
form = CustomProductForm({"slug": "teddy-bear-blue"})
self.assertEqual(len(form.errors), 1)
self.assertEqual(form.errors["slug"], ["Product's Slug not unique."])
def test_override_unique_together_message(self):
class CustomPriceForm(PriceForm):
class Meta(PriceForm.Meta):
error_messages = {
NON_FIELD_ERRORS: {
"unique_together": (
"%(model_name)s's %(field_labels)s not unique."
),
}
}
Price.objects.create(price=6.00, quantity=1)
form = CustomPriceForm({"price": "6.00", "quantity": "1"})
self.assertEqual(len(form.errors), 1)
self.assertEqual(
form.errors[NON_FIELD_ERRORS], ["Price's Price and Quantity not unique."]
)
def test_override_unique_for_date_message(self):
class CustomPostForm(PostForm):
class Meta(PostForm.Meta):
error_messages = {
"title": {
"unique_for_date": (
"%(model_name)s's %(field_label)s not unique "
"for %(date_field_label)s date."
),
}
}
Post.objects.create(
title="Django 1.0 is released",
slug="Django 1.0",
subtitle="Finally",
posted=datetime.date(2008, 9, 3),
)
form = CustomPostForm(
{"title": "Django 1.0 is released", "posted": "2008-09-03"}
)
self.assertEqual(len(form.errors), 1)
self.assertEqual(
form.errors["title"], ["Post's Title not unique for Posted date."]
)
class ModelFormBasicTests(TestCase):
def create_basic_data(self):
self.c1 = Category.objects.create(
name="Entertainment", slug="entertainment", url="entertainment"
)
self.c2 = Category.objects.create(
name="It's a test", slug="its-test", url="test"
)
self.c3 = Category.objects.create(
name="Third test", slug="third-test", url="third"
)
self.w_royko = Writer.objects.create(name="Mike Royko")
self.w_woodward = Writer.objects.create(name="Bob Woodward")
def test_base_form(self):
self.assertEqual(Category.objects.count(), 0)
f = BaseCategoryForm()
self.assertHTMLEqual(
str(f),
'<div><label for="id_name">Name:</label><input type="text" name="name" '
'maxlength="20" required id="id_name"></div><div><label for="id_slug">Slug:'
'</label><input type="text" name="slug" maxlength="20" required '
'id="id_slug"></div><div><label for="id_url">The URL:</label>'
'<input type="text" name="url" maxlength="40" required id="id_url"></div>',
)
self.assertHTMLEqual(
str(f.as_ul()),
"""
<li><label for="id_name">Name:</label>
<input id="id_name" type="text" name="name" maxlength="20" required></li>
<li><label for="id_slug">Slug:</label>
<input id="id_slug" type="text" name="slug" maxlength="20" required></li>
<li><label for="id_url">The URL:</label>
<input id="id_url" type="text" name="url" maxlength="40" required></li>
""",
)
self.assertHTMLEqual(
str(f["name"]),
"""<input id="id_name" type="text" name="name" maxlength="20" required>""",
)
def test_auto_id(self):
f = BaseCategoryForm(auto_id=False)
self.assertHTMLEqual(
str(f.as_ul()),
"""<li>Name: <input type="text" name="name" maxlength="20" required></li>
<li>Slug: <input type="text" name="slug" maxlength="20" required></li>
<li>The URL: <input type="text" name="url" maxlength="40" required></li>""",
)
def test_initial_values(self):
self.create_basic_data()
# Initial values can be provided for model forms
f = ArticleForm(
auto_id=False,
initial={
"headline": "Your headline here",
"categories": [str(self.c1.id), str(self.c2.id)],
},
)
self.assertHTMLEqual(
f.as_ul(),
"""
<li>Headline:
<input type="text" name="headline" value="Your headline here" maxlength="50"
required>
</li>
<li>Slug: <input type="text" name="slug" maxlength="50" required></li>
<li>Pub date: <input type="text" name="pub_date" required></li>
<li>Writer: <select name="writer" required>
<option value="" selected>---------</option>
<option value="%s">Bob Woodward</option>
<option value="%s">Mike Royko</option>
</select></li>
<li>Article:
<textarea rows="10" cols="40" name="article" required></textarea></li>
<li>Categories: <select multiple name="categories">
<option value="%s" selected>Entertainment</option>
<option value="%s" selected>It's a test</option>
<option value="%s">Third test</option>
</select></li>
<li>Status: <select name="status">
<option value="" selected>---------</option>
<option value="1">Draft</option>
<option value="2">Pending</option>
<option value="3">Live</option>
</select></li>
"""
% (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
)
# When the ModelForm is passed an instance, that instance's current values are
# inserted as 'initial' data in each Field.
f = RoykoForm(auto_id=False, instance=self.w_royko)
self.assertHTMLEqual(
str(f),
'<div>Name:<div class="helptext">Use both first and last names.</div>'
'<input type="text" name="name" value="Mike Royko" maxlength="50" '
"required></div>",
)
art = Article.objects.create(
headline="Test article",
slug="test-article",
pub_date=datetime.date(1988, 1, 4),
writer=self.w_royko,
article="Hello.",
)
art_id_1 = art.id
f = ArticleForm(auto_id=False, instance=art)
self.assertHTMLEqual(
f.as_ul(),
"""
<li>Headline:
<input type="text" name="headline" value="Test article" maxlength="50"
required>
</li>
<li>Slug:
<input type="text" name="slug" value="test-article" maxlength="50" required>
</li>
<li>Pub date:
<input type="text" name="pub_date" value="1988-01-04" required></li>
<li>Writer: <select name="writer" required>
<option value="">---------</option>
<option value="%s">Bob Woodward</option>
<option value="%s" selected>Mike Royko</option>
</select></li>
<li>Article:
<textarea rows="10" cols="40" name="article" required>Hello.</textarea></li>
<li>Categories: <select multiple name="categories">
<option value="%s">Entertainment</option>
<option value="%s">It's a test</option>
<option value="%s">Third test</option>
</select></li>
<li>Status: <select name="status">
<option value="" selected>---------</option>
<option value="1">Draft</option>
<option value="2">Pending</option>
<option value="3">Live</option>
</select></li>
"""
% (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
)
f = ArticleForm(
{
"headline": "Test headline",
"slug": "test-headline",
"pub_date": "1984-02-06",
"writer": str(self.w_royko.pk),
"article": "Hello.",
},
instance=art,
)
self.assertEqual(f.errors, {})
self.assertTrue(f.is_valid())
test_art = f.save()
self.assertEqual(test_art.id, art_id_1)
test_art = Article.objects.get(id=art_id_1)
self.assertEqual(test_art.headline, "Test headline")
def test_m2m_initial_callable(self):
"""
A callable can be provided as the initial value for an m2m field.
"""
self.maxDiff = 1200
self.create_basic_data()
# Set up a callable initial value
def formfield_for_dbfield(db_field, **kwargs):
if db_field.name == "categories":
kwargs["initial"] = lambda: Category.objects.order_by("name")[:2]
return db_field.formfield(**kwargs)
# Create a ModelForm, instantiate it, and check that the output is as expected
ModelForm = modelform_factory(
Article,
fields=["headline", "categories"],
formfield_callback=formfield_for_dbfield,
)
form = ModelForm()
self.assertHTMLEqual(
form.as_ul(),
"""<li><label for="id_headline">Headline:</label>
<input id="id_headline" type="text" name="headline" maxlength="50" required></li>
<li><label for="id_categories">Categories:</label>
<select multiple name="categories" id="id_categories">
<option value="%d" selected>Entertainment</option>
<option value="%d" selected>It's a test</option>
<option value="%d">Third test</option>
</select></li>"""
% (self.c1.pk, self.c2.pk, self.c3.pk),
)
def test_basic_creation(self):
self.assertEqual(Category.objects.count(), 0)
f = BaseCategoryForm(
{
"name": "Entertainment",
"slug": "entertainment",
"url": "entertainment",
}
)
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data["name"], "Entertainment")
self.assertEqual(f.cleaned_data["slug"], "entertainment")
self.assertEqual(f.cleaned_data["url"], "entertainment")
c1 = f.save()
# Testing whether the same object is returned from the
# ORM... not the fastest way...
self.assertEqual(Category.objects.count(), 1)
self.assertEqual(c1, Category.objects.all()[0])
self.assertEqual(c1.name, "Entertainment")
def test_save_commit_false(self):
# If you call save() with commit=False, then it will return an object that
# hasn't yet been saved to the database. In this case, it's up to you to call
# save() on the resulting model instance.
f = BaseCategoryForm(
{"name": "Third test", "slug": "third-test", "url": "third"}
)
self.assertTrue(f.is_valid())
c1 = f.save(commit=False)
self.assertEqual(c1.name, "Third test")
self.assertEqual(Category.objects.count(), 0)
c1.save()
self.assertEqual(Category.objects.count(), 1)
def test_save_with_data_errors(self):
# If you call save() with invalid data, you'll get a ValueError.
f = BaseCategoryForm({"name": "", "slug": "not a slug!", "url": "foo"})
self.assertEqual(f.errors["name"], ["This field is required."])
self.assertEqual(
f.errors["slug"],
[
"Enter a valid “slug” consisting of letters, numbers, underscores or "
"hyphens."
],
)
self.assertEqual(f.cleaned_data, {"url": "foo"})
msg = "The Category could not be created because the data didn't validate."
with self.assertRaisesMessage(ValueError, msg):
f.save()
f = BaseCategoryForm({"name": "", "slug": "", "url": "foo"})
with self.assertRaisesMessage(ValueError, msg):
f.save()
def test_multi_fields(self):
self.create_basic_data()
self.maxDiff = None
# ManyToManyFields are represented by a MultipleChoiceField, ForeignKeys and any
# fields with the 'choices' attribute are represented by a ChoiceField.
f = ArticleForm(auto_id=False)
self.assertHTMLEqual(
str(f),
"""
<div>Headline:
<input type="text" name="headline" maxlength="50" required>
</div>
<div>Slug:
<input type="text" name="slug" maxlength="50" required>
</div>
<div>Pub date:
<input type="text" name="pub_date" required>
</div>
<div>Writer:
<select name="writer" required>
<option value="" selected>---------</option>
<option value="%s">Bob Woodward</option>
<option value="%s">Mike Royko</option>
</select>
</div>
<div>Article:
<textarea name="article" cols="40" rows="10" required></textarea>
</div>
<div>Categories:
<select name="categories" multiple>
<option value="%s">Entertainment</option>
<option value="%s">It's a test</option>
<option value="%s">Third test</option>
</select>
</div>
<div>Status:
<select name="status">
<option value="" selected>---------</option>
<option value="1">Draft</option><option value="2">Pending</option>
<option value="3">Live</option>
</select>
</div>
"""
% (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
)
# Add some categories and test the many-to-many form output.
new_art = Article.objects.create(
article="Hello.",
headline="New headline",
slug="new-headline",
pub_date=datetime.date(1988, 1, 4),
writer=self.w_royko,
)
new_art.categories.add(Category.objects.get(name="Entertainment"))
self.assertSequenceEqual(new_art.categories.all(), [self.c1])
f = ArticleForm(auto_id=False, instance=new_art)
self.assertHTMLEqual(
f.as_ul(),
"""
<li>Headline:
<input type="text" name="headline" value="New headline" maxlength="50"
required>
</li>
<li>Slug:
<input type="text" name="slug" value="new-headline" maxlength="50" required>
</li>
<li>Pub date:
<input type="text" name="pub_date" value="1988-01-04" required></li>
<li>Writer: <select name="writer" required>
<option value="">---------</option>
<option value="%s">Bob Woodward</option>
<option value="%s" selected>Mike Royko</option>
</select></li>
<li>Article:
<textarea rows="10" cols="40" name="article" required>Hello.</textarea></li>
<li>Categories: <select multiple name="categories">
<option value="%s" selected>Entertainment</option>
<option value="%s">It's a test</option>
<option value="%s">Third test</option>
</select></li>
<li>Status: <select name="status">
<option value="" selected>---------</option>
<option value="1">Draft</option>
<option value="2">Pending</option>
<option value="3">Live</option>
</select></li>
"""
% (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
)
def test_subset_fields(self):
# You can restrict a form to a subset of the complete list of fields
# by providing a 'fields' argument. If you try to save a
# model created with such a form, you need to ensure that the fields
# that are _not_ on the form have default values, or are allowed to have
# a value of None. If a field isn't specified on a form, the object created
# from the form can't provide a value for that field!
class PartialArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ("headline", "pub_date")
f = PartialArticleForm(auto_id=False)
self.assertHTMLEqual(
str(f),
'<div>Headline:<input type="text" name="headline" maxlength="50" required>'
'</div><div>Pub date:<input type="text" name="pub_date" required></div>',
)
class PartialArticleFormWithSlug(forms.ModelForm):
class Meta:
model = Article
fields = ("headline", "slug", "pub_date")
w_royko = Writer.objects.create(name="Mike Royko")
art = Article.objects.create(
article="Hello.",
headline="New headline",
slug="new-headline",
pub_date=datetime.date(1988, 1, 4),
writer=w_royko,
)
f = PartialArticleFormWithSlug(
{
"headline": "New headline",
"slug": "new-headline",
"pub_date": "1988-01-04",
},
auto_id=False,
instance=art,
)
self.assertHTMLEqual(
f.as_ul(),
"""
<li>Headline:
<input type="text" name="headline" value="New headline" maxlength="50"
required>
</li>
<li>Slug:
<input type="text" name="slug" value="new-headline" maxlength="50"
required>
</li>
<li>Pub date:
<input type="text" name="pub_date" value="1988-01-04" required></li>
""",
)
self.assertTrue(f.is_valid())
new_art = f.save()
self.assertEqual(new_art.id, art.id)
new_art = Article.objects.get(id=art.id)
self.assertEqual(new_art.headline, "New headline")
def test_m2m_editing(self):
self.create_basic_data()
form_data = {
"headline": "New headline",
"slug": "new-headline",
"pub_date": "1988-01-04",
"writer": str(self.w_royko.pk),
"article": "Hello.",
"categories": [str(self.c1.id), str(self.c2.id)],
}
# Create a new article, with categories, via the form.
f = ArticleForm(form_data)
new_art = f.save()
new_art = Article.objects.get(id=new_art.id)
art_id_1 = new_art.id
self.assertSequenceEqual(
new_art.categories.order_by("name"), [self.c1, self.c2]
)
# Now, submit form data with no categories. This deletes the existing
# categories.
form_data["categories"] = []
f = ArticleForm(form_data, instance=new_art)
new_art = f.save()
self.assertEqual(new_art.id, art_id_1)
new_art = Article.objects.get(id=art_id_1)
self.assertSequenceEqual(new_art.categories.all(), [])
# Create a new article, with no categories, via the form.
f = ArticleForm(form_data)
new_art = f.save()
art_id_2 = new_art.id
self.assertNotIn(art_id_2, (None, art_id_1))
new_art = Article.objects.get(id=art_id_2)
self.assertSequenceEqual(new_art.categories.all(), [])
# Create a new article, with categories, via the form, but use commit=False.
# The m2m data won't be saved until save_m2m() is invoked on the form.
form_data["categories"] = [str(self.c1.id), str(self.c2.id)]
f = ArticleForm(form_data)
new_art = f.save(commit=False)
# Manually save the instance
new_art.save()
art_id_3 = new_art.id
self.assertNotIn(art_id_3, (None, art_id_1, art_id_2))
# The instance doesn't have m2m data yet
new_art = Article.objects.get(id=art_id_3)
self.assertSequenceEqual(new_art.categories.all(), [])
# Save the m2m data on the form
f.save_m2m()
self.assertSequenceEqual(
new_art.categories.order_by("name"), [self.c1, self.c2]
)
def test_custom_form_fields(self):
# Here, we define a custom ModelForm. Because it happens to have the
# same fields as the Category model, we can just call the form's save()
# to apply its changes to an existing Category instance.
class ShortCategory(forms.ModelForm):
name = forms.CharField(max_length=5)
slug = forms.CharField(max_length=5)
url = forms.CharField(max_length=3)
class Meta:
model = Category
fields = "__all__"
cat = Category.objects.create(name="Third test")
form = ShortCategory(
{"name": "Third", "slug": "third", "url": "3rd"}, instance=cat
)
self.assertEqual(form.save().name, "Third")
self.assertEqual(Category.objects.get(id=cat.id).name, "Third")
def test_runtime_choicefield_populated(self):
self.maxDiff = None
# Here, we demonstrate that choices for a ForeignKey ChoiceField are determined
# at runtime, based on the data in the database when the form is displayed, not
# the data in the database when the form is instantiated.
self.create_basic_data()
f = ArticleForm(auto_id=False)
self.assertHTMLEqual(
f.as_ul(),
'<li>Headline: <input type="text" name="headline" maxlength="50" required>'
"</li>"
'<li>Slug: <input type="text" name="slug" maxlength="50" required></li>'
'<li>Pub date: <input type="text" name="pub_date" required></li>'
'<li>Writer: <select name="writer" required>'
'<option value="" selected>---------</option>'
'<option value="%s">Bob Woodward</option>'
'<option value="%s">Mike Royko</option>'
"</select></li>"
'<li>Article: <textarea rows="10" cols="40" name="article" required>'
"</textarea></li>"
'<li>Categories: <select multiple name="categories">'
'<option value="%s">Entertainment</option>'
'<option value="%s">It's a test</option>'
'<option value="%s">Third test</option>'
"</select> </li>"
'<li>Status: <select name="status">'
'<option value="" selected>---------</option>'
'<option value="1">Draft</option>'
'<option value="2">Pending</option>'
'<option value="3">Live</option>'
"</select></li>"
% (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
)
c4 = Category.objects.create(name="Fourth", url="4th")
w_bernstein = Writer.objects.create(name="Carl Bernstein")
self.assertHTMLEqual(
f.as_ul(),
'<li>Headline: <input type="text" name="headline" maxlength="50" required>'
"</li>"
'<li>Slug: <input type="text" name="slug" maxlength="50" required></li>'
'<li>Pub date: <input type="text" name="pub_date" required></li>'
'<li>Writer: <select name="writer" required>'
'<option value="" selected>---------</option>'
'<option value="%s">Bob Woodward</option>'
'<option value="%s">Carl Bernstein</option>'
'<option value="%s">Mike Royko</option>'
"</select></li>"
'<li>Article: <textarea rows="10" cols="40" name="article" required>'
"</textarea></li>"
'<li>Categories: <select multiple name="categories">'
'<option value="%s">Entertainment</option>'
'<option value="%s">It's a test</option>'
'<option value="%s">Third test</option>'
'<option value="%s">Fourth</option>'
"</select></li>"
'<li>Status: <select name="status">'
'<option value="" selected>---------</option>'
'<option value="1">Draft</option>'
'<option value="2">Pending</option>'
'<option value="3">Live</option>'
"</select></li>"
% (
self.w_woodward.pk,
w_bernstein.pk,
self.w_royko.pk,
self.c1.pk,
self.c2.pk,
self.c3.pk,
c4.pk,
),
)
def test_recleaning_model_form_instance(self):
"""
Re-cleaning an instance that was added via a ModelForm shouldn't raise
a pk uniqueness error.
"""
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
fields = "__all__"
form = AuthorForm({"full_name": "Bob"})
self.assertTrue(form.is_valid())
obj = form.save()
obj.name = "Alice"
obj.full_clean()
def test_validate_foreign_key_uses_default_manager(self):
class MyForm(forms.ModelForm):
class Meta:
model = Article
fields = "__all__"
# Archived writers are filtered out by the default manager.
w = Writer.objects.create(name="Randy", archived=True)
data = {
"headline": "My Article",
"slug": "my-article",
"pub_date": datetime.date.today(),
"writer": w.pk,
"article": "lorem ipsum",
}
form = MyForm(data)
self.assertIs(form.is_valid(), False)
self.assertEqual(
form.errors,
{
"writer": [
"Select a valid choice. That choice is not one of the available "
"choices."
]
},
)
def test_validate_foreign_key_to_model_with_overridden_manager(self):
class MyForm(forms.ModelForm):
class Meta:
model = Article
fields = "__all__"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Allow archived authors.
self.fields["writer"].queryset = Writer._base_manager.all()
w = Writer.objects.create(name="Randy", archived=True)
data = {
"headline": "My Article",
"slug": "my-article",
"pub_date": datetime.date.today(),
"writer": w.pk,
"article": "lorem ipsum",
}
form = MyForm(data)
self.assertIs(form.is_valid(), True)
article = form.save()
self.assertEqual(article.writer, w)
class ModelMultipleChoiceFieldTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.c1 = Category.objects.create(
name="Entertainment", slug="entertainment", url="entertainment"
)
cls.c2 = Category.objects.create(
name="It's a test", slug="its-test", url="test"
)
cls.c3 = Category.objects.create(name="Third", slug="third-test", url="third")
def test_model_multiple_choice_field(self):
f = forms.ModelMultipleChoiceField(Category.objects.all())
self.assertCountEqual(
list(f.choices),
[
(self.c1.pk, "Entertainment"),
(self.c2.pk, "It's a test"),
(self.c3.pk, "Third"),
],
)
with self.assertRaises(ValidationError):
f.clean(None)
with self.assertRaises(ValidationError):
f.clean([])
self.assertCountEqual(f.clean([self.c1.id]), [self.c1])
self.assertCountEqual(f.clean([self.c2.id]), [self.c2])
self.assertCountEqual(f.clean([str(self.c1.id)]), [self.c1])
self.assertCountEqual(
f.clean([str(self.c1.id), str(self.c2.id)]),
[self.c1, self.c2],
)
self.assertCountEqual(
f.clean([self.c1.id, str(self.c2.id)]),
[self.c1, self.c2],
)
self.assertCountEqual(
f.clean((self.c1.id, str(self.c2.id))),
[self.c1, self.c2],
)
with self.assertRaises(ValidationError):
f.clean(["0"])
with self.assertRaises(ValidationError):
f.clean("hello")
with self.assertRaises(ValidationError):
f.clean(["fail"])
# Invalid types that require TypeError to be caught (#22808).
with self.assertRaises(ValidationError):
f.clean([["fail"]])
with self.assertRaises(ValidationError):
f.clean([{"foo": "bar"}])
# Add a Category object *after* the ModelMultipleChoiceField has already been
# instantiated. This proves clean() checks the database during clean() rather
# than caching it at time of instantiation.
# Note, we are using an id of 1006 here since tests that run before
# this may create categories with primary keys up to 6. Use
# a number that will not conflict.
c6 = Category.objects.create(id=1006, name="Sixth", url="6th")
self.assertCountEqual(f.clean([c6.id]), [c6])
# Delete a Category object *after* the ModelMultipleChoiceField has already been
# instantiated. This proves clean() checks the database during clean() rather
# than caching it at time of instantiation.
Category.objects.get(url="6th").delete()
with self.assertRaises(ValidationError):
f.clean([c6.id])
def test_model_multiple_choice_required_false(self):
f = forms.ModelMultipleChoiceField(Category.objects.all(), required=False)
self.assertIsInstance(f.clean([]), EmptyQuerySet)
self.assertIsInstance(f.clean(()), EmptyQuerySet)
with self.assertRaises(ValidationError):
f.clean(["0"])
with self.assertRaises(ValidationError):
f.clean([str(self.c3.id), "0"])
with self.assertRaises(ValidationError):
f.clean([str(self.c1.id), "0"])
# queryset can be changed after the field is created.
f.queryset = Category.objects.exclude(name="Third")
self.assertCountEqual(
list(f.choices),
[(self.c1.pk, "Entertainment"), (self.c2.pk, "It's a test")],
)
self.assertSequenceEqual(f.clean([self.c2.id]), [self.c2])
with self.assertRaises(ValidationError):
f.clean([self.c3.id])
with self.assertRaises(ValidationError):
f.clean([str(self.c2.id), str(self.c3.id)])
f.queryset = Category.objects.all()
f.label_from_instance = lambda obj: "multicategory " + str(obj)
self.assertCountEqual(
list(f.choices),
[
(self.c1.pk, "multicategory Entertainment"),
(self.c2.pk, "multicategory It's a test"),
(self.c3.pk, "multicategory Third"),
],
)
def test_model_multiple_choice_number_of_queries(self):
"""
ModelMultipleChoiceField does O(1) queries instead of O(n) (#10156).
"""
persons = [Writer.objects.create(name="Person %s" % i) for i in range(30)]
f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all())
self.assertNumQueries(1, f.clean, [p.pk for p in persons[1:11:2]])
def test_model_multiple_choice_run_validators(self):
"""
ModelMultipleChoiceField run given validators (#14144).
"""
for i in range(30):
Writer.objects.create(name="Person %s" % i)
self._validator_run = False
def my_validator(value):
self._validator_run = True
f = forms.ModelMultipleChoiceField(
queryset=Writer.objects.all(), validators=[my_validator]
)
f.clean([p.pk for p in Writer.objects.all()[8:9]])
self.assertTrue(self._validator_run)
def test_model_multiple_choice_show_hidden_initial(self):
"""
Test support of show_hidden_initial by ModelMultipleChoiceField.
"""
class WriterForm(forms.Form):
persons = forms.ModelMultipleChoiceField(
show_hidden_initial=True, queryset=Writer.objects.all()
)
person1 = Writer.objects.create(name="Person 1")
person2 = Writer.objects.create(name="Person 2")
form = WriterForm(
initial={"persons": [person1, person2]},
data={
"initial-persons": [str(person1.pk), str(person2.pk)],
"persons": [str(person1.pk), str(person2.pk)],
},
)
self.assertTrue(form.is_valid())
self.assertFalse(form.has_changed())
form = WriterForm(
initial={"persons": [person1, person2]},
data={
"initial-persons": [str(person1.pk), str(person2.pk)],
"persons": [str(person2.pk)],
},
)
self.assertTrue(form.is_valid())
self.assertTrue(form.has_changed())
def test_model_multiple_choice_field_22745(self):
"""
#22745 -- Make sure that ModelMultipleChoiceField with
CheckboxSelectMultiple widget doesn't produce unnecessary db queries
when accessing its BoundField's attrs.
"""
class ModelMultipleChoiceForm(forms.Form):
categories = forms.ModelMultipleChoiceField(
Category.objects.all(), widget=forms.CheckboxSelectMultiple
)
form = ModelMultipleChoiceForm()
field = form["categories"] # BoundField
template = Template("{{ field.name }}{{ field }}{{ field.help_text }}")
with self.assertNumQueries(1):
template.render(Context({"field": field}))
def test_show_hidden_initial_changed_queries_efficiently(self):
class WriterForm(forms.Form):
persons = forms.ModelMultipleChoiceField(
show_hidden_initial=True, queryset=Writer.objects.all()
)
writers = (Writer.objects.create(name=str(x)) for x in range(0, 50))
writer_pks = tuple(x.pk for x in writers)
form = WriterForm(data={"initial-persons": writer_pks})
with self.assertNumQueries(1):
self.assertTrue(form.has_changed())
def test_clean_does_deduplicate_values(self):
class PersonForm(forms.Form):
persons = forms.ModelMultipleChoiceField(queryset=Person.objects.all())
person1 = Person.objects.create(name="Person 1")
form = PersonForm(data={})
queryset = form.fields["persons"].clean([str(person1.pk)] * 50)
sql, params = queryset.query.sql_with_params()
self.assertEqual(len(params), 1)
def test_to_field_name_with_initial_data(self):
class ArticleCategoriesForm(forms.ModelForm):
categories = forms.ModelMultipleChoiceField(
Category.objects.all(), to_field_name="slug"
)
class Meta:
model = Article
fields = ["categories"]
article = Article.objects.create(
headline="Test article",
slug="test-article",
pub_date=datetime.date(1988, 1, 4),
writer=Writer.objects.create(name="Test writer"),
article="Hello.",
)
article.categories.add(self.c2, self.c3)
form = ArticleCategoriesForm(instance=article)
self.assertCountEqual(form["categories"].value(), [self.c2.slug, self.c3.slug])
class ModelOneToOneFieldTests(TestCase):
def test_modelform_onetoonefield(self):
class ImprovedArticleForm(forms.ModelForm):
class Meta:
model = ImprovedArticle
fields = "__all__"
class ImprovedArticleWithParentLinkForm(forms.ModelForm):
class Meta:
model = ImprovedArticleWithParentLink
fields = "__all__"
self.assertEqual(list(ImprovedArticleForm.base_fields), ["article"])
self.assertEqual(list(ImprovedArticleWithParentLinkForm.base_fields), [])
def test_modelform_subclassed_model(self):
class BetterWriterForm(forms.ModelForm):
class Meta:
# BetterWriter model is a subclass of Writer with an additional
# `score` field.
model = BetterWriter
fields = "__all__"
bw = BetterWriter.objects.create(name="Joe Better", score=10)
self.assertEqual(
sorted(model_to_dict(bw)), ["id", "name", "score", "writer_ptr"]
)
self.assertEqual(sorted(model_to_dict(bw, fields=[])), [])
self.assertEqual(
sorted(model_to_dict(bw, fields=["id", "name"])), ["id", "name"]
)
self.assertEqual(
sorted(model_to_dict(bw, exclude=[])), ["id", "name", "score", "writer_ptr"]
)
self.assertEqual(
sorted(model_to_dict(bw, exclude=["id", "name"])), ["score", "writer_ptr"]
)
form = BetterWriterForm({"name": "Some Name", "score": 12})
self.assertTrue(form.is_valid())
bw2 = form.save()
self.assertEqual(bw2.score, 12)
def test_onetoonefield(self):
class WriterProfileForm(forms.ModelForm):
class Meta:
# WriterProfile has a OneToOneField to Writer
model = WriterProfile
fields = "__all__"
self.w_royko = Writer.objects.create(name="Mike Royko")
self.w_woodward = Writer.objects.create(name="Bob Woodward")
form = WriterProfileForm()
self.assertHTMLEqual(
form.as_p(),
"""
<p><label for="id_writer">Writer:</label>
<select name="writer" id="id_writer" required>
<option value="" selected>---------</option>
<option value="%s">Bob Woodward</option>
<option value="%s">Mike Royko</option>
</select></p>
<p><label for="id_age">Age:</label>
<input type="number" name="age" id="id_age" min="0" required></p>
"""
% (
self.w_woodward.pk,
self.w_royko.pk,
),
)
data = {
"writer": str(self.w_woodward.pk),
"age": "65",
}
form = WriterProfileForm(data)
instance = form.save()
self.assertEqual(str(instance), "Bob Woodward is 65")
form = WriterProfileForm(instance=instance)
self.assertHTMLEqual(
form.as_p(),
"""
<p><label for="id_writer">Writer:</label>
<select name="writer" id="id_writer" required>
<option value="">---------</option>
<option value="%s" selected>Bob Woodward</option>
<option value="%s">Mike Royko</option>
</select></p>
<p><label for="id_age">Age:</label>
<input type="number" name="age" value="65" id="id_age" min="0" required>
</p>"""
% (
self.w_woodward.pk,
self.w_royko.pk,
),
)
def test_assignment_of_none(self):
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
fields = ["publication", "full_name"]
publication = Publication.objects.create(
title="Pravda", date_published=datetime.date(1991, 8, 22)
)
author = Author.objects.create(publication=publication, full_name="John Doe")
form = AuthorForm({"publication": "", "full_name": "John Doe"}, instance=author)
self.assertTrue(form.is_valid())
self.assertIsNone(form.cleaned_data["publication"])
author = form.save()
# author object returned from form still retains original publication object
# that's why we need to retrieve it from database again
new_author = Author.objects.get(pk=author.pk)
self.assertIsNone(new_author.publication)
def test_assignment_of_none_null_false(self):
class AuthorForm(forms.ModelForm):
class Meta:
model = Author1
fields = ["publication", "full_name"]
publication = Publication.objects.create(
title="Pravda", date_published=datetime.date(1991, 8, 22)
)
author = Author1.objects.create(publication=publication, full_name="John Doe")
form = AuthorForm({"publication": "", "full_name": "John Doe"}, instance=author)
self.assertFalse(form.is_valid())
class FileAndImageFieldTests(TestCase):
def test_clean_false(self):
"""
If the ``clean`` method on a non-required FileField receives False as
the data (meaning clear the field value), it returns False, regardless
of the value of ``initial``.
"""
f = forms.FileField(required=False)
self.assertIs(f.clean(False), False)
self.assertIs(f.clean(False, "initial"), False)
def test_clean_false_required(self):
"""
If the ``clean`` method on a required FileField receives False as the
data, it has the same effect as None: initial is returned if non-empty,
otherwise the validation catches the lack of a required value.
"""
f = forms.FileField(required=True)
self.assertEqual(f.clean(False, "initial"), "initial")
with self.assertRaises(ValidationError):
f.clean(False)
def test_full_clear(self):
"""
Integration happy-path test that a model FileField can actually be set
and cleared via a ModelForm.
"""
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = "__all__"
form = DocumentForm()
self.assertIn('name="myfile"', str(form))
self.assertNotIn("myfile-clear", str(form))
form = DocumentForm(
files={"myfile": SimpleUploadedFile("something.txt", b"content")}
)
self.assertTrue(form.is_valid())
doc = form.save(commit=False)
self.assertEqual(doc.myfile.name, "something.txt")
form = DocumentForm(instance=doc)
self.assertIn("myfile-clear", str(form))
form = DocumentForm(instance=doc, data={"myfile-clear": "true"})
doc = form.save(commit=False)
self.assertFalse(doc.myfile)
def test_clear_and_file_contradiction(self):
"""
If the user submits a new file upload AND checks the clear checkbox,
they get a validation error, and the bound redisplay of the form still
includes the current file and the clear checkbox.
"""
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = "__all__"
form = DocumentForm(
files={"myfile": SimpleUploadedFile("something.txt", b"content")}
)
self.assertTrue(form.is_valid())
doc = form.save(commit=False)
form = DocumentForm(
instance=doc,
files={"myfile": SimpleUploadedFile("something.txt", b"content")},
data={"myfile-clear": "true"},
)
self.assertTrue(not form.is_valid())
self.assertEqual(
form.errors["myfile"],
["Please either submit a file or check the clear checkbox, not both."],
)
rendered = str(form)
self.assertIn("something.txt", rendered)
self.assertIn("myfile-clear", rendered)
def test_render_empty_file_field(self):
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = "__all__"
doc = Document.objects.create()
form = DocumentForm(instance=doc)
self.assertHTMLEqual(
str(form["myfile"]), '<input id="id_myfile" name="myfile" type="file">'
)
def test_file_field_data(self):
# Test conditions when files is either not given or empty.
f = TextFileForm(data={"description": "Assistance"})
self.assertFalse(f.is_valid())
f = TextFileForm(data={"description": "Assistance"}, files={})
self.assertFalse(f.is_valid())
# Upload a file and ensure it all works as expected.
f = TextFileForm(
data={"description": "Assistance"},
files={"file": SimpleUploadedFile("test1.txt", b"hello world")},
)
self.assertTrue(f.is_valid())
self.assertEqual(type(f.cleaned_data["file"]), SimpleUploadedFile)
instance = f.save()
self.assertEqual(instance.file.name, "tests/test1.txt")
instance.file.delete()
# If the previous file has been deleted, the file name can be reused
f = TextFileForm(
data={"description": "Assistance"},
files={"file": SimpleUploadedFile("test1.txt", b"hello world")},
)
self.assertTrue(f.is_valid())
self.assertEqual(type(f.cleaned_data["file"]), SimpleUploadedFile)
instance = f.save()
self.assertEqual(instance.file.name, "tests/test1.txt")
# Check if the max_length attribute has been inherited from the model.
f = TextFileForm(
data={"description": "Assistance"},
files={"file": SimpleUploadedFile("test-maxlength.txt", b"hello world")},
)
self.assertFalse(f.is_valid())
# Edit an instance that already has the file defined in the model. This will not
# save the file again, but leave it exactly as it is.
f = TextFileForm({"description": "Assistance"}, instance=instance)
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data["file"].name, "tests/test1.txt")
instance = f.save()
self.assertEqual(instance.file.name, "tests/test1.txt")
# Delete the current file since this is not done by Django.
instance.file.delete()
# Override the file by uploading a new one.
f = TextFileForm(
data={"description": "Assistance"},
files={"file": SimpleUploadedFile("test2.txt", b"hello world")},
instance=instance,
)
self.assertTrue(f.is_valid())
instance = f.save()
self.assertEqual(instance.file.name, "tests/test2.txt")
# Delete the current file since this is not done by Django.
instance.file.delete()
instance.delete()
def test_filefield_required_false(self):
# Test the non-required FileField
f = TextFileForm(data={"description": "Assistance"})
f.fields["file"].required = False
self.assertTrue(f.is_valid())
instance = f.save()
self.assertEqual(instance.file.name, "")
f = TextFileForm(
data={"description": "Assistance"},
files={"file": SimpleUploadedFile("test3.txt", b"hello world")},
instance=instance,
)
self.assertTrue(f.is_valid())
instance = f.save()
self.assertEqual(instance.file.name, "tests/test3.txt")
# Instance can be edited w/out re-uploading the file and existing file
# should be preserved.
f = TextFileForm({"description": "New Description"}, instance=instance)
f.fields["file"].required = False
self.assertTrue(f.is_valid())
instance = f.save()
self.assertEqual(instance.description, "New Description")
self.assertEqual(instance.file.name, "tests/test3.txt")
# Delete the current file since this is not done by Django.
instance.file.delete()
instance.delete()
def test_custom_file_field_save(self):
"""
Regression for #11149: save_form_data should be called only once
"""
class CFFForm(forms.ModelForm):
class Meta:
model = CustomFF
fields = "__all__"
# It's enough that the form saves without error -- the custom save routine will
# generate an AssertionError if it is called more than once during save.
form = CFFForm(data={"f": None})
form.save()
def test_file_field_multiple_save(self):
"""
Simulate a file upload and check how many times Model.save() gets
called. Test for bug #639.
"""
class PhotoForm(forms.ModelForm):
class Meta:
model = Photo
fields = "__all__"
# Grab an image for testing.
filename = os.path.join(os.path.dirname(__file__), "test.png")
with open(filename, "rb") as fp:
img = fp.read()
# Fake a POST QueryDict and FILES MultiValueDict.
data = {"title": "Testing"}
files = {"image": SimpleUploadedFile("test.png", img, "image/png")}
form = PhotoForm(data=data, files=files)
p = form.save()
try:
# Check the savecount stored on the object (see the model).
self.assertEqual(p._savecount, 1)
finally:
# Delete the "uploaded" file to avoid clogging /tmp.
p = Photo.objects.get()
p.image.delete(save=False)
def test_file_path_field_blank(self):
"""FilePathField(blank=True) includes the empty option."""
class FPForm(forms.ModelForm):
class Meta:
model = FilePathModel
fields = "__all__"
form = FPForm()
self.assertEqual(
[name for _, name in form["path"].field.choices], ["---------", "models.py"]
)
@skipUnless(test_images, "Pillow not installed")
def test_image_field(self):
# ImageField and FileField are nearly identical, but they differ slightly when
# it comes to validation. This specifically tests that #6302 is fixed for
# both file fields and image fields.
with open(os.path.join(os.path.dirname(__file__), "test.png"), "rb") as fp:
image_data = fp.read()
with open(os.path.join(os.path.dirname(__file__), "test2.png"), "rb") as fp:
image_data2 = fp.read()
f = ImageFileForm(
data={"description": "An image"},
files={"image": SimpleUploadedFile("test.png", image_data)},
)
self.assertTrue(f.is_valid())
self.assertEqual(type(f.cleaned_data["image"]), SimpleUploadedFile)
instance = f.save()
self.assertEqual(instance.image.name, "tests/test.png")
self.assertEqual(instance.width, 16)
self.assertEqual(instance.height, 16)
# Delete the current file since this is not done by Django, but don't save
# because the dimension fields are not null=True.
instance.image.delete(save=False)
f = ImageFileForm(
data={"description": "An image"},
files={"image": SimpleUploadedFile("test.png", image_data)},
)
self.assertTrue(f.is_valid())
self.assertEqual(type(f.cleaned_data["image"]), SimpleUploadedFile)
instance = f.save()
self.assertEqual(instance.image.name, "tests/test.png")
self.assertEqual(instance.width, 16)
self.assertEqual(instance.height, 16)
# Edit an instance that already has the (required) image defined in the
# model. This will not save the image again, but leave it exactly as it
# is.
f = ImageFileForm(data={"description": "Look, it changed"}, instance=instance)
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data["image"].name, "tests/test.png")
instance = f.save()
self.assertEqual(instance.image.name, "tests/test.png")
self.assertEqual(instance.height, 16)
self.assertEqual(instance.width, 16)
# Delete the current file since this is not done by Django, but don't save
# because the dimension fields are not null=True.
instance.image.delete(save=False)
# Override the file by uploading a new one.
f = ImageFileForm(
data={"description": "Changed it"},
files={"image": SimpleUploadedFile("test2.png", image_data2)},
instance=instance,
)
self.assertTrue(f.is_valid())
instance = f.save()
self.assertEqual(instance.image.name, "tests/test2.png")
self.assertEqual(instance.height, 32)
self.assertEqual(instance.width, 48)
# Delete the current file since this is not done by Django, but don't save
# because the dimension fields are not null=True.
instance.image.delete(save=False)
instance.delete()
f = ImageFileForm(
data={"description": "Changed it"},
files={"image": SimpleUploadedFile("test2.png", image_data2)},
)
self.assertTrue(f.is_valid())
instance = f.save()
self.assertEqual(instance.image.name, "tests/test2.png")
self.assertEqual(instance.height, 32)
self.assertEqual(instance.width, 48)
# Delete the current file since this is not done by Django, but don't save
# because the dimension fields are not null=True.
instance.image.delete(save=False)
instance.delete()
# Test the non-required ImageField
# Note: In Oracle, we expect a null ImageField to return '' instead of
# None.
if connection.features.interprets_empty_strings_as_nulls:
expected_null_imagefield_repr = ""
else:
expected_null_imagefield_repr = None
f = OptionalImageFileForm(data={"description": "Test"})
self.assertTrue(f.is_valid())
instance = f.save()
self.assertEqual(instance.image.name, expected_null_imagefield_repr)
self.assertIsNone(instance.width)
self.assertIsNone(instance.height)
f = OptionalImageFileForm(
data={"description": "And a final one"},
files={"image": SimpleUploadedFile("test3.png", image_data)},
instance=instance,
)
self.assertTrue(f.is_valid())
instance = f.save()
self.assertEqual(instance.image.name, "tests/test3.png")
self.assertEqual(instance.width, 16)
self.assertEqual(instance.height, 16)
# Editing the instance without re-uploading the image should not affect
# the image or its width/height properties.
f = OptionalImageFileForm({"description": "New Description"}, instance=instance)
self.assertTrue(f.is_valid())
instance = f.save()
self.assertEqual(instance.description, "New Description")
self.assertEqual(instance.image.name, "tests/test3.png")
self.assertEqual(instance.width, 16)
self.assertEqual(instance.height, 16)
# Delete the current file since this is not done by Django.
instance.image.delete()
instance.delete()
f = OptionalImageFileForm(
data={"description": "And a final one"},
files={"image": SimpleUploadedFile("test4.png", image_data2)},
)
self.assertTrue(f.is_valid())
instance = f.save()
self.assertEqual(instance.image.name, "tests/test4.png")
self.assertEqual(instance.width, 48)
self.assertEqual(instance.height, 32)
instance.delete()
# Callable upload_to behavior that's dependent on the value of another
# field in the model.
f = ImageFileForm(
data={"description": "And a final one", "path": "foo"},
files={"image": SimpleUploadedFile("test4.png", image_data)},
)
self.assertTrue(f.is_valid())
instance = f.save()
self.assertEqual(instance.image.name, "foo/test4.png")
instance.delete()
# Editing an instance that has an image without an extension shouldn't
# fail validation. First create:
f = NoExtensionImageFileForm(
data={"description": "An image"},
files={"image": SimpleUploadedFile("test.png", image_data)},
)
self.assertTrue(f.is_valid())
instance = f.save()
self.assertEqual(instance.image.name, "tests/no_extension")
# Then edit:
f = NoExtensionImageFileForm(
data={"description": "Edited image"}, instance=instance
)
self.assertTrue(f.is_valid())
class ModelOtherFieldTests(SimpleTestCase):
def test_big_integer_field(self):
bif = BigIntForm({"biggie": "-9223372036854775808"})
self.assertTrue(bif.is_valid())
bif = BigIntForm({"biggie": "-9223372036854775809"})
self.assertFalse(bif.is_valid())
self.assertEqual(
bif.errors,
{
"biggie": [
"Ensure this value is greater than or equal to "
"-9223372036854775808."
]
},
)
bif = BigIntForm({"biggie": "9223372036854775807"})
self.assertTrue(bif.is_valid())
bif = BigIntForm({"biggie": "9223372036854775808"})
self.assertFalse(bif.is_valid())
self.assertEqual(
bif.errors,
{
"biggie": [
"Ensure this value is less than or equal to 9223372036854775807."
]
},
)
def test_url_on_modelform(self):
"Check basic URL field validation on model forms"
class HomepageForm(forms.ModelForm):
class Meta:
model = Homepage
fields = "__all__"
self.assertFalse(HomepageForm({"url": "foo"}).is_valid())
self.assertFalse(HomepageForm({"url": "http://"}).is_valid())
self.assertFalse(HomepageForm({"url": "http://example"}).is_valid())
self.assertFalse(HomepageForm({"url": "http://example."}).is_valid())
self.assertFalse(HomepageForm({"url": "http://com."}).is_valid())
self.assertTrue(HomepageForm({"url": "http://localhost"}).is_valid())
self.assertTrue(HomepageForm({"url": "http://example.com"}).is_valid())
self.assertTrue(HomepageForm({"url": "http://www.example.com"}).is_valid())
self.assertTrue(HomepageForm({"url": "http://www.example.com:8000"}).is_valid())
self.assertTrue(HomepageForm({"url": "http://www.example.com/test"}).is_valid())
self.assertTrue(
HomepageForm({"url": "http://www.example.com:8000/test"}).is_valid()
)
self.assertTrue(HomepageForm({"url": "http://example.com/foo/bar"}).is_valid())
def test_modelform_non_editable_field(self):
"""
When explicitly including a non-editable field in a ModelForm, the
error message should be explicit.
"""
# 'created', non-editable, is excluded by default
self.assertNotIn("created", ArticleForm().fields)
msg = (
"'created' cannot be specified for Article model form as it is a "
"non-editable field"
)
with self.assertRaisesMessage(FieldError, msg):
class InvalidArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ("headline", "created")
def test_http_prefixing(self):
"""
If the http:// prefix is omitted on form input, the field adds it again.
"""
class HomepageForm(forms.ModelForm):
class Meta:
model = Homepage
fields = "__all__"
form = HomepageForm({"url": "example.com"})
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data["url"], "http://example.com")
form = HomepageForm({"url": "example.com/test"})
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data["url"], "http://example.com/test")
class OtherModelFormTests(TestCase):
def test_media_on_modelform(self):
# Similar to a regular Form class you can define custom media to be used on
# the ModelForm.
f = ModelFormWithMedia()
self.assertHTMLEqual(
str(f.media),
'<link href="/some/form/css" media="all" rel="stylesheet">'
'<script src="/some/form/javascript"></script>',
)
def test_choices_type(self):
# Choices on CharField and IntegerField
f = ArticleForm()
with self.assertRaises(ValidationError):
f.fields["status"].clean("42")
f = ArticleStatusForm()
with self.assertRaises(ValidationError):
f.fields["status"].clean("z")
def test_prefetch_related_queryset(self):
"""
ModelChoiceField should respect a prefetch_related() on its queryset.
"""
blue = Colour.objects.create(name="blue")
red = Colour.objects.create(name="red")
multicolor_item = ColourfulItem.objects.create()
multicolor_item.colours.add(blue, red)
red_item = ColourfulItem.objects.create()
red_item.colours.add(red)
class ColorModelChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return ", ".join(c.name for c in obj.colours.all())
field = ColorModelChoiceField(ColourfulItem.objects.prefetch_related("colours"))
with self.assertNumQueries(3): # would be 4 if prefetch is ignored
self.assertEqual(
tuple(field.choices),
(
("", "---------"),
(multicolor_item.pk, "blue, red"),
(red_item.pk, "red"),
),
)
def test_foreignkeys_which_use_to_field(self):
apple = Inventory.objects.create(barcode=86, name="Apple")
pear = Inventory.objects.create(barcode=22, name="Pear")
core = Inventory.objects.create(barcode=87, name="Core", parent=apple)
field = forms.ModelChoiceField(Inventory.objects.all(), to_field_name="barcode")
self.assertEqual(
tuple(field.choices),
(("", "---------"), (86, "Apple"), (87, "Core"), (22, "Pear")),
)
form = InventoryForm(instance=core)
self.assertHTMLEqual(
str(form["parent"]),
"""<select name="parent" id="id_parent">
<option value="">---------</option>
<option value="86" selected>Apple</option>
<option value="87">Core</option>
<option value="22">Pear</option>
</select>""",
)
data = model_to_dict(core)
data["parent"] = "22"
form = InventoryForm(data=data, instance=core)
core = form.save()
self.assertEqual(core.parent.name, "Pear")
class CategoryForm(forms.ModelForm):
description = forms.CharField()
class Meta:
model = Category
fields = ["description", "url"]
self.assertEqual(list(CategoryForm.base_fields), ["description", "url"])
self.assertHTMLEqual(
str(CategoryForm()),
'<div><label for="id_description">Description:</label><input type="text" '
'name="description" required id="id_description"></div><div>'
'<label for="id_url">The URL:</label><input type="text" name="url" '
'maxlength="40" required id="id_url"></div>',
)
# to_field_name should also work on ModelMultipleChoiceField ##################
field = forms.ModelMultipleChoiceField(
Inventory.objects.all(), to_field_name="barcode"
)
self.assertEqual(
tuple(field.choices), ((86, "Apple"), (87, "Core"), (22, "Pear"))
)
self.assertSequenceEqual(field.clean([86]), [apple])
form = SelectInventoryForm({"items": [87, 22]})
self.assertTrue(form.is_valid())
self.assertEqual(len(form.cleaned_data), 1)
self.assertSequenceEqual(form.cleaned_data["items"], [core, pear])
def test_model_field_that_returns_none_to_exclude_itself_with_explicit_fields(self):
self.assertEqual(list(CustomFieldForExclusionForm.base_fields), ["name"])
self.assertHTMLEqual(
str(CustomFieldForExclusionForm()),
'<div><label for="id_name">Name:</label><input type="text" '
'name="name" maxlength="10" required id="id_name"></div>',
)
def test_iterable_model_m2m(self):
class ColourfulItemForm(forms.ModelForm):
class Meta:
model = ColourfulItem
fields = "__all__"
colour = Colour.objects.create(name="Blue")
form = ColourfulItemForm()
self.maxDiff = 1024
self.assertHTMLEqual(
form.as_p(),
"""
<p>
<label for="id_name">Name:</label>
<input id="id_name" type="text" name="name" maxlength="50" required></p>
<p><label for="id_colours">Colours:</label>
<select multiple name="colours" id="id_colours" required>
<option value="%(blue_pk)s">Blue</option>
</select></p>
"""
% {"blue_pk": colour.pk},
)
def test_callable_field_default(self):
class PublicationDefaultsForm(forms.ModelForm):
class Meta:
model = PublicationDefaults
fields = ("title", "date_published", "mode", "category")
self.maxDiff = 2000
form = PublicationDefaultsForm()
today_str = str(datetime.date.today())
self.assertHTMLEqual(
form.as_p(),
"""
<p><label for="id_title">Title:</label>
<input id="id_title" maxlength="30" name="title" type="text" required>
</p>
<p><label for="id_date_published">Date published:</label>
<input id="id_date_published" name="date_published" type="text" value="{0}"
required>
<input id="initial-id_date_published" name="initial-date_published"
type="hidden" value="{0}">
</p>
<p><label for="id_mode">Mode:</label> <select id="id_mode" name="mode">
<option value="di" selected>direct</option>
<option value="de">delayed</option></select>
<input id="initial-id_mode" name="initial-mode" type="hidden" value="di">
</p>
<p>
<label for="id_category">Category:</label>
<select id="id_category" name="category">
<option value="1">Games</option>
<option value="2">Comics</option>
<option value="3" selected>Novel</option></select>
<input id="initial-id_category" name="initial-category" type="hidden"
value="3">
""".format(
today_str
),
)
empty_data = {
"title": "",
"date_published": today_str,
"initial-date_published": today_str,
"mode": "di",
"initial-mode": "di",
"category": "3",
"initial-category": "3",
}
bound_form = PublicationDefaultsForm(empty_data)
self.assertFalse(bound_form.has_changed())
class ModelFormCustomErrorTests(SimpleTestCase):
def test_custom_error_messages(self):
data = {"name1": "@#$!!**@#$", "name2": "@#$!!**@#$"}
errors = CustomErrorMessageForm(data).errors
self.assertHTMLEqual(
str(errors["name1"]),
'<ul class="errorlist"><li>Form custom error message.</li></ul>',
)
self.assertHTMLEqual(
str(errors["name2"]),
'<ul class="errorlist"><li>Model custom error message.</li></ul>',
)
def test_model_clean_error_messages(self):
data = {"name1": "FORBIDDEN_VALUE", "name2": "ABC"}
form = CustomErrorMessageForm(data)
self.assertFalse(form.is_valid())
self.assertHTMLEqual(
str(form.errors["name1"]),
'<ul class="errorlist"><li>Model.clean() error messages.</li></ul>',
)
data = {"name1": "FORBIDDEN_VALUE2", "name2": "ABC"}
form = CustomErrorMessageForm(data)
self.assertFalse(form.is_valid())
self.assertHTMLEqual(
str(form.errors["name1"]),
'<ul class="errorlist">'
"<li>Model.clean() error messages (simpler syntax).</li></ul>",
)
data = {"name1": "GLOBAL_ERROR", "name2": "ABC"}
form = CustomErrorMessageForm(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors["__all__"], ["Global error message."])
class CustomCleanTests(TestCase):
def test_override_clean(self):
"""
Regression for #12596: Calling super from ModelForm.clean() should be
optional.
"""
class TripleFormWithCleanOverride(forms.ModelForm):
class Meta:
model = Triple
fields = "__all__"
def clean(self):
if not self.cleaned_data["left"] == self.cleaned_data["right"]:
raise ValidationError("Left and right should be equal")
return self.cleaned_data
form = TripleFormWithCleanOverride({"left": 1, "middle": 2, "right": 1})
self.assertTrue(form.is_valid())
# form.instance.left will be None if the instance was not constructed
# by form.full_clean().
self.assertEqual(form.instance.left, 1)
def test_model_form_clean_applies_to_model(self):
"""
Regression test for #12960. Make sure the cleaned_data returned from
ModelForm.clean() is applied to the model instance.
"""
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = "__all__"
def clean(self):
self.cleaned_data["name"] = self.cleaned_data["name"].upper()
return self.cleaned_data
data = {"name": "Test", "slug": "test", "url": "/test"}
form = CategoryForm(data)
category = form.save()
self.assertEqual(category.name, "TEST")
class ModelFormInheritanceTests(SimpleTestCase):
def test_form_subclass_inheritance(self):
class Form(forms.Form):
age = forms.IntegerField()
class ModelForm(forms.ModelForm, Form):
class Meta:
model = Writer
fields = "__all__"
self.assertEqual(list(ModelForm().fields), ["name", "age"])
def test_field_removal(self):
class ModelForm(forms.ModelForm):
class Meta:
model = Writer
fields = "__all__"
class Mixin:
age = None
class Form(forms.Form):
age = forms.IntegerField()
class Form2(forms.Form):
foo = forms.IntegerField()
self.assertEqual(list(ModelForm().fields), ["name"])
self.assertEqual(list(type("NewForm", (Mixin, Form), {})().fields), [])
self.assertEqual(
list(type("NewForm", (Form2, Mixin, Form), {})().fields), ["foo"]
)
self.assertEqual(
list(type("NewForm", (Mixin, ModelForm, Form), {})().fields), ["name"]
)
self.assertEqual(
list(type("NewForm", (ModelForm, Mixin, Form), {})().fields), ["name"]
)
self.assertEqual(
list(type("NewForm", (ModelForm, Form, Mixin), {})().fields),
["name", "age"],
)
self.assertEqual(
list(type("NewForm", (ModelForm, Form), {"age": None})().fields), ["name"]
)
def test_field_removal_name_clashes(self):
"""
Form fields can be removed in subclasses by setting them to None
(#22510).
"""
class MyForm(forms.ModelForm):
media = forms.CharField()
class Meta:
model = Writer
fields = "__all__"
class SubForm(MyForm):
media = None
self.assertIn("media", MyForm().fields)
self.assertNotIn("media", SubForm().fields)
self.assertTrue(hasattr(MyForm, "media"))
self.assertTrue(hasattr(SubForm, "media"))
class StumpJokeForm(forms.ModelForm):
class Meta:
model = StumpJoke
fields = "__all__"
class CustomFieldWithQuerysetButNoLimitChoicesTo(forms.Field):
queryset = 42
class StumpJokeWithCustomFieldForm(forms.ModelForm):
custom = CustomFieldWithQuerysetButNoLimitChoicesTo()
class Meta:
model = StumpJoke
fields = ()
class LimitChoicesToTests(TestCase):
"""
Tests the functionality of ``limit_choices_to``.
"""
@classmethod
def setUpTestData(cls):
cls.threepwood = Character.objects.create(
username="threepwood",
last_action=datetime.datetime.today() + datetime.timedelta(days=1),
)
cls.marley = Character.objects.create(
username="marley",
last_action=datetime.datetime.today() - datetime.timedelta(days=1),
)
def test_limit_choices_to_callable_for_fk_rel(self):
"""
A ForeignKey can use limit_choices_to as a callable (#2554).
"""
stumpjokeform = StumpJokeForm()
self.assertSequenceEqual(
stumpjokeform.fields["most_recently_fooled"].queryset, [self.threepwood]
)
def test_limit_choices_to_callable_for_m2m_rel(self):
"""
A ManyToManyField can use limit_choices_to as a callable (#2554).
"""
stumpjokeform = StumpJokeForm()
self.assertSequenceEqual(
stumpjokeform.fields["most_recently_fooled"].queryset, [self.threepwood]
)
def test_custom_field_with_queryset_but_no_limit_choices_to(self):
"""
A custom field with a `queryset` attribute but no `limit_choices_to`
works (#23795).
"""
f = StumpJokeWithCustomFieldForm()
self.assertEqual(f.fields["custom"].queryset, 42)
def test_fields_for_model_applies_limit_choices_to(self):
fields = fields_for_model(StumpJoke, ["has_fooled_today"])
self.assertSequenceEqual(fields["has_fooled_today"].queryset, [self.threepwood])
def test_callable_called_each_time_form_is_instantiated(self):
field = StumpJokeForm.base_fields["most_recently_fooled"]
with mock.patch.object(field, "limit_choices_to") as today_callable_dict:
StumpJokeForm()
self.assertEqual(today_callable_dict.call_count, 1)
StumpJokeForm()
self.assertEqual(today_callable_dict.call_count, 2)
StumpJokeForm()
self.assertEqual(today_callable_dict.call_count, 3)
@isolate_apps("model_forms")
def test_limit_choices_to_no_duplicates(self):
joke1 = StumpJoke.objects.create(
funny=True,
most_recently_fooled=self.threepwood,
)
joke2 = StumpJoke.objects.create(
funny=True,
most_recently_fooled=self.threepwood,
)
joke3 = StumpJoke.objects.create(
funny=True,
most_recently_fooled=self.marley,
)
StumpJoke.objects.create(funny=False, most_recently_fooled=self.marley)
joke1.has_fooled_today.add(self.marley, self.threepwood)
joke2.has_fooled_today.add(self.marley)
joke3.has_fooled_today.add(self.marley, self.threepwood)
class CharacterDetails(models.Model):
character1 = models.ForeignKey(
Character,
models.CASCADE,
limit_choices_to=models.Q(
jokes__funny=True,
jokes_today__funny=True,
),
related_name="details_fk_1",
)
character2 = models.ForeignKey(
Character,
models.CASCADE,
limit_choices_to={
"jokes__funny": True,
"jokes_today__funny": True,
},
related_name="details_fk_2",
)
character3 = models.ManyToManyField(
Character,
limit_choices_to=models.Q(
jokes__funny=True,
jokes_today__funny=True,
),
related_name="details_m2m_1",
)
class CharacterDetailsForm(forms.ModelForm):
class Meta:
model = CharacterDetails
fields = "__all__"
form = CharacterDetailsForm()
self.assertCountEqual(
form.fields["character1"].queryset,
[self.marley, self.threepwood],
)
self.assertCountEqual(
form.fields["character2"].queryset,
[self.marley, self.threepwood],
)
self.assertCountEqual(
form.fields["character3"].queryset,
[self.marley, self.threepwood],
)
def test_limit_choices_to_m2m_through(self):
class DiceForm(forms.ModelForm):
class Meta:
model = Dice
fields = ["numbers"]
Number.objects.create(value=0)
n1 = Number.objects.create(value=1)
n2 = Number.objects.create(value=2)
form = DiceForm()
self.assertCountEqual(form.fields["numbers"].queryset, [n1, n2])
class FormFieldCallbackTests(SimpleTestCase):
def test_baseform_with_widgets_in_meta(self):
"""
Using base forms with widgets defined in Meta should not raise errors.
"""
widget = forms.Textarea()
class BaseForm(forms.ModelForm):
class Meta:
model = Person
widgets = {"name": widget}
fields = "__all__"
Form = modelform_factory(Person, form=BaseForm)
self.assertIsInstance(Form.base_fields["name"].widget, forms.Textarea)
def test_factory_with_widget_argument(self):
"""Regression for #15315: modelform_factory should accept widgets
argument
"""
widget = forms.Textarea()
# Without a widget should not set the widget to textarea
Form = modelform_factory(Person, fields="__all__")
self.assertNotEqual(Form.base_fields["name"].widget.__class__, forms.Textarea)
# With a widget should not set the widget to textarea
Form = modelform_factory(Person, fields="__all__", widgets={"name": widget})
self.assertEqual(Form.base_fields["name"].widget.__class__, forms.Textarea)
def test_modelform_factory_without_fields(self):
"""Regression for #19733"""
message = (
"Calling modelform_factory without defining 'fields' or 'exclude' "
"explicitly is prohibited."
)
with self.assertRaisesMessage(ImproperlyConfigured, message):
modelform_factory(Person)
def test_modelform_factory_with_all_fields(self):
"""Regression for #19733"""
form = modelform_factory(Person, fields="__all__")
self.assertEqual(list(form.base_fields), ["name"])
def test_custom_callback(self):
"""A custom formfield_callback is used if provided"""
callback_args = []
def callback(db_field, **kwargs):
callback_args.append((db_field, kwargs))
return db_field.formfield(**kwargs)
widget = forms.Textarea()
class BaseForm(forms.ModelForm):
class Meta:
model = Person
widgets = {"name": widget}
fields = "__all__"
modelform_factory(Person, form=BaseForm, formfield_callback=callback)
id_field, name_field = Person._meta.fields
self.assertEqual(
callback_args, [(id_field, {}), (name_field, {"widget": widget})]
)
def test_bad_callback(self):
# A bad callback provided by user still gives an error
with self.assertRaises(TypeError):
modelform_factory(
Person,
fields="__all__",
formfield_callback="not a function or callable",
)
def test_inherit_after_custom_callback(self):
def callback(db_field, **kwargs):
if isinstance(db_field, models.CharField):
return forms.CharField(widget=forms.Textarea)
return db_field.formfield(**kwargs)
class BaseForm(forms.ModelForm):
class Meta:
model = Person
fields = "__all__"
NewForm = modelform_factory(Person, form=BaseForm, formfield_callback=callback)
class InheritedForm(NewForm):
pass
for name in NewForm.base_fields:
self.assertEqual(
type(InheritedForm.base_fields[name].widget),
type(NewForm.base_fields[name].widget),
)
def test_custom_callback_in_meta(self):
def callback(db_field, **kwargs):
return forms.CharField(widget=forms.Textarea)
class NewForm(forms.ModelForm):
class Meta:
model = Person
fields = ["id", "name"]
formfield_callback = callback
for field in NewForm.base_fields.values():
self.assertEqual(type(field.widget), forms.Textarea)
def test_custom_callback_from_base_form_meta(self):
def callback(db_field, **kwargs):
return forms.CharField(widget=forms.Textarea)
class BaseForm(forms.ModelForm):
class Meta:
model = Person
fields = "__all__"
formfield_callback = callback
NewForm = modelform_factory(model=Person, form=BaseForm)
class InheritedForm(NewForm):
pass
for name, field in NewForm.base_fields.items():
self.assertEqual(type(field.widget), forms.Textarea)
self.assertEqual(
type(field.widget),
type(InheritedForm.base_fields[name].widget),
)
class LocalizedModelFormTest(TestCase):
def test_model_form_applies_localize_to_some_fields(self):
class PartiallyLocalizedTripleForm(forms.ModelForm):
class Meta:
model = Triple
localized_fields = (
"left",
"right",
)
fields = "__all__"
f = PartiallyLocalizedTripleForm({"left": 10, "middle": 10, "right": 10})
self.assertTrue(f.is_valid())
self.assertTrue(f.fields["left"].localize)
self.assertFalse(f.fields["middle"].localize)
self.assertTrue(f.fields["right"].localize)
def test_model_form_applies_localize_to_all_fields(self):
class FullyLocalizedTripleForm(forms.ModelForm):
class Meta:
model = Triple
localized_fields = "__all__"
fields = "__all__"
f = FullyLocalizedTripleForm({"left": 10, "middle": 10, "right": 10})
self.assertTrue(f.is_valid())
self.assertTrue(f.fields["left"].localize)
self.assertTrue(f.fields["middle"].localize)
self.assertTrue(f.fields["right"].localize)
def test_model_form_refuses_arbitrary_string(self):
msg = (
"BrokenLocalizedTripleForm.Meta.localized_fields "
"cannot be a string. Did you mean to type: ('foo',)?"
)
with self.assertRaisesMessage(TypeError, msg):
class BrokenLocalizedTripleForm(forms.ModelForm):
class Meta:
model = Triple
localized_fields = "foo"
class CustomMetaclass(ModelFormMetaclass):
def __new__(cls, name, bases, attrs):
new = super().__new__(cls, name, bases, attrs)
new.base_fields = {}
return new
class CustomMetaclassForm(forms.ModelForm, metaclass=CustomMetaclass):
pass
class CustomMetaclassTestCase(SimpleTestCase):
def test_modelform_factory_metaclass(self):
new_cls = modelform_factory(Person, fields="__all__", form=CustomMetaclassForm)
self.assertEqual(new_cls.base_fields, {})
class StrictAssignmentTests(SimpleTestCase):
"""
Should a model do anything special with __setattr__() or descriptors which
raise a ValidationError, a model form should catch the error (#24706).
"""
def test_setattr_raises_validation_error_field_specific(self):
"""
A model ValidationError using the dict form should put the error
message into the correct key of form.errors.
"""
form_class = modelform_factory(
model=StrictAssignmentFieldSpecific, fields=["title"]
)
form = form_class(data={"title": "testing setattr"}, files=None)
# This line turns on the ValidationError; it avoids the model erroring
# when its own __init__() is called when creating form.instance.
form.instance._should_error = True
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{"title": ["Cannot set attribute", "This field cannot be blank."]},
)
def test_setattr_raises_validation_error_non_field(self):
"""
A model ValidationError not using the dict form should put the error
message into __all__ (i.e. non-field errors) on the form.
"""
form_class = modelform_factory(model=StrictAssignmentAll, fields=["title"])
form = form_class(data={"title": "testing setattr"}, files=None)
# This line turns on the ValidationError; it avoids the model erroring
# when its own __init__() is called when creating form.instance.
form.instance._should_error = True
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{
"__all__": ["Cannot set attribute"],
"title": ["This field cannot be blank."],
},
)
class ModelToDictTests(TestCase):
def test_many_to_many(self):
"""Data for a ManyToManyField is a list rather than a lazy QuerySet."""
blue = Colour.objects.create(name="blue")
red = Colour.objects.create(name="red")
item = ColourfulItem.objects.create()
item.colours.set([blue])
data = model_to_dict(item)["colours"]
self.assertEqual(data, [blue])
item.colours.set([red])
# If data were a QuerySet, it would be reevaluated here and give "red"
# instead of the original value.
self.assertEqual(data, [blue])
|
1ec0c6c6591d26804f6cd8415cb0c2852cd56f650e3886556f2a398c897fa3ab | """
Distance and Area objects to allow for sensible and convenient calculation
and conversions. Here are some tests.
"""
import unittest
from django.contrib.gis.measure import A, Area, D, Distance
class DistanceTest(unittest.TestCase):
"Testing the Distance object"
def test_init(self):
"Testing initialization from valid units"
d = Distance(m=100)
self.assertEqual(d.m, 100)
d1, d2, d3 = D(m=100), D(meter=100), D(metre=100)
for d in (d1, d2, d3):
self.assertEqual(d.m, 100)
d = D(nm=100)
self.assertEqual(d.m, 185200)
y1, y2, y3 = D(yd=100), D(yard=100), D(Yard=100)
for d in (y1, y2, y3):
self.assertEqual(d.yd, 100)
mm1, mm2 = D(millimeter=1000), D(MiLLiMeTeR=1000)
for d in (mm1, mm2):
self.assertEqual(d.m, 1.0)
self.assertEqual(d.mm, 1000.0)
def test_init_invalid(self):
"Testing initialization from invalid units"
with self.assertRaises(AttributeError):
D(banana=100)
def test_access(self):
"Testing access in different units"
d = D(m=100)
self.assertEqual(d.km, 0.1)
self.assertAlmostEqual(d.ft, 328.084, 3)
def test_access_invalid(self):
"Testing access in invalid units"
d = D(m=100)
self.assertFalse(hasattr(d, "banana"))
def test_addition(self):
"Test addition & subtraction"
d1 = D(m=100)
d2 = D(m=200)
d3 = d1 + d2
self.assertEqual(d3.m, 300)
d3 += d1
self.assertEqual(d3.m, 400)
d4 = d1 - d2
self.assertEqual(d4.m, -100)
d4 -= d1
self.assertEqual(d4.m, -200)
with self.assertRaises(TypeError):
d1 + 1
with self.assertRaises(TypeError):
d1 - 1
with self.assertRaises(TypeError):
d1 += 1
with self.assertRaises(TypeError):
d1 -= 1
def test_multiplication(self):
"Test multiplication & division"
d1 = D(m=100)
d3 = d1 * 2
self.assertEqual(d3.m, 200)
d3 = 2 * d1
self.assertEqual(d3.m, 200)
d3 *= 5
self.assertEqual(d3.m, 1000)
d4 = d1 / 2
self.assertEqual(d4.m, 50)
d4 /= 5
self.assertEqual(d4.m, 10)
d5 = d1 / D(m=2)
self.assertEqual(d5, 50)
a5 = d1 * D(m=10)
self.assertIsInstance(a5, Area)
self.assertEqual(a5.sq_m, 100 * 10)
with self.assertRaises(TypeError):
d1 *= D(m=1)
with self.assertRaises(TypeError):
d1 /= D(m=1)
def test_unit_conversions(self):
"Testing default units during maths"
d1 = D(m=100)
d2 = D(km=1)
d3 = d1 + d2
self.assertEqual(d3._default_unit, "m")
d4 = d2 + d1
self.assertEqual(d4._default_unit, "km")
d5 = d1 * 2
self.assertEqual(d5._default_unit, "m")
d6 = d1 / 2
self.assertEqual(d6._default_unit, "m")
def test_comparisons(self):
"Testing comparisons"
d1 = D(m=100)
d2 = D(km=1)
d3 = D(km=0)
self.assertGreater(d2, d1)
self.assertEqual(d1, d1)
self.assertLess(d1, d2)
self.assertFalse(d3)
def test_units_str(self):
"Testing conversion to strings"
d1 = D(m=100)
d2 = D(km=3.5)
self.assertEqual(str(d1), "100.0 m")
self.assertEqual(str(d2), "3.5 km")
self.assertEqual(repr(d1), "Distance(m=100.0)")
self.assertEqual(repr(d2), "Distance(km=3.5)")
def test_furlong(self):
d = D(m=201.168)
self.assertEqual(d.furlong, 1)
def test_unit_att_name(self):
"Testing the `unit_attname` class method"
unit_tuple = [
("Yard", "yd"),
("Nautical Mile", "nm"),
("German legal metre", "german_m"),
("Indian yard", "indian_yd"),
("Chain (Sears)", "chain_sears"),
("Chain", "chain"),
("Furrow Long", "furlong"),
]
for nm, att in unit_tuple:
with self.subTest(nm=nm):
self.assertEqual(att, D.unit_attname(nm))
def test_hash(self):
d1 = D(m=99)
d2 = D(m=100)
d3 = D(km=0.1)
self.assertEqual(hash(d2), hash(d3))
self.assertNotEqual(hash(d1), hash(d2))
self.assertNotEqual(hash(d1), hash(d3))
class AreaTest(unittest.TestCase):
"Testing the Area object"
def test_init(self):
"Testing initialization from valid units"
a = Area(sq_m=100)
self.assertEqual(a.sq_m, 100)
a = A(sq_m=100)
self.assertEqual(a.sq_m, 100)
a = A(sq_mi=100)
self.assertEqual(a.sq_m, 258998811.0336)
def test_init_invalid_a(self):
"Testing initialization from invalid units"
with self.assertRaises(AttributeError):
A(banana=100)
def test_access(self):
"Testing access in different units"
a = A(sq_m=100)
self.assertEqual(a.sq_km, 0.0001)
self.assertAlmostEqual(a.sq_ft, 1076.391, 3)
def test_access_invalid_a(self):
"Testing access in invalid units"
a = A(sq_m=100)
self.assertFalse(hasattr(a, "banana"))
def test_addition(self):
"Test addition & subtraction"
a1 = A(sq_m=100)
a2 = A(sq_m=200)
a3 = a1 + a2
self.assertEqual(a3.sq_m, 300)
a3 += a1
self.assertEqual(a3.sq_m, 400)
a4 = a1 - a2
self.assertEqual(a4.sq_m, -100)
a4 -= a1
self.assertEqual(a4.sq_m, -200)
with self.assertRaises(TypeError):
a1 + 1
with self.assertRaises(TypeError):
a1 - 1
with self.assertRaises(TypeError):
a1 += 1
with self.assertRaises(TypeError):
a1 -= 1
def test_multiplication(self):
"Test multiplication & division"
a1 = A(sq_m=100)
a3 = a1 * 2
self.assertEqual(a3.sq_m, 200)
a3 = 2 * a1
self.assertEqual(a3.sq_m, 200)
a3 *= 5
self.assertEqual(a3.sq_m, 1000)
a4 = a1 / 2
self.assertEqual(a4.sq_m, 50)
a4 /= 5
self.assertEqual(a4.sq_m, 10)
with self.assertRaises(TypeError):
a1 * A(sq_m=1)
with self.assertRaises(TypeError):
a1 *= A(sq_m=1)
with self.assertRaises(TypeError):
a1 / A(sq_m=1)
with self.assertRaises(TypeError):
a1 /= A(sq_m=1)
def test_unit_conversions(self):
"Testing default units during maths"
a1 = A(sq_m=100)
a2 = A(sq_km=1)
a3 = a1 + a2
self.assertEqual(a3._default_unit, "sq_m")
a4 = a2 + a1
self.assertEqual(a4._default_unit, "sq_km")
a5 = a1 * 2
self.assertEqual(a5._default_unit, "sq_m")
a6 = a1 / 2
self.assertEqual(a6._default_unit, "sq_m")
def test_comparisons(self):
"Testing comparisons"
a1 = A(sq_m=100)
a2 = A(sq_km=1)
a3 = A(sq_km=0)
self.assertGreater(a2, a1)
self.assertEqual(a1, a1)
self.assertLess(a1, a2)
self.assertFalse(a3)
def test_units_str(self):
"Testing conversion to strings"
a1 = A(sq_m=100)
a2 = A(sq_km=3.5)
self.assertEqual(str(a1), "100.0 sq_m")
self.assertEqual(str(a2), "3.5 sq_km")
self.assertEqual(repr(a1), "Area(sq_m=100.0)")
self.assertEqual(repr(a2), "Area(sq_km=3.5)")
def test_hash(self):
a1 = A(sq_m=100)
a2 = A(sq_m=1000000)
a3 = A(sq_km=1)
self.assertEqual(hash(a2), hash(a3))
self.assertNotEqual(hash(a1), hash(a2))
self.assertNotEqual(hash(a1), hash(a3))
|
d8773bcfba3a754db1c5e760d5f0f37560188b3f3b1f3f076dfbe108556858d6 | import re
from django.contrib.gis import forms
from django.contrib.gis.forms import BaseGeometryWidget, OpenLayersWidget
from django.contrib.gis.geos import GEOSGeometry
from django.core.exceptions import ValidationError
from django.test import SimpleTestCase, override_settings
from django.utils.deprecation import RemovedInDjango51Warning
from django.utils.html import escape
class GeometryFieldTest(SimpleTestCase):
def test_init(self):
"Testing GeometryField initialization with defaults."
fld = forms.GeometryField()
for bad_default in ("blah", 3, "FoO", None, 0):
with self.subTest(bad_default=bad_default):
with self.assertRaises(ValidationError):
fld.clean(bad_default)
def test_srid(self):
"Testing GeometryField with a SRID set."
# Input that doesn't specify the SRID is assumed to be in the SRID
# of the input field.
fld = forms.GeometryField(srid=4326)
geom = fld.clean("POINT(5 23)")
self.assertEqual(4326, geom.srid)
# Making the field in a different SRID from that of the geometry, and
# asserting it transforms.
fld = forms.GeometryField(srid=32140)
# Different PROJ versions use different transformations, all are
# correct as having a 1 meter accuracy.
tol = 1
xform_geom = GEOSGeometry(
"POINT (951640.547328465 4219369.26171664)", srid=32140
)
# The cleaned geometry is transformed to 32140 (the widget map_srid is 3857).
cleaned_geom = fld.clean(
"SRID=3857;POINT (-10615777.40976205 3473169.895707852)"
)
self.assertEqual(cleaned_geom.srid, 32140)
self.assertTrue(xform_geom.equals_exact(cleaned_geom, tol))
def test_null(self):
"Testing GeometryField's handling of null (None) geometries."
# Form fields, by default, are required (`required=True`)
fld = forms.GeometryField()
with self.assertRaisesMessage(ValidationError, "No geometry value provided."):
fld.clean(None)
# This will clean None as a geometry (See #10660).
fld = forms.GeometryField(required=False)
self.assertIsNone(fld.clean(None))
def test_geom_type(self):
"Testing GeometryField's handling of different geometry types."
# By default, all geometry types are allowed.
fld = forms.GeometryField()
for wkt in (
"POINT(5 23)",
"MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))",
"LINESTRING(0 0, 1 1)",
):
with self.subTest(wkt=wkt):
# to_python() uses the SRID of OpenLayersWidget if the
# converted value doesn't have an SRID.
self.assertEqual(
GEOSGeometry(wkt, srid=fld.widget.map_srid), fld.clean(wkt)
)
pnt_fld = forms.GeometryField(geom_type="POINT")
self.assertEqual(
GEOSGeometry("POINT(5 23)", srid=pnt_fld.widget.map_srid),
pnt_fld.clean("POINT(5 23)"),
)
# a WKT for any other geom_type will be properly transformed by `to_python`
self.assertEqual(
GEOSGeometry("LINESTRING(0 0, 1 1)", srid=pnt_fld.widget.map_srid),
pnt_fld.to_python("LINESTRING(0 0, 1 1)"),
)
# but rejected by `clean`
with self.assertRaises(ValidationError):
pnt_fld.clean("LINESTRING(0 0, 1 1)")
def test_to_python(self):
"""
to_python() either returns a correct GEOSGeometry object or
a ValidationError.
"""
good_inputs = [
"POINT(5 23)",
"MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))",
"LINESTRING(0 0, 1 1)",
]
bad_inputs = [
"POINT(5)",
"MULTI POLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))",
"BLAH(0 0, 1 1)",
'{"type": "FeatureCollection", "features": ['
'{"geometry": {"type": "Point", "coordinates": [508375, 148905]}, '
'"type": "Feature"}]}',
]
fld = forms.GeometryField()
# to_python returns the same GEOSGeometry for a WKT
for geo_input in good_inputs:
with self.subTest(geo_input=geo_input):
self.assertEqual(
GEOSGeometry(geo_input, srid=fld.widget.map_srid),
fld.to_python(geo_input),
)
# but raises a ValidationError for any other string
for geo_input in bad_inputs:
with self.subTest(geo_input=geo_input):
with self.assertRaises(ValidationError):
fld.to_python(geo_input)
def test_to_python_different_map_srid(self):
f = forms.GeometryField(widget=OpenLayersWidget)
json = '{ "type": "Point", "coordinates": [ 5.0, 23.0 ] }'
self.assertEqual(
GEOSGeometry("POINT(5 23)", srid=f.widget.map_srid), f.to_python(json)
)
def test_field_with_text_widget(self):
class PointForm(forms.Form):
pt = forms.PointField(srid=4326, widget=forms.TextInput)
form = PointForm()
cleaned_pt = form.fields["pt"].clean("POINT(5 23)")
self.assertEqual(cleaned_pt, GEOSGeometry("POINT(5 23)", srid=4326))
self.assertEqual(4326, cleaned_pt.srid)
with self.assertRaisesMessage(ValidationError, "Invalid geometry value."):
form.fields["pt"].clean("POINT(5)")
point = GEOSGeometry("SRID=4326;POINT(5 23)")
form = PointForm(data={"pt": "POINT(5 23)"}, initial={"pt": point})
self.assertFalse(form.has_changed())
def test_field_string_value(self):
"""
Initialization of a geometry field with a valid/empty/invalid string.
Only the invalid string should trigger an error log entry.
"""
class PointForm(forms.Form):
pt1 = forms.PointField(srid=4326)
pt2 = forms.PointField(srid=4326)
pt3 = forms.PointField(srid=4326)
form = PointForm(
{
"pt1": "SRID=4326;POINT(7.3 44)", # valid
"pt2": "", # empty
"pt3": "PNT(0)", # invalid
}
)
with self.assertLogs("django.contrib.gis", "ERROR") as logger_calls:
output = str(form)
# The first point can't use assertInHTML() due to non-deterministic
# ordering of the rendered dictionary.
pt1_serialized = re.search(r"<textarea [^>]*>({[^<]+})<", output)[1]
pt1_json = pt1_serialized.replace(""", '"')
pt1_expected = GEOSGeometry(form.data["pt1"]).transform(3857, clone=True)
self.assertJSONEqual(pt1_json, pt1_expected.json)
self.assertInHTML(
'<textarea id="id_pt2" class="vSerializedField required" cols="150"'
' rows="10" name="pt2" hidden></textarea>',
output,
)
self.assertInHTML(
'<textarea id="id_pt3" class="vSerializedField required" cols="150"'
' rows="10" name="pt3" hidden></textarea>',
output,
)
# Only the invalid PNT(0) triggers an error log entry.
# Deserialization is called in form clean and in widget rendering.
self.assertEqual(len(logger_calls.records), 2)
self.assertEqual(
logger_calls.records[0].getMessage(),
"Error creating geometry from value 'PNT(0)' (String input "
"unrecognized as WKT EWKT, and HEXEWKB.)",
)
class SpecializedFieldTest(SimpleTestCase):
def setUp(self):
self.geometries = {
"point": GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)"),
"multipoint": GEOSGeometry(
"SRID=4326;MULTIPOINT("
"(13.18634033203125 14.504356384277344),"
"(13.207969665527 14.490966796875),"
"(13.177070617675 14.454917907714))"
),
"linestring": GEOSGeometry(
"SRID=4326;LINESTRING("
"-8.26171875 -0.52734375,"
"-7.734375 4.21875,"
"6.85546875 3.779296875,"
"5.44921875 -3.515625)"
),
"multilinestring": GEOSGeometry(
"SRID=4326;MULTILINESTRING("
"(-16.435546875 -2.98828125,"
"-17.2265625 2.98828125,"
"-0.703125 3.515625,"
"-1.494140625 -3.33984375),"
"(-8.0859375 -5.9765625,"
"8.525390625 -8.7890625,"
"12.392578125 -0.87890625,"
"10.01953125 7.646484375))"
),
"polygon": GEOSGeometry(
"SRID=4326;POLYGON("
"(-1.669921875 6.240234375,"
"-3.8671875 -0.615234375,"
"5.9765625 -3.955078125,"
"18.193359375 3.955078125,"
"9.84375 9.4921875,"
"-1.669921875 6.240234375))"
),
"multipolygon": GEOSGeometry(
"SRID=4326;MULTIPOLYGON("
"((-17.578125 13.095703125,"
"-17.2265625 10.8984375,"
"-13.974609375 10.1953125,"
"-13.359375 12.744140625,"
"-15.732421875 13.7109375,"
"-17.578125 13.095703125)),"
"((-8.525390625 5.537109375,"
"-8.876953125 2.548828125,"
"-5.888671875 1.93359375,"
"-5.09765625 4.21875,"
"-6.064453125 6.240234375,"
"-8.525390625 5.537109375)))"
),
"geometrycollection": GEOSGeometry(
"SRID=4326;GEOMETRYCOLLECTION("
"POINT(5.625 -0.263671875),"
"POINT(6.767578125 -3.603515625),"
"POINT(8.525390625 0.087890625),"
"POINT(8.0859375 -2.13134765625),"
"LINESTRING("
"6.273193359375 -1.175537109375,"
"5.77880859375 -1.812744140625,"
"7.27294921875 -2.230224609375,"
"7.657470703125 -1.25244140625))"
),
}
def assertMapWidget(self, form_instance):
"""
Make sure the MapWidget js is passed in the form media and a MapWidget
is actually created
"""
self.assertTrue(form_instance.is_valid())
rendered = form_instance.as_p()
self.assertIn("new MapWidget(options);", rendered)
self.assertIn("map_srid: 3857,", rendered)
self.assertIn("gis/js/OLMapWidget.js", str(form_instance.media))
def assertTextarea(self, geom, rendered):
"""Makes sure the wkt and a textarea are in the content"""
self.assertIn("<textarea ", rendered)
self.assertIn("required", rendered)
ogr = geom.ogr
ogr.transform(3857)
self.assertIn(escape(ogr.json), rendered)
# map_srid in openlayers.html template must not be localized.
@override_settings(USE_THOUSAND_SEPARATOR=True)
def test_pointfield(self):
class PointForm(forms.Form):
p = forms.PointField()
geom = self.geometries["point"]
form = PointForm(data={"p": geom})
self.assertTextarea(geom, form.as_p())
self.assertMapWidget(form)
self.assertFalse(PointForm().is_valid())
invalid = PointForm(data={"p": "some invalid geom"})
self.assertFalse(invalid.is_valid())
self.assertIn("Invalid geometry value", str(invalid.errors))
for invalid in [geo for key, geo in self.geometries.items() if key != "point"]:
self.assertFalse(PointForm(data={"p": invalid.wkt}).is_valid())
def test_multipointfield(self):
class PointForm(forms.Form):
p = forms.MultiPointField()
geom = self.geometries["multipoint"]
form = PointForm(data={"p": geom})
self.assertTextarea(geom, form.as_p())
self.assertMapWidget(form)
self.assertFalse(PointForm().is_valid())
for invalid in [
geo for key, geo in self.geometries.items() if key != "multipoint"
]:
self.assertFalse(PointForm(data={"p": invalid.wkt}).is_valid())
def test_linestringfield(self):
class LineStringForm(forms.Form):
f = forms.LineStringField()
geom = self.geometries["linestring"]
form = LineStringForm(data={"f": geom})
self.assertTextarea(geom, form.as_p())
self.assertMapWidget(form)
self.assertFalse(LineStringForm().is_valid())
for invalid in [
geo for key, geo in self.geometries.items() if key != "linestring"
]:
self.assertFalse(LineStringForm(data={"p": invalid.wkt}).is_valid())
def test_multilinestringfield(self):
class LineStringForm(forms.Form):
f = forms.MultiLineStringField()
geom = self.geometries["multilinestring"]
form = LineStringForm(data={"f": geom})
self.assertTextarea(geom, form.as_p())
self.assertMapWidget(form)
self.assertFalse(LineStringForm().is_valid())
for invalid in [
geo for key, geo in self.geometries.items() if key != "multilinestring"
]:
self.assertFalse(LineStringForm(data={"p": invalid.wkt}).is_valid())
def test_polygonfield(self):
class PolygonForm(forms.Form):
p = forms.PolygonField()
geom = self.geometries["polygon"]
form = PolygonForm(data={"p": geom})
self.assertTextarea(geom, form.as_p())
self.assertMapWidget(form)
self.assertFalse(PolygonForm().is_valid())
for invalid in [
geo for key, geo in self.geometries.items() if key != "polygon"
]:
self.assertFalse(PolygonForm(data={"p": invalid.wkt}).is_valid())
def test_multipolygonfield(self):
class PolygonForm(forms.Form):
p = forms.MultiPolygonField()
geom = self.geometries["multipolygon"]
form = PolygonForm(data={"p": geom})
self.assertTextarea(geom, form.as_p())
self.assertMapWidget(form)
self.assertFalse(PolygonForm().is_valid())
for invalid in [
geo for key, geo in self.geometries.items() if key != "multipolygon"
]:
self.assertFalse(PolygonForm(data={"p": invalid.wkt}).is_valid())
def test_geometrycollectionfield(self):
class GeometryForm(forms.Form):
g = forms.GeometryCollectionField()
geom = self.geometries["geometrycollection"]
form = GeometryForm(data={"g": geom})
self.assertTextarea(geom, form.as_p())
self.assertMapWidget(form)
self.assertFalse(GeometryForm().is_valid())
for invalid in [
geo for key, geo in self.geometries.items() if key != "geometrycollection"
]:
self.assertFalse(GeometryForm(data={"g": invalid.wkt}).is_valid())
class OSMWidgetTest(SimpleTestCase):
def setUp(self):
self.geometries = {
"point": GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)"),
}
def test_osm_widget(self):
class PointForm(forms.Form):
p = forms.PointField(widget=forms.OSMWidget)
geom = self.geometries["point"]
form = PointForm(data={"p": geom})
rendered = form.as_p()
self.assertIn("ol.source.OSM()", rendered)
self.assertIn("id: 'id_p',", rendered)
def test_default_lat_lon(self):
self.assertEqual(forms.OSMWidget.default_lon, 5)
self.assertEqual(forms.OSMWidget.default_lat, 47)
self.assertEqual(forms.OSMWidget.default_zoom, 12)
class PointForm(forms.Form):
p = forms.PointField(
widget=forms.OSMWidget(
attrs={
"default_lon": 20,
"default_lat": 30,
"default_zoom": 17,
}
),
)
form = PointForm()
rendered = form.as_p()
self.assertIn("options['default_lon'] = 20;", rendered)
self.assertIn("options['default_lat'] = 30;", rendered)
self.assertIn("options['default_zoom'] = 17;", rendered)
class GeometryWidgetTests(SimpleTestCase):
def test_get_context_attrs(self):
# The Widget.get_context() attrs argument overrides self.attrs.
widget = BaseGeometryWidget(attrs={"geom_type": "POINT"})
context = widget.get_context("point", None, attrs={"geom_type": "POINT2"})
self.assertEqual(context["geom_type"], "POINT2")
# Widget.get_context() returns expected name for geom_type.
widget = BaseGeometryWidget(attrs={"geom_type": "POLYGON"})
context = widget.get_context("polygon", None, None)
self.assertEqual(context["geom_type"], "Polygon")
# Widget.get_context() returns 'Geometry' instead of 'Unknown'.
widget = BaseGeometryWidget(attrs={"geom_type": "GEOMETRY"})
context = widget.get_context("geometry", None, None)
self.assertEqual(context["geom_type"], "Geometry")
def test_subwidgets(self):
widget = forms.BaseGeometryWidget()
self.assertEqual(
list(widget.subwidgets("name", "value")),
[
{
"is_hidden": False,
"attrs": {
"map_srid": 4326,
"map_width": 600,
"geom_type": "GEOMETRY",
"map_height": 400,
"display_raw": False,
},
"name": "name",
"template_name": "",
"value": "value",
"required": False,
}
],
)
def test_custom_serialization_widget(self):
class CustomGeometryWidget(forms.BaseGeometryWidget):
template_name = "gis/openlayers.html"
deserialize_called = 0
def serialize(self, value):
return value.json if value else ""
def deserialize(self, value):
self.deserialize_called += 1
return GEOSGeometry(value)
class PointForm(forms.Form):
p = forms.PointField(widget=CustomGeometryWidget)
point = GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)")
form = PointForm(data={"p": point})
self.assertIn(escape(point.json), form.as_p())
CustomGeometryWidget.called = 0
widget = form.fields["p"].widget
# Force deserialize use due to a string value
self.assertIn(escape(point.json), widget.render("p", point.json))
self.assertEqual(widget.deserialize_called, 1)
form = PointForm(data={"p": point.json})
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data["p"].srid, 4326)
def test_deprecated_width_and_height(self):
class CustomGeometryWidget(forms.BaseGeometryWidget):
map_height = 300
map_width = 550
msg = (
"The map_height and map_width widget attributes are deprecated. Please use "
"CSS to size map widgets."
)
with self.assertRaisesMessage(RemovedInDjango51Warning, msg):
CustomGeometryWidget()
with self.assertRaisesMessage(RemovedInDjango51Warning, msg):
forms.BaseGeometryWidget({"map_width": 400})
with self.assertRaisesMessage(RemovedInDjango51Warning, msg):
forms.BaseGeometryWidget({"map_height": 600})
|
e76b559a0a0b3145512760c6448508ee90de0a9c2ed914f67b9f44ef2222b001 | import datetime
import unittest
try:
import pytz
except ImportError:
pytz = None
from django.test import TestCase, ignore_warnings, override_settings
from django.utils import timezone
from django.utils.deprecation import RemovedInDjango50Warning
from .models import Article, Category, Comment
class DateTimesTests(TestCase):
def test_related_model_traverse(self):
a1 = Article.objects.create(
title="First one",
pub_date=datetime.datetime(2005, 7, 28, 9, 0, 0),
)
a2 = Article.objects.create(
title="Another one",
pub_date=datetime.datetime(2010, 7, 28, 10, 0, 0),
)
a3 = Article.objects.create(
title="Third one, in the first day",
pub_date=datetime.datetime(2005, 7, 28, 17, 0, 0),
)
a1.comments.create(
text="Im the HULK!",
pub_date=datetime.datetime(2005, 7, 28, 9, 30, 0),
)
a1.comments.create(
text="HULK SMASH!",
pub_date=datetime.datetime(2005, 7, 29, 1, 30, 0),
)
a2.comments.create(
text="LMAO",
pub_date=datetime.datetime(2010, 7, 28, 10, 10, 10),
)
a3.comments.create(
text="+1",
pub_date=datetime.datetime(2005, 8, 29, 10, 10, 10),
)
c = Category.objects.create(name="serious-news")
c.articles.add(a1, a3)
self.assertSequenceEqual(
Comment.objects.datetimes("article__pub_date", "year"),
[
datetime.datetime(2005, 1, 1),
datetime.datetime(2010, 1, 1),
],
)
self.assertSequenceEqual(
Comment.objects.datetimes("article__pub_date", "month"),
[
datetime.datetime(2005, 7, 1),
datetime.datetime(2010, 7, 1),
],
)
self.assertSequenceEqual(
Comment.objects.datetimes("article__pub_date", "week"),
[
datetime.datetime(2005, 7, 25),
datetime.datetime(2010, 7, 26),
],
)
self.assertSequenceEqual(
Comment.objects.datetimes("article__pub_date", "day"),
[
datetime.datetime(2005, 7, 28),
datetime.datetime(2010, 7, 28),
],
)
self.assertSequenceEqual(
Article.objects.datetimes("comments__pub_date", "day"),
[
datetime.datetime(2005, 7, 28),
datetime.datetime(2005, 7, 29),
datetime.datetime(2005, 8, 29),
datetime.datetime(2010, 7, 28),
],
)
self.assertSequenceEqual(
Article.objects.datetimes("comments__approval_date", "day"), []
)
self.assertSequenceEqual(
Category.objects.datetimes("articles__pub_date", "day"),
[
datetime.datetime(2005, 7, 28),
],
)
@override_settings(USE_TZ=True)
def test_21432(self):
now = timezone.localtime(timezone.now().replace(microsecond=0))
Article.objects.create(title="First one", pub_date=now)
qs = Article.objects.datetimes("pub_date", "second")
self.assertEqual(qs[0], now)
@unittest.skipUnless(pytz is not None, "Test requires pytz")
@ignore_warnings(category=RemovedInDjango50Warning)
@override_settings(USE_TZ=True, TIME_ZONE="UTC", USE_DEPRECATED_PYTZ=True)
def test_datetimes_ambiguous_and_invalid_times(self):
sao = pytz.timezone("America/Sao_Paulo")
utc = pytz.UTC
article = Article.objects.create(
title="Article 1",
pub_date=utc.localize(datetime.datetime(2016, 2, 21, 1)),
)
Comment.objects.create(
article=article,
pub_date=utc.localize(datetime.datetime(2016, 10, 16, 13)),
)
with timezone.override(sao):
with self.assertRaisesMessage(
pytz.AmbiguousTimeError, "2016-02-20 23:00:00"
):
Article.objects.datetimes("pub_date", "hour").get()
with self.assertRaisesMessage(
pytz.NonExistentTimeError, "2016-10-16 00:00:00"
):
Comment.objects.datetimes("pub_date", "day").get()
self.assertEqual(
Article.objects.datetimes("pub_date", "hour", is_dst=False).get().dst(),
datetime.timedelta(0),
)
self.assertEqual(
Comment.objects.datetimes("pub_date", "day", is_dst=False).get().dst(),
datetime.timedelta(0),
)
self.assertEqual(
Article.objects.datetimes("pub_date", "hour", is_dst=True).get().dst(),
datetime.timedelta(0, 3600),
)
self.assertEqual(
Comment.objects.datetimes("pub_date", "hour", is_dst=True).get().dst(),
datetime.timedelta(0, 3600),
)
def test_datetimes_returns_available_dates_for_given_scope_and_given_field(self):
pub_dates = [
datetime.datetime(2005, 7, 28, 12, 15),
datetime.datetime(2005, 7, 29, 2, 15),
datetime.datetime(2005, 7, 30, 5, 15),
datetime.datetime(2005, 7, 31, 19, 15),
]
for i, pub_date in enumerate(pub_dates):
Article(pub_date=pub_date, title="title #{}".format(i)).save()
self.assertSequenceEqual(
Article.objects.datetimes("pub_date", "year"),
[datetime.datetime(2005, 1, 1, 0, 0)],
)
self.assertSequenceEqual(
Article.objects.datetimes("pub_date", "month"),
[datetime.datetime(2005, 7, 1, 0, 0)],
)
self.assertSequenceEqual(
Article.objects.datetimes("pub_date", "week"),
[datetime.datetime(2005, 7, 25, 0, 0)],
)
self.assertSequenceEqual(
Article.objects.datetimes("pub_date", "day"),
[
datetime.datetime(2005, 7, 28, 0, 0),
datetime.datetime(2005, 7, 29, 0, 0),
datetime.datetime(2005, 7, 30, 0, 0),
datetime.datetime(2005, 7, 31, 0, 0),
],
)
self.assertSequenceEqual(
Article.objects.datetimes("pub_date", "day", order="ASC"),
[
datetime.datetime(2005, 7, 28, 0, 0),
datetime.datetime(2005, 7, 29, 0, 0),
datetime.datetime(2005, 7, 30, 0, 0),
datetime.datetime(2005, 7, 31, 0, 0),
],
)
self.assertSequenceEqual(
Article.objects.datetimes("pub_date", "day", order="DESC"),
[
datetime.datetime(2005, 7, 31, 0, 0),
datetime.datetime(2005, 7, 30, 0, 0),
datetime.datetime(2005, 7, 29, 0, 0),
datetime.datetime(2005, 7, 28, 0, 0),
],
)
def test_datetimes_has_lazy_iterator(self):
pub_dates = [
datetime.datetime(2005, 7, 28, 12, 15),
datetime.datetime(2005, 7, 29, 2, 15),
datetime.datetime(2005, 7, 30, 5, 15),
datetime.datetime(2005, 7, 31, 19, 15),
]
for i, pub_date in enumerate(pub_dates):
Article(pub_date=pub_date, title="title #{}".format(i)).save()
# Use iterator() with datetimes() to return a generator that lazily
# requests each result one at a time, to save memory.
dates = []
with self.assertNumQueries(0):
article_datetimes_iterator = Article.objects.datetimes(
"pub_date", "day", order="DESC"
).iterator()
with self.assertNumQueries(1):
for article in article_datetimes_iterator:
dates.append(article)
self.assertEqual(
dates,
[
datetime.datetime(2005, 7, 31, 0, 0),
datetime.datetime(2005, 7, 30, 0, 0),
datetime.datetime(2005, 7, 29, 0, 0),
datetime.datetime(2005, 7, 28, 0, 0),
],
)
def test_datetimes_disallows_date_fields(self):
dt = datetime.datetime(2005, 7, 28, 12, 15)
Article.objects.create(
pub_date=dt,
published_on=dt.date(),
title="Don't put dates into datetime functions!",
)
with self.assertRaisesMessage(
ValueError, "Cannot truncate DateField 'published_on' to DateTimeField"
):
list(Article.objects.datetimes("published_on", "second"))
def test_datetimes_fails_when_given_invalid_kind_argument(self):
msg = (
"'kind' must be one of 'year', 'month', 'week', 'day', 'hour', "
"'minute', or 'second'."
)
with self.assertRaisesMessage(ValueError, msg):
Article.objects.datetimes("pub_date", "bad_kind")
def test_datetimes_fails_when_given_invalid_order_argument(self):
msg = "'order' must be either 'ASC' or 'DESC'."
with self.assertRaisesMessage(ValueError, msg):
Article.objects.datetimes("pub_date", "year", order="bad order")
|
677e5901c376ca2e2d102bd7e2e33c1c2dea2467592d3d9fd322dab38b281bbc | from math import ceil
from django.db import connection, models
from django.db.models import ProtectedError, RestrictedError
from django.db.models.deletion import Collector
from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from .models import (
B1,
B2,
B3,
MR,
A,
Avatar,
B,
Base,
Child,
DeleteBottom,
DeleteTop,
GenericB1,
GenericB2,
GenericDeleteBottom,
HiddenUser,
HiddenUserProfile,
M,
M2MFrom,
M2MTo,
MRNull,
Origin,
P,
Parent,
R,
RChild,
RChildChild,
Referrer,
S,
T,
User,
create_a,
get_default_r,
)
class OnDeleteTests(TestCase):
def setUp(self):
self.DEFAULT = get_default_r()
def test_auto(self):
a = create_a("auto")
a.auto.delete()
self.assertFalse(A.objects.filter(name="auto").exists())
def test_non_callable(self):
msg = "on_delete must be callable."
with self.assertRaisesMessage(TypeError, msg):
models.ForeignKey("self", on_delete=None)
with self.assertRaisesMessage(TypeError, msg):
models.OneToOneField("self", on_delete=None)
def test_auto_nullable(self):
a = create_a("auto_nullable")
a.auto_nullable.delete()
self.assertFalse(A.objects.filter(name="auto_nullable").exists())
def test_setvalue(self):
a = create_a("setvalue")
a.setvalue.delete()
a = A.objects.get(pk=a.pk)
self.assertEqual(self.DEFAULT, a.setvalue.pk)
def test_setnull(self):
a = create_a("setnull")
a.setnull.delete()
a = A.objects.get(pk=a.pk)
self.assertIsNone(a.setnull)
def test_setdefault(self):
a = create_a("setdefault")
a.setdefault.delete()
a = A.objects.get(pk=a.pk)
self.assertEqual(self.DEFAULT, a.setdefault.pk)
def test_setdefault_none(self):
a = create_a("setdefault_none")
a.setdefault_none.delete()
a = A.objects.get(pk=a.pk)
self.assertIsNone(a.setdefault_none)
def test_cascade(self):
a = create_a("cascade")
a.cascade.delete()
self.assertFalse(A.objects.filter(name="cascade").exists())
def test_cascade_nullable(self):
a = create_a("cascade_nullable")
a.cascade_nullable.delete()
self.assertFalse(A.objects.filter(name="cascade_nullable").exists())
def test_protect(self):
a = create_a("protect")
msg = (
"Cannot delete some instances of model 'R' because they are "
"referenced through protected foreign keys: 'A.protect'."
)
with self.assertRaisesMessage(ProtectedError, msg) as cm:
a.protect.delete()
self.assertEqual(cm.exception.protected_objects, {a})
def test_protect_multiple(self):
a = create_a("protect")
b = B.objects.create(protect=a.protect)
msg = (
"Cannot delete some instances of model 'R' because they are "
"referenced through protected foreign keys: 'A.protect', "
"'B.protect'."
)
with self.assertRaisesMessage(ProtectedError, msg) as cm:
a.protect.delete()
self.assertEqual(cm.exception.protected_objects, {a, b})
def test_protect_path(self):
a = create_a("protect")
a.protect.p = P.objects.create()
a.protect.save()
msg = (
"Cannot delete some instances of model 'P' because they are "
"referenced through protected foreign keys: 'R.p'."
)
with self.assertRaisesMessage(ProtectedError, msg) as cm:
a.protect.p.delete()
self.assertEqual(cm.exception.protected_objects, {a})
def test_do_nothing(self):
# Testing DO_NOTHING is a bit harder: It would raise IntegrityError for
# a normal model, so we connect to pre_delete and set the fk to a known
# value.
replacement_r = R.objects.create()
def check_do_nothing(sender, **kwargs):
obj = kwargs["instance"]
obj.donothing_set.update(donothing=replacement_r)
models.signals.pre_delete.connect(check_do_nothing)
a = create_a("do_nothing")
a.donothing.delete()
a = A.objects.get(pk=a.pk)
self.assertEqual(replacement_r, a.donothing)
models.signals.pre_delete.disconnect(check_do_nothing)
def test_do_nothing_qscount(self):
"""
A models.DO_NOTHING relation doesn't trigger a query.
"""
b = Base.objects.create()
with self.assertNumQueries(1):
# RelToBase should not be queried.
b.delete()
self.assertEqual(Base.objects.count(), 0)
def test_inheritance_cascade_up(self):
child = RChild.objects.create()
child.delete()
self.assertFalse(R.objects.filter(pk=child.pk).exists())
def test_inheritance_cascade_down(self):
child = RChild.objects.create()
parent = child.r_ptr
parent.delete()
self.assertFalse(RChild.objects.filter(pk=child.pk).exists())
def test_cascade_from_child(self):
a = create_a("child")
a.child.delete()
self.assertFalse(A.objects.filter(name="child").exists())
self.assertFalse(R.objects.filter(pk=a.child_id).exists())
def test_cascade_from_parent(self):
a = create_a("child")
R.objects.get(pk=a.child_id).delete()
self.assertFalse(A.objects.filter(name="child").exists())
self.assertFalse(RChild.objects.filter(pk=a.child_id).exists())
def test_setnull_from_child(self):
a = create_a("child_setnull")
a.child_setnull.delete()
self.assertFalse(R.objects.filter(pk=a.child_setnull_id).exists())
a = A.objects.get(pk=a.pk)
self.assertIsNone(a.child_setnull)
def test_setnull_from_parent(self):
a = create_a("child_setnull")
R.objects.get(pk=a.child_setnull_id).delete()
self.assertFalse(RChild.objects.filter(pk=a.child_setnull_id).exists())
a = A.objects.get(pk=a.pk)
self.assertIsNone(a.child_setnull)
def test_o2o_setnull(self):
a = create_a("o2o_setnull")
a.o2o_setnull.delete()
a = A.objects.get(pk=a.pk)
self.assertIsNone(a.o2o_setnull)
def test_restrict(self):
a = create_a("restrict")
msg = (
"Cannot delete some instances of model 'R' because they are "
"referenced through restricted foreign keys: 'A.restrict'."
)
with self.assertRaisesMessage(RestrictedError, msg) as cm:
a.restrict.delete()
self.assertEqual(cm.exception.restricted_objects, {a})
def test_restrict_multiple(self):
a = create_a("restrict")
b3 = B3.objects.create(restrict=a.restrict)
msg = (
"Cannot delete some instances of model 'R' because they are "
"referenced through restricted foreign keys: 'A.restrict', "
"'B3.restrict'."
)
with self.assertRaisesMessage(RestrictedError, msg) as cm:
a.restrict.delete()
self.assertEqual(cm.exception.restricted_objects, {a, b3})
def test_restrict_path_cascade_indirect(self):
a = create_a("restrict")
a.restrict.p = P.objects.create()
a.restrict.save()
msg = (
"Cannot delete some instances of model 'P' because they are "
"referenced through restricted foreign keys: 'A.restrict'."
)
with self.assertRaisesMessage(RestrictedError, msg) as cm:
a.restrict.p.delete()
self.assertEqual(cm.exception.restricted_objects, {a})
# Object referenced also with CASCADE relationship can be deleted.
a.cascade.p = a.restrict.p
a.cascade.save()
a.restrict.p.delete()
self.assertFalse(A.objects.filter(name="restrict").exists())
self.assertFalse(R.objects.filter(pk=a.restrict_id).exists())
def test_restrict_path_cascade_direct(self):
a = create_a("restrict")
a.restrict.p = P.objects.create()
a.restrict.save()
a.cascade_p = a.restrict.p
a.save()
a.restrict.p.delete()
self.assertFalse(A.objects.filter(name="restrict").exists())
self.assertFalse(R.objects.filter(pk=a.restrict_id).exists())
def test_restrict_path_cascade_indirect_diamond(self):
delete_top = DeleteTop.objects.create()
b1 = B1.objects.create(delete_top=delete_top)
b2 = B2.objects.create(delete_top=delete_top)
delete_bottom = DeleteBottom.objects.create(b1=b1, b2=b2)
msg = (
"Cannot delete some instances of model 'B1' because they are "
"referenced through restricted foreign keys: 'DeleteBottom.b1'."
)
with self.assertRaisesMessage(RestrictedError, msg) as cm:
b1.delete()
self.assertEqual(cm.exception.restricted_objects, {delete_bottom})
self.assertTrue(DeleteTop.objects.exists())
self.assertTrue(B1.objects.exists())
self.assertTrue(B2.objects.exists())
self.assertTrue(DeleteBottom.objects.exists())
# Object referenced also with CASCADE relationship can be deleted.
delete_top.delete()
self.assertFalse(DeleteTop.objects.exists())
self.assertFalse(B1.objects.exists())
self.assertFalse(B2.objects.exists())
self.assertFalse(DeleteBottom.objects.exists())
def test_restrict_gfk_no_fast_delete(self):
delete_top = DeleteTop.objects.create()
generic_b1 = GenericB1.objects.create(generic_delete_top=delete_top)
generic_b2 = GenericB2.objects.create(generic_delete_top=delete_top)
generic_delete_bottom = GenericDeleteBottom.objects.create(
generic_b1=generic_b1,
generic_b2=generic_b2,
)
msg = (
"Cannot delete some instances of model 'GenericB1' because they "
"are referenced through restricted foreign keys: "
"'GenericDeleteBottom.generic_b1'."
)
with self.assertRaisesMessage(RestrictedError, msg) as cm:
generic_b1.delete()
self.assertEqual(cm.exception.restricted_objects, {generic_delete_bottom})
self.assertTrue(DeleteTop.objects.exists())
self.assertTrue(GenericB1.objects.exists())
self.assertTrue(GenericB2.objects.exists())
self.assertTrue(GenericDeleteBottom.objects.exists())
# Object referenced also with CASCADE relationship can be deleted.
delete_top.delete()
self.assertFalse(DeleteTop.objects.exists())
self.assertFalse(GenericB1.objects.exists())
self.assertFalse(GenericB2.objects.exists())
self.assertFalse(GenericDeleteBottom.objects.exists())
class DeletionTests(TestCase):
def test_sliced_queryset(self):
msg = "Cannot use 'limit' or 'offset' with delete()."
with self.assertRaisesMessage(TypeError, msg):
M.objects.all()[0:5].delete()
def test_pk_none(self):
m = M()
msg = "M object can't be deleted because its id attribute is set to None."
with self.assertRaisesMessage(ValueError, msg):
m.delete()
def test_m2m(self):
m = M.objects.create()
r = R.objects.create()
MR.objects.create(m=m, r=r)
r.delete()
self.assertFalse(MR.objects.exists())
r = R.objects.create()
MR.objects.create(m=m, r=r)
m.delete()
self.assertFalse(MR.objects.exists())
m = M.objects.create()
r = R.objects.create()
m.m2m.add(r)
r.delete()
through = M._meta.get_field("m2m").remote_field.through
self.assertFalse(through.objects.exists())
r = R.objects.create()
m.m2m.add(r)
m.delete()
self.assertFalse(through.objects.exists())
m = M.objects.create()
r = R.objects.create()
MRNull.objects.create(m=m, r=r)
r.delete()
self.assertFalse(not MRNull.objects.exists())
self.assertFalse(m.m2m_through_null.exists())
def test_bulk(self):
s = S.objects.create(r=R.objects.create())
for i in range(2 * GET_ITERATOR_CHUNK_SIZE):
T.objects.create(s=s)
# 1 (select related `T` instances)
# + 1 (select related `U` instances)
# + 2 (delete `T` instances in batches)
# + 1 (delete `s`)
self.assertNumQueries(5, s.delete)
self.assertFalse(S.objects.exists())
def test_instance_update(self):
deleted = []
related_setnull_sets = []
def pre_delete(sender, **kwargs):
obj = kwargs["instance"]
deleted.append(obj)
if isinstance(obj, R):
related_setnull_sets.append([a.pk for a in obj.setnull_set.all()])
models.signals.pre_delete.connect(pre_delete)
a = create_a("update_setnull")
a.setnull.delete()
a = create_a("update_cascade")
a.cascade.delete()
for obj in deleted:
self.assertIsNone(obj.pk)
for pk_list in related_setnull_sets:
for a in A.objects.filter(id__in=pk_list):
self.assertIsNone(a.setnull)
models.signals.pre_delete.disconnect(pre_delete)
def test_deletion_order(self):
pre_delete_order = []
post_delete_order = []
def log_post_delete(sender, **kwargs):
pre_delete_order.append((sender, kwargs["instance"].pk))
def log_pre_delete(sender, **kwargs):
post_delete_order.append((sender, kwargs["instance"].pk))
models.signals.post_delete.connect(log_post_delete)
models.signals.pre_delete.connect(log_pre_delete)
r = R.objects.create(pk=1)
s1 = S.objects.create(pk=1, r=r)
s2 = S.objects.create(pk=2, r=r)
T.objects.create(pk=1, s=s1)
T.objects.create(pk=2, s=s2)
RChild.objects.create(r_ptr=r)
r.delete()
self.assertEqual(
pre_delete_order, [(T, 2), (T, 1), (RChild, 1), (S, 2), (S, 1), (R, 1)]
)
self.assertEqual(
post_delete_order, [(T, 1), (T, 2), (RChild, 1), (S, 1), (S, 2), (R, 1)]
)
models.signals.post_delete.disconnect(log_post_delete)
models.signals.pre_delete.disconnect(log_pre_delete)
def test_relational_post_delete_signals_happen_before_parent_object(self):
deletions = []
def log_post_delete(instance, **kwargs):
self.assertTrue(R.objects.filter(pk=instance.r_id))
self.assertIs(type(instance), S)
deletions.append(instance.id)
r = R.objects.create()
s = S.objects.create(r=r)
s_id = s.pk
models.signals.post_delete.connect(log_post_delete, sender=S)
try:
r.delete()
finally:
models.signals.post_delete.disconnect(log_post_delete)
self.assertEqual(len(deletions), 1)
self.assertEqual(deletions[0], s_id)
@skipUnlessDBFeature("can_defer_constraint_checks")
def test_can_defer_constraint_checks(self):
u = User.objects.create(avatar=Avatar.objects.create())
a = Avatar.objects.get(pk=u.avatar_id)
# 1 query to find the users for the avatar.
# 1 query to delete the user
# 1 query to delete the avatar
# The important thing is that when we can defer constraint checks there
# is no need to do an UPDATE on User.avatar to null it out.
# Attach a signal to make sure we will not do fast_deletes.
calls = []
def noop(*args, **kwargs):
calls.append("")
models.signals.post_delete.connect(noop, sender=User)
self.assertNumQueries(3, a.delete)
self.assertFalse(User.objects.exists())
self.assertFalse(Avatar.objects.exists())
self.assertEqual(len(calls), 1)
models.signals.post_delete.disconnect(noop, sender=User)
@skipIfDBFeature("can_defer_constraint_checks")
def test_cannot_defer_constraint_checks(self):
u = User.objects.create(avatar=Avatar.objects.create())
# Attach a signal to make sure we will not do fast_deletes.
calls = []
def noop(*args, **kwargs):
calls.append("")
models.signals.post_delete.connect(noop, sender=User)
a = Avatar.objects.get(pk=u.avatar_id)
# The below doesn't make sense... Why do we need to null out
# user.avatar if we are going to delete the user immediately after it,
# and there are no more cascades.
# 1 query to find the users for the avatar.
# 1 query to delete the user
# 1 query to null out user.avatar, because we can't defer the constraint
# 1 query to delete the avatar
self.assertNumQueries(4, a.delete)
self.assertFalse(User.objects.exists())
self.assertFalse(Avatar.objects.exists())
self.assertEqual(len(calls), 1)
models.signals.post_delete.disconnect(noop, sender=User)
def test_hidden_related(self):
r = R.objects.create()
h = HiddenUser.objects.create(r=r)
HiddenUserProfile.objects.create(user=h)
r.delete()
self.assertEqual(HiddenUserProfile.objects.count(), 0)
def test_large_delete(self):
TEST_SIZE = 2000
objs = [Avatar() for i in range(0, TEST_SIZE)]
Avatar.objects.bulk_create(objs)
# Calculate the number of queries needed.
batch_size = connection.ops.bulk_batch_size(["pk"], objs)
# The related fetches are done in batches.
batches = ceil(len(objs) / batch_size)
# One query for Avatar.objects.all() and then one related fast delete for
# each batch.
fetches_to_mem = 1 + batches
# The Avatar objects are going to be deleted in batches of
# GET_ITERATOR_CHUNK_SIZE.
queries = fetches_to_mem + TEST_SIZE // GET_ITERATOR_CHUNK_SIZE
self.assertNumQueries(queries, Avatar.objects.all().delete)
self.assertFalse(Avatar.objects.exists())
def test_large_delete_related(self):
TEST_SIZE = 2000
s = S.objects.create(r=R.objects.create())
for i in range(TEST_SIZE):
T.objects.create(s=s)
batch_size = max(connection.ops.bulk_batch_size(["pk"], range(TEST_SIZE)), 1)
# TEST_SIZE / batch_size (select related `T` instances)
# + 1 (select related `U` instances)
# + TEST_SIZE / GET_ITERATOR_CHUNK_SIZE (delete `T` instances in batches)
# + 1 (delete `s`)
expected_num_queries = ceil(TEST_SIZE / batch_size)
expected_num_queries += ceil(TEST_SIZE / GET_ITERATOR_CHUNK_SIZE) + 2
self.assertNumQueries(expected_num_queries, s.delete)
self.assertFalse(S.objects.exists())
self.assertFalse(T.objects.exists())
def test_delete_with_keeping_parents(self):
child = RChild.objects.create()
parent_id = child.r_ptr_id
child.delete(keep_parents=True)
self.assertFalse(RChild.objects.filter(id=child.id).exists())
self.assertTrue(R.objects.filter(id=parent_id).exists())
def test_delete_with_keeping_parents_relationships(self):
child = RChild.objects.create()
parent_id = child.r_ptr_id
parent_referent_id = S.objects.create(r=child.r_ptr).pk
child.delete(keep_parents=True)
self.assertFalse(RChild.objects.filter(id=child.id).exists())
self.assertTrue(R.objects.filter(id=parent_id).exists())
self.assertTrue(S.objects.filter(pk=parent_referent_id).exists())
childchild = RChildChild.objects.create()
parent_id = childchild.rchild_ptr.r_ptr_id
child_id = childchild.rchild_ptr_id
parent_referent_id = S.objects.create(r=childchild.rchild_ptr.r_ptr).pk
childchild.delete(keep_parents=True)
self.assertFalse(RChildChild.objects.filter(id=childchild.id).exists())
self.assertTrue(RChild.objects.filter(id=child_id).exists())
self.assertTrue(R.objects.filter(id=parent_id).exists())
self.assertTrue(S.objects.filter(pk=parent_referent_id).exists())
def test_queryset_delete_returns_num_rows(self):
"""
QuerySet.delete() should return the number of deleted rows and a
dictionary with the number of deletions for each object type.
"""
Avatar.objects.bulk_create(
[Avatar(desc="a"), Avatar(desc="b"), Avatar(desc="c")]
)
avatars_count = Avatar.objects.count()
deleted, rows_count = Avatar.objects.all().delete()
self.assertEqual(deleted, avatars_count)
# more complex example with multiple object types
r = R.objects.create()
h1 = HiddenUser.objects.create(r=r)
HiddenUser.objects.create(r=r)
HiddenUserProfile.objects.create(user=h1)
existed_objs = {
R._meta.label: R.objects.count(),
HiddenUser._meta.label: HiddenUser.objects.count(),
HiddenUserProfile._meta.label: HiddenUserProfile.objects.count(),
}
deleted, deleted_objs = R.objects.all().delete()
self.assertCountEqual(deleted_objs.keys(), existed_objs.keys())
for k, v in existed_objs.items():
self.assertEqual(deleted_objs[k], v)
def test_model_delete_returns_num_rows(self):
"""
Model.delete() should return the number of deleted rows and a
dictionary with the number of deletions for each object type.
"""
r = R.objects.create()
h1 = HiddenUser.objects.create(r=r)
h2 = HiddenUser.objects.create(r=r)
HiddenUser.objects.create(r=r)
HiddenUserProfile.objects.create(user=h1)
HiddenUserProfile.objects.create(user=h2)
m1 = M.objects.create()
m2 = M.objects.create()
MR.objects.create(r=r, m=m1)
r.m_set.add(m1)
r.m_set.add(m2)
r.save()
existed_objs = {
R._meta.label: R.objects.count(),
HiddenUser._meta.label: HiddenUser.objects.count(),
MR._meta.label: MR.objects.count(),
HiddenUserProfile._meta.label: HiddenUserProfile.objects.count(),
M.m2m.through._meta.label: M.m2m.through.objects.count(),
}
deleted, deleted_objs = r.delete()
self.assertEqual(deleted, sum(existed_objs.values()))
self.assertCountEqual(deleted_objs.keys(), existed_objs.keys())
for k, v in existed_objs.items():
self.assertEqual(deleted_objs[k], v)
def test_proxied_model_duplicate_queries(self):
"""
#25685 - Deleting instances of a model with existing proxy
classes should not issue multiple queries during cascade
deletion of referring models.
"""
avatar = Avatar.objects.create()
# One query for the Avatar table and a second for the User one.
with self.assertNumQueries(2):
avatar.delete()
def test_only_referenced_fields_selected(self):
"""
Only referenced fields are selected during cascade deletion SELECT
unless deletion signals are connected.
"""
origin = Origin.objects.create()
expected_sql = str(
Referrer.objects.only(
# Both fields are referenced by SecondReferrer.
"id",
"unique_field",
)
.filter(origin__in=[origin])
.query
)
with self.assertNumQueries(2) as ctx:
origin.delete()
self.assertEqual(ctx.captured_queries[0]["sql"], expected_sql)
def receiver(instance, **kwargs):
pass
# All fields are selected if deletion signals are connected.
for signal_name in ("pre_delete", "post_delete"):
with self.subTest(signal=signal_name):
origin = Origin.objects.create()
signal = getattr(models.signals, signal_name)
signal.connect(receiver, sender=Referrer)
with self.assertNumQueries(2) as ctx:
origin.delete()
self.assertIn(
connection.ops.quote_name("large_field"),
ctx.captured_queries[0]["sql"],
)
signal.disconnect(receiver, sender=Referrer)
class FastDeleteTests(TestCase):
def test_fast_delete_all(self):
with self.assertNumQueries(1) as ctx:
User.objects.all().delete()
sql = ctx.captured_queries[0]["sql"]
# No subqueries is used when performing a full delete.
self.assertNotIn("SELECT", sql)
def test_fast_delete_fk(self):
u = User.objects.create(avatar=Avatar.objects.create())
a = Avatar.objects.get(pk=u.avatar_id)
# 1 query to fast-delete the user
# 1 query to delete the avatar
self.assertNumQueries(2, a.delete)
self.assertFalse(User.objects.exists())
self.assertFalse(Avatar.objects.exists())
def test_fast_delete_m2m(self):
t = M2MTo.objects.create()
f = M2MFrom.objects.create()
f.m2m.add(t)
# 1 to delete f, 1 to fast-delete m2m for f
self.assertNumQueries(2, f.delete)
def test_fast_delete_revm2m(self):
t = M2MTo.objects.create()
f = M2MFrom.objects.create()
f.m2m.add(t)
# 1 to delete t, 1 to fast-delete t's m_set
self.assertNumQueries(2, f.delete)
def test_fast_delete_qs(self):
u1 = User.objects.create()
u2 = User.objects.create()
self.assertNumQueries(1, User.objects.filter(pk=u1.pk).delete)
self.assertEqual(User.objects.count(), 1)
self.assertTrue(User.objects.filter(pk=u2.pk).exists())
def test_fast_delete_instance_set_pk_none(self):
u = User.objects.create()
# User can be fast-deleted.
collector = Collector(using="default")
self.assertTrue(collector.can_fast_delete(u))
u.delete()
self.assertIsNone(u.pk)
def test_fast_delete_joined_qs(self):
a = Avatar.objects.create(desc="a")
User.objects.create(avatar=a)
u2 = User.objects.create()
self.assertNumQueries(1, User.objects.filter(avatar__desc="a").delete)
self.assertEqual(User.objects.count(), 1)
self.assertTrue(User.objects.filter(pk=u2.pk).exists())
def test_fast_delete_inheritance(self):
c = Child.objects.create()
p = Parent.objects.create()
# 1 for self, 1 for parent
self.assertNumQueries(2, c.delete)
self.assertFalse(Child.objects.exists())
self.assertEqual(Parent.objects.count(), 1)
self.assertEqual(Parent.objects.filter(pk=p.pk).count(), 1)
# 1 for self delete, 1 for fast delete of empty "child" qs.
self.assertNumQueries(2, p.delete)
self.assertFalse(Parent.objects.exists())
# 1 for self delete, 1 for fast delete of empty "child" qs.
c = Child.objects.create()
p = c.parent_ptr
self.assertNumQueries(2, p.delete)
self.assertFalse(Parent.objects.exists())
self.assertFalse(Child.objects.exists())
def test_fast_delete_large_batch(self):
User.objects.bulk_create(User() for i in range(0, 2000))
# No problems here - we aren't going to cascade, so we will fast
# delete the objects in a single query.
self.assertNumQueries(1, User.objects.all().delete)
a = Avatar.objects.create(desc="a")
User.objects.bulk_create(User(avatar=a) for i in range(0, 2000))
# We don't hit parameter amount limits for a, so just one query for
# that + fast delete of the related objs.
self.assertNumQueries(2, a.delete)
self.assertEqual(User.objects.count(), 0)
def test_fast_delete_empty_no_update_can_self_select(self):
"""
Fast deleting when DatabaseFeatures.update_can_self_select = False
works even if the specified filter doesn't match any row (#25932).
"""
with self.assertNumQueries(1):
self.assertEqual(
User.objects.filter(avatar__desc="missing").delete(),
(0, {}),
)
def test_fast_delete_combined_relationships(self):
# The cascading fast-delete of SecondReferrer should be combined
# in a single DELETE WHERE referrer_id OR unique_field.
origin = Origin.objects.create()
referer = Referrer.objects.create(origin=origin, unique_field=42)
with self.assertNumQueries(2):
referer.delete()
def test_fast_delete_aggregation(self):
# Fast-deleting when filtering against an aggregation result in
# a single query containing a subquery.
Base.objects.create()
with self.assertNumQueries(1):
self.assertEqual(
Base.objects.annotate(
rels_count=models.Count("rels"),
)
.filter(rels_count=0)
.delete(),
(1, {"delete.Base": 1}),
)
self.assertIs(Base.objects.exists(), False)
|
2d0ff024832c103900306ff1c3bf1322bf6a9e3d075ef277387ad7d0d55c1f60 | from unittest import skipUnless
from django.core import checks
from django.db import connection, models
from django.test import SimpleTestCase
from django.test.utils import isolate_apps
@isolate_apps("invalid_models_tests")
class DeprecatedFieldsTests(SimpleTestCase):
def test_IPAddressField_deprecated(self):
class IPAddressModel(models.Model):
ip = models.IPAddressField()
model = IPAddressModel()
self.assertEqual(
model.check(),
[
checks.Error(
"IPAddressField has been removed except for support in "
"historical migrations.",
hint="Use GenericIPAddressField instead.",
obj=IPAddressModel._meta.get_field("ip"),
id="fields.E900",
)
],
)
def test_CommaSeparatedIntegerField_deprecated(self):
class CommaSeparatedIntegerModel(models.Model):
csi = models.CommaSeparatedIntegerField(max_length=64)
model = CommaSeparatedIntegerModel()
self.assertEqual(
model.check(),
[
checks.Error(
"CommaSeparatedIntegerField is removed except for support in "
"historical migrations.",
hint=(
"Use "
"CharField(validators=[validate_comma_separated_integer_list]) "
"instead."
),
obj=CommaSeparatedIntegerModel._meta.get_field("csi"),
id="fields.E901",
)
],
)
def test_nullbooleanfield_deprecated(self):
class NullBooleanFieldModel(models.Model):
nb = models.NullBooleanField()
model = NullBooleanFieldModel()
self.assertEqual(
model.check(),
[
checks.Error(
"NullBooleanField is removed except for support in historical "
"migrations.",
hint="Use BooleanField(null=True) instead.",
obj=NullBooleanFieldModel._meta.get_field("nb"),
id="fields.E903",
),
],
)
@skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL")
def test_postgres_jsonfield_deprecated(self):
from django.contrib.postgres.fields import JSONField
class PostgresJSONFieldModel(models.Model):
field = JSONField()
self.assertEqual(
PostgresJSONFieldModel.check(),
[
checks.Error(
"django.contrib.postgres.fields.JSONField is removed except "
"for support in historical migrations.",
hint="Use django.db.models.JSONField instead.",
obj=PostgresJSONFieldModel._meta.get_field("field"),
id="fields.E904",
),
],
)
@skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL")
def test_postgres_ci_fields_deprecated(self):
from django.contrib.postgres.fields import (
ArrayField,
CICharField,
CIEmailField,
CITextField,
)
class PostgresCIFieldsModel(models.Model):
ci_char = CICharField(max_length=255)
ci_email = CIEmailField()
ci_text = CITextField()
array_ci_text = ArrayField(CITextField())
self.assertEqual(
PostgresCIFieldsModel.check(),
[
checks.Warning(
"django.contrib.postgres.fields.CICharField is deprecated. Support "
"for it (except in historical migrations) will be removed in "
"Django 5.1.",
hint=(
'Use CharField(db_collation="…") with a case-insensitive '
"non-deterministic collation instead."
),
obj=PostgresCIFieldsModel._meta.get_field("ci_char"),
id="fields.W905",
),
checks.Warning(
"django.contrib.postgres.fields.CIEmailField is deprecated. "
"Support for it (except in historical migrations) will be removed "
"in Django 5.1.",
hint=(
'Use EmailField(db_collation="…") with a case-insensitive '
"non-deterministic collation instead."
),
obj=PostgresCIFieldsModel._meta.get_field("ci_email"),
id="fields.W906",
),
checks.Warning(
"django.contrib.postgres.fields.CITextField is deprecated. Support "
"for it (except in historical migrations) will be removed in "
"Django 5.1.",
hint=(
'Use TextField(db_collation="…") with a case-insensitive '
"non-deterministic collation instead."
),
obj=PostgresCIFieldsModel._meta.get_field("ci_text"),
id="fields.W907",
),
checks.Warning(
"Base field for array has warnings:\n"
" django.contrib.postgres.fields.CITextField is deprecated. "
"Support for it (except in historical migrations) will be removed "
"in Django 5.1. (fields.W907)",
obj=PostgresCIFieldsModel._meta.get_field("array_ci_text"),
id="postgres.W004",
),
],
)
|
bba9afafdfbdc8015aca2daf79681a215029cbbdc0ab6465d517265fe22b2649 | from datetime import datetime
from operator import attrgetter
from django.db.models import Q
from django.test import TestCase
from .models import Article
class OrLookupsTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.a1 = Article.objects.create(
headline="Hello", pub_date=datetime(2005, 11, 27)
).pk
cls.a2 = Article.objects.create(
headline="Goodbye", pub_date=datetime(2005, 11, 28)
).pk
cls.a3 = Article.objects.create(
headline="Hello and goodbye", pub_date=datetime(2005, 11, 29)
).pk
def test_filter_or(self):
self.assertQuerySetEqual(
(
Article.objects.filter(headline__startswith="Hello")
| Article.objects.filter(headline__startswith="Goodbye")
),
["Hello", "Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(headline__contains="Hello")
| Article.objects.filter(headline__contains="bye"),
["Hello", "Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(headline__iexact="Hello")
| Article.objects.filter(headline__contains="ood"),
["Hello", "Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(
Q(headline__startswith="Hello") | Q(headline__startswith="Goodbye")
),
["Hello", "Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
def test_stages(self):
# You can shorten this syntax with code like the following, which is
# especially useful if building the query in stages:
articles = Article.objects.all()
self.assertQuerySetEqual(
articles.filter(headline__startswith="Hello")
& articles.filter(headline__startswith="Goodbye"),
[],
)
self.assertQuerySetEqual(
articles.filter(headline__startswith="Hello")
& articles.filter(headline__contains="bye"),
["Hello and goodbye"],
attrgetter("headline"),
)
def test_pk_q(self):
self.assertQuerySetEqual(
Article.objects.filter(Q(pk=self.a1) | Q(pk=self.a2)),
["Hello", "Goodbye"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(Q(pk=self.a1) | Q(pk=self.a2) | Q(pk=self.a3)),
["Hello", "Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
def test_pk_in(self):
self.assertQuerySetEqual(
Article.objects.filter(pk__in=[self.a1, self.a2, self.a3]),
["Hello", "Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(pk__in=(self.a1, self.a2, self.a3)),
["Hello", "Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(pk__in=[self.a1, self.a2, self.a3, 40000]),
["Hello", "Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
def test_q_repr(self):
or_expr = Q(baz=Article(headline="Foö"))
self.assertEqual(repr(or_expr), "<Q: (AND: ('baz', <Article: Foö>))>")
negated_or = ~Q(baz=Article(headline="Foö"))
self.assertEqual(repr(negated_or), "<Q: (NOT (AND: ('baz', <Article: Foö>)))>")
def test_q_negated(self):
# Q objects can be negated
self.assertQuerySetEqual(
Article.objects.filter(Q(pk=self.a1) | ~Q(pk=self.a2)),
["Hello", "Hello and goodbye"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(~Q(pk=self.a1) & ~Q(pk=self.a2)),
["Hello and goodbye"],
attrgetter("headline"),
)
# This allows for more complex queries than filter() and exclude()
# alone would allow
self.assertQuerySetEqual(
Article.objects.filter(Q(pk=self.a1) & (~Q(pk=self.a2) | Q(pk=self.a3))),
["Hello"],
attrgetter("headline"),
)
def test_complex_filter(self):
# The 'complex_filter' method supports framework features such as
# 'limit_choices_to' which normally take a single dictionary of lookup
# arguments but need to support arbitrary queries via Q objects too.
self.assertQuerySetEqual(
Article.objects.complex_filter({"pk": self.a1}),
["Hello"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.complex_filter(Q(pk=self.a1) | Q(pk=self.a2)),
["Hello", "Goodbye"],
attrgetter("headline"),
)
def test_empty_in(self):
# Passing "in" an empty list returns no results ...
self.assertQuerySetEqual(Article.objects.filter(pk__in=[]), [])
# ... but can return results if we OR it with another query.
self.assertQuerySetEqual(
Article.objects.filter(Q(pk__in=[]) | Q(headline__icontains="goodbye")),
["Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
def test_q_and(self):
# Q arg objects are ANDed
self.assertQuerySetEqual(
Article.objects.filter(
Q(headline__startswith="Hello"), Q(headline__contains="bye")
),
["Hello and goodbye"],
attrgetter("headline"),
)
# Q arg AND order is irrelevant
self.assertQuerySetEqual(
Article.objects.filter(
Q(headline__contains="bye"), headline__startswith="Hello"
),
["Hello and goodbye"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(
Q(headline__startswith="Hello") & Q(headline__startswith="Goodbye")
),
[],
)
def test_q_exclude(self):
self.assertQuerySetEqual(
Article.objects.exclude(Q(headline__startswith="Hello")),
["Goodbye"],
attrgetter("headline"),
)
def test_other_arg_queries(self):
# Try some arg queries with operations other than filter.
self.assertEqual(
Article.objects.get(
Q(headline__startswith="Hello"), Q(headline__contains="bye")
).headline,
"Hello and goodbye",
)
self.assertEqual(
Article.objects.filter(
Q(headline__startswith="Hello") | Q(headline__contains="bye")
).count(),
3,
)
self.assertSequenceEqual(
Article.objects.filter(
Q(headline__startswith="Hello"), Q(headline__contains="bye")
).values(),
[
{
"headline": "Hello and goodbye",
"id": self.a3,
"pub_date": datetime(2005, 11, 29),
},
],
)
self.assertEqual(
Article.objects.filter(Q(headline__startswith="Hello")).in_bulk(
[self.a1, self.a2]
),
{self.a1: Article.objects.get(pk=self.a1)},
)
|
5d1b63a14c0340875a8379ae609589b0757a5f70baf56e65cbbe0ddfe276c8b9 | import operator
import uuid
from unittest import mock
from django import forms
from django.core import serializers
from django.core.exceptions import ValidationError
from django.core.serializers.json import DjangoJSONEncoder
from django.db import (
DataError,
IntegrityError,
NotSupportedError,
OperationalError,
connection,
models,
)
from django.db.models import (
Count,
ExpressionWrapper,
F,
IntegerField,
OuterRef,
Q,
Subquery,
Transform,
Value,
)
from django.db.models.expressions import RawSQL
from django.db.models.fields.json import (
KT,
KeyTextTransform,
KeyTransform,
KeyTransformFactory,
KeyTransformTextLookupMixin,
)
from django.db.models.functions import Cast
from django.test import SimpleTestCase, TestCase, skipIfDBFeature, skipUnlessDBFeature
from django.test.utils import CaptureQueriesContext
from .models import CustomJSONDecoder, JSONModel, NullableJSONModel, RelatedJSONModel
@skipUnlessDBFeature("supports_json_field")
class JSONFieldTests(TestCase):
def test_invalid_value(self):
msg = "is not JSON serializable"
with self.assertRaisesMessage(TypeError, msg):
NullableJSONModel.objects.create(
value={
"uuid": uuid.UUID("d85e2076-b67c-4ee7-8c3a-2bf5a2cc2475"),
}
)
def test_custom_encoder_decoder(self):
value = {"uuid": uuid.UUID("{d85e2076-b67c-4ee7-8c3a-2bf5a2cc2475}")}
obj = NullableJSONModel(value_custom=value)
obj.clean_fields()
obj.save()
obj.refresh_from_db()
self.assertEqual(obj.value_custom, value)
def test_db_check_constraints(self):
value = "{@!invalid json value 123 $!@#"
with mock.patch.object(DjangoJSONEncoder, "encode", return_value=value):
with self.assertRaises((IntegrityError, DataError, OperationalError)):
NullableJSONModel.objects.create(value_custom=value)
class TestMethods(SimpleTestCase):
def test_deconstruct(self):
field = models.JSONField()
name, path, args, kwargs = field.deconstruct()
self.assertEqual(path, "django.db.models.JSONField")
self.assertEqual(args, [])
self.assertEqual(kwargs, {})
def test_deconstruct_custom_encoder_decoder(self):
field = models.JSONField(encoder=DjangoJSONEncoder, decoder=CustomJSONDecoder)
name, path, args, kwargs = field.deconstruct()
self.assertEqual(kwargs["encoder"], DjangoJSONEncoder)
self.assertEqual(kwargs["decoder"], CustomJSONDecoder)
def test_get_transforms(self):
@models.JSONField.register_lookup
class MyTransform(Transform):
lookup_name = "my_transform"
field = models.JSONField()
transform = field.get_transform("my_transform")
self.assertIs(transform, MyTransform)
models.JSONField._unregister_lookup(MyTransform)
transform = field.get_transform("my_transform")
self.assertIsInstance(transform, KeyTransformFactory)
def test_key_transform_text_lookup_mixin_non_key_transform(self):
transform = Transform("test")
msg = (
"Transform should be an instance of KeyTransform in order to use "
"this lookup."
)
with self.assertRaisesMessage(TypeError, msg):
KeyTransformTextLookupMixin(transform)
class TestValidation(SimpleTestCase):
def test_invalid_encoder(self):
msg = "The encoder parameter must be a callable object."
with self.assertRaisesMessage(ValueError, msg):
models.JSONField(encoder=DjangoJSONEncoder())
def test_invalid_decoder(self):
msg = "The decoder parameter must be a callable object."
with self.assertRaisesMessage(ValueError, msg):
models.JSONField(decoder=CustomJSONDecoder())
def test_validation_error(self):
field = models.JSONField()
msg = "Value must be valid JSON."
value = uuid.UUID("{d85e2076-b67c-4ee7-8c3a-2bf5a2cc2475}")
with self.assertRaisesMessage(ValidationError, msg):
field.clean({"uuid": value}, None)
def test_custom_encoder(self):
field = models.JSONField(encoder=DjangoJSONEncoder)
value = uuid.UUID("{d85e2076-b67c-4ee7-8c3a-2bf5a2cc2475}")
field.clean({"uuid": value}, None)
class TestFormField(SimpleTestCase):
def test_formfield(self):
model_field = models.JSONField()
form_field = model_field.formfield()
self.assertIsInstance(form_field, forms.JSONField)
def test_formfield_custom_encoder_decoder(self):
model_field = models.JSONField(
encoder=DjangoJSONEncoder, decoder=CustomJSONDecoder
)
form_field = model_field.formfield()
self.assertIs(form_field.encoder, DjangoJSONEncoder)
self.assertIs(form_field.decoder, CustomJSONDecoder)
class TestSerialization(SimpleTestCase):
test_data = (
'[{"fields": {"value": %s}, "model": "model_fields.jsonmodel", "pk": null}]'
)
test_values = (
# (Python value, serialized value),
({"a": "b", "c": None}, '{"a": "b", "c": null}'),
("abc", '"abc"'),
('{"a": "a"}', '"{\\"a\\": \\"a\\"}"'),
)
def test_dumping(self):
for value, serialized in self.test_values:
with self.subTest(value=value):
instance = JSONModel(value=value)
data = serializers.serialize("json", [instance])
self.assertJSONEqual(data, self.test_data % serialized)
def test_loading(self):
for value, serialized in self.test_values:
with self.subTest(value=value):
instance = list(
serializers.deserialize("json", self.test_data % serialized)
)[0].object
self.assertEqual(instance.value, value)
def test_xml_serialization(self):
test_xml_data = (
'<django-objects version="1.0">'
'<object model="model_fields.nullablejsonmodel">'
'<field name="value" type="JSONField">%s'
"</field></object></django-objects>"
)
for value, serialized in self.test_values:
with self.subTest(value=value):
instance = NullableJSONModel(value=value)
data = serializers.serialize("xml", [instance], fields=["value"])
self.assertXMLEqual(data, test_xml_data % serialized)
new_instance = list(serializers.deserialize("xml", data))[0].object
self.assertEqual(new_instance.value, instance.value)
@skipUnlessDBFeature("supports_json_field")
class TestSaveLoad(TestCase):
def test_null(self):
obj = NullableJSONModel(value=None)
obj.save()
obj.refresh_from_db()
self.assertIsNone(obj.value)
@skipUnlessDBFeature("supports_primitives_in_json_field")
def test_json_null_different_from_sql_null(self):
json_null = NullableJSONModel.objects.create(value=Value("null"))
json_null.refresh_from_db()
sql_null = NullableJSONModel.objects.create(value=None)
sql_null.refresh_from_db()
# 'null' is not equal to NULL in the database.
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value=Value("null")),
[json_null],
)
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value=None),
[json_null],
)
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__isnull=True),
[sql_null],
)
# 'null' is equal to NULL in Python (None).
self.assertEqual(json_null.value, sql_null.value)
@skipUnlessDBFeature("supports_primitives_in_json_field")
def test_primitives(self):
values = [
True,
1,
1.45,
"String",
"",
]
for value in values:
with self.subTest(value=value):
obj = JSONModel(value=value)
obj.save()
obj.refresh_from_db()
self.assertEqual(obj.value, value)
def test_dict(self):
values = [
{},
{"name": "John", "age": 20, "height": 180.3},
{"a": True, "b": {"b1": False, "b2": None}},
]
for value in values:
with self.subTest(value=value):
obj = JSONModel.objects.create(value=value)
obj.refresh_from_db()
self.assertEqual(obj.value, value)
def test_list(self):
values = [
[],
["John", 20, 180.3],
[True, [False, None]],
]
for value in values:
with self.subTest(value=value):
obj = JSONModel.objects.create(value=value)
obj.refresh_from_db()
self.assertEqual(obj.value, value)
def test_realistic_object(self):
value = {
"name": "John",
"age": 20,
"pets": [
{"name": "Kit", "type": "cat", "age": 2},
{"name": "Max", "type": "dog", "age": 1},
],
"courses": [
["A1", "A2", "A3"],
["B1", "B2"],
["C1"],
],
}
obj = JSONModel.objects.create(value=value)
obj.refresh_from_db()
self.assertEqual(obj.value, value)
@skipUnlessDBFeature("supports_json_field")
class TestQuerying(TestCase):
@classmethod
def setUpTestData(cls):
cls.primitives = [True, False, "yes", 7, 9.6]
values = [
None,
[],
{},
{"a": "b", "c": 14},
{
"a": "b",
"c": 14,
"d": ["e", {"f": "g"}],
"h": True,
"i": False,
"j": None,
"k": {"l": "m"},
"n": [None, True, False],
"o": '"quoted"',
"p": 4.2,
"r": {"s": True, "t": False},
},
[1, [2]],
{"k": True, "l": False, "foo": "bax"},
{
"foo": "bar",
"baz": {"a": "b", "c": "d"},
"bar": ["foo", "bar"],
"bax": {"foo": "bar"},
},
]
cls.objs = [NullableJSONModel.objects.create(value=value) for value in values]
if connection.features.supports_primitives_in_json_field:
cls.objs.extend(
[
NullableJSONModel.objects.create(value=value)
for value in cls.primitives
]
)
cls.raw_sql = "%s::jsonb" if connection.vendor == "postgresql" else "%s"
def test_exact(self):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__exact={}),
[self.objs[2]],
)
def test_exact_complex(self):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__exact={"a": "b", "c": 14}),
[self.objs[3]],
)
def test_icontains(self):
self.assertCountEqual(
NullableJSONModel.objects.filter(value__icontains="BaX"),
self.objs[6:8],
)
def test_isnull(self):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__isnull=True),
[self.objs[0]],
)
def test_ordering_by_transform(self):
mariadb = connection.vendor == "mysql" and connection.mysql_is_mariadb
values = [
{"ord": 93, "name": "bar"},
{"ord": 22.1, "name": "foo"},
{"ord": -1, "name": "baz"},
{"ord": 21.931902, "name": "spam"},
{"ord": -100291029, "name": "eggs"},
]
for field_name in ["value", "value_custom"]:
with self.subTest(field=field_name):
objs = [
NullableJSONModel.objects.create(**{field_name: value})
for value in values
]
query = NullableJSONModel.objects.filter(
**{"%s__name__isnull" % field_name: False},
).order_by("%s__ord" % field_name)
expected = [objs[4], objs[2], objs[3], objs[1], objs[0]]
if mariadb or connection.vendor == "oracle":
# MariaDB and Oracle return JSON values as strings.
expected = [objs[2], objs[4], objs[3], objs[1], objs[0]]
self.assertSequenceEqual(query, expected)
def test_ordering_grouping_by_key_transform(self):
base_qs = NullableJSONModel.objects.filter(value__d__0__isnull=False)
for qs in (
base_qs.order_by("value__d__0"),
base_qs.annotate(
key=KeyTransform("0", KeyTransform("d", "value"))
).order_by("key"),
):
self.assertSequenceEqual(qs, [self.objs[4]])
none_val = "" if connection.features.interprets_empty_strings_as_nulls else None
qs = NullableJSONModel.objects.filter(value__isnull=False)
self.assertQuerySetEqual(
qs.filter(value__isnull=False)
.annotate(key=KT("value__d__1__f"))
.values("key")
.annotate(count=Count("key"))
.order_by("count"),
[(none_val, 0), ("g", 1)],
operator.itemgetter("key", "count"),
)
def test_ordering_grouping_by_count(self):
qs = (
NullableJSONModel.objects.filter(
value__isnull=False,
)
.values("value__d__0")
.annotate(count=Count("value__d__0"))
.order_by("count")
)
self.assertQuerySetEqual(qs, [0, 1], operator.itemgetter("count"))
def test_order_grouping_custom_decoder(self):
NullableJSONModel.objects.create(value_custom={"a": "b"})
qs = NullableJSONModel.objects.filter(value_custom__isnull=False)
self.assertSequenceEqual(
qs.values(
"value_custom__a",
)
.annotate(
count=Count("id"),
)
.order_by("value_custom__a"),
[{"value_custom__a": "b", "count": 1}],
)
def test_key_transform_raw_expression(self):
expr = RawSQL(self.raw_sql, ['{"x": "bar"}'])
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__foo=KeyTransform("x", expr)),
[self.objs[7]],
)
def test_nested_key_transform_raw_expression(self):
expr = RawSQL(self.raw_sql, ['{"x": {"y": "bar"}}'])
self.assertSequenceEqual(
NullableJSONModel.objects.filter(
value__foo=KeyTransform("y", KeyTransform("x", expr))
),
[self.objs[7]],
)
def test_key_transform_expression(self):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__d__0__isnull=False)
.annotate(
key=KeyTransform("d", "value"),
chain=KeyTransform("0", "key"),
expr=KeyTransform("0", Cast("key", models.JSONField())),
)
.filter(chain=F("expr")),
[self.objs[4]],
)
def test_key_transform_annotation_expression(self):
obj = NullableJSONModel.objects.create(value={"d": ["e", "e"]})
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__d__0__isnull=False)
.annotate(
key=F("value__d"),
chain=F("key__0"),
expr=Cast("key", models.JSONField()),
)
.filter(chain=F("expr__1")),
[obj],
)
def test_nested_key_transform_expression(self):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__d__0__isnull=False)
.annotate(
key=KeyTransform("d", "value"),
chain=KeyTransform("f", KeyTransform("1", "key")),
expr=KeyTransform(
"f", KeyTransform("1", Cast("key", models.JSONField()))
),
)
.filter(chain=F("expr")),
[self.objs[4]],
)
def test_nested_key_transform_annotation_expression(self):
obj = NullableJSONModel.objects.create(
value={"d": ["e", {"f": "g"}, {"f": "g"}]},
)
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__d__0__isnull=False)
.annotate(
key=F("value__d"),
chain=F("key__1__f"),
expr=Cast("key", models.JSONField()),
)
.filter(chain=F("expr__2__f")),
[obj],
)
def test_nested_key_transform_on_subquery(self):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__d__0__isnull=False)
.annotate(
subquery_value=Subquery(
NullableJSONModel.objects.filter(pk=OuterRef("pk")).values("value")
),
key=KeyTransform("d", "subquery_value"),
chain=KeyTransform("f", KeyTransform("1", "key")),
)
.filter(chain="g"),
[self.objs[4]],
)
def test_key_text_transform_char_lookup(self):
qs = NullableJSONModel.objects.annotate(
char_value=KeyTextTransform("foo", "value"),
).filter(char_value__startswith="bar")
self.assertSequenceEqual(qs, [self.objs[7]])
qs = NullableJSONModel.objects.annotate(
char_value=KeyTextTransform(1, KeyTextTransform("bar", "value")),
).filter(char_value__startswith="bar")
self.assertSequenceEqual(qs, [self.objs[7]])
def test_expression_wrapper_key_transform(self):
self.assertCountEqual(
NullableJSONModel.objects.annotate(
expr=ExpressionWrapper(
KeyTransform("c", "value"),
output_field=IntegerField(),
),
).filter(expr__isnull=False),
self.objs[3:5],
)
def test_has_key(self):
self.assertCountEqual(
NullableJSONModel.objects.filter(value__has_key="a"),
[self.objs[3], self.objs[4]],
)
def test_has_key_null_value(self):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__has_key="j"),
[self.objs[4]],
)
def test_has_key_deep(self):
tests = [
(Q(value__baz__has_key="a"), self.objs[7]),
(
Q(value__has_key=KeyTransform("a", KeyTransform("baz", "value"))),
self.objs[7],
),
(Q(value__has_key=F("value__baz__a")), self.objs[7]),
(
Q(value__has_key=KeyTransform("c", KeyTransform("baz", "value"))),
self.objs[7],
),
(Q(value__has_key=F("value__baz__c")), self.objs[7]),
(Q(value__d__1__has_key="f"), self.objs[4]),
(
Q(
value__has_key=KeyTransform(
"f", KeyTransform("1", KeyTransform("d", "value"))
)
),
self.objs[4],
),
(Q(value__has_key=F("value__d__1__f")), self.objs[4]),
]
for condition, expected in tests:
with self.subTest(condition=condition):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(condition),
[expected],
)
def test_has_key_list(self):
obj = NullableJSONModel.objects.create(value=[{"a": 1}, {"b": "x"}])
tests = [
Q(value__1__has_key="b"),
Q(value__has_key=KeyTransform("b", KeyTransform(1, "value"))),
Q(value__has_key=KeyTransform("b", KeyTransform("1", "value"))),
Q(value__has_key=F("value__1__b")),
]
for condition in tests:
with self.subTest(condition=condition):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(condition),
[obj],
)
def test_has_keys(self):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__has_keys=["a", "c", "h"]),
[self.objs[4]],
)
def test_has_any_keys(self):
self.assertCountEqual(
NullableJSONModel.objects.filter(value__has_any_keys=["c", "l"]),
[self.objs[3], self.objs[4], self.objs[6]],
)
def test_has_key_number(self):
obj = NullableJSONModel.objects.create(
value={
"123": "value",
"nested": {"456": "bar", "lorem": "abc", "999": True},
"array": [{"789": "baz", "777": "def", "ipsum": 200}],
"000": "val",
}
)
tests = [
Q(value__has_key="123"),
Q(value__nested__has_key="456"),
Q(value__array__0__has_key="789"),
Q(value__has_keys=["nested", "123", "array", "000"]),
Q(value__nested__has_keys=["lorem", "999", "456"]),
Q(value__array__0__has_keys=["789", "ipsum", "777"]),
Q(value__has_any_keys=["000", "nonexistent"]),
Q(value__nested__has_any_keys=["999", "nonexistent"]),
Q(value__array__0__has_any_keys=["777", "nonexistent"]),
]
for condition in tests:
with self.subTest(condition=condition):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(condition),
[obj],
)
@skipUnlessDBFeature("supports_json_field_contains")
def test_contains(self):
tests = [
({}, self.objs[2:5] + self.objs[6:8]),
({"baz": {"a": "b", "c": "d"}}, [self.objs[7]]),
({"baz": {"a": "b"}}, [self.objs[7]]),
({"baz": {"c": "d"}}, [self.objs[7]]),
({"k": True, "l": False}, [self.objs[6]]),
({"d": ["e", {"f": "g"}]}, [self.objs[4]]),
({"d": ["e"]}, [self.objs[4]]),
({"d": [{"f": "g"}]}, [self.objs[4]]),
([1, [2]], [self.objs[5]]),
([1], [self.objs[5]]),
([[2]], [self.objs[5]]),
({"n": [None, True, False]}, [self.objs[4]]),
({"j": None}, [self.objs[4]]),
]
for value, expected in tests:
with self.subTest(value=value):
qs = NullableJSONModel.objects.filter(value__contains=value)
self.assertCountEqual(qs, expected)
@skipIfDBFeature("supports_json_field_contains")
def test_contains_unsupported(self):
msg = "contains lookup is not supported on this database backend."
with self.assertRaisesMessage(NotSupportedError, msg):
NullableJSONModel.objects.filter(
value__contains={"baz": {"a": "b", "c": "d"}},
).get()
@skipUnlessDBFeature(
"supports_primitives_in_json_field",
"supports_json_field_contains",
)
def test_contains_primitives(self):
for value in self.primitives:
with self.subTest(value=value):
qs = NullableJSONModel.objects.filter(value__contains=value)
self.assertIs(qs.exists(), True)
@skipUnlessDBFeature("supports_json_field_contains")
def test_contained_by(self):
qs = NullableJSONModel.objects.filter(
value__contained_by={"a": "b", "c": 14, "h": True}
)
self.assertCountEqual(qs, self.objs[2:4])
@skipIfDBFeature("supports_json_field_contains")
def test_contained_by_unsupported(self):
msg = "contained_by lookup is not supported on this database backend."
with self.assertRaisesMessage(NotSupportedError, msg):
NullableJSONModel.objects.filter(value__contained_by={"a": "b"}).get()
def test_deep_values(self):
qs = NullableJSONModel.objects.values_list("value__k__l").order_by("pk")
expected_objs = [(None,)] * len(self.objs)
expected_objs[4] = ("m",)
self.assertSequenceEqual(qs, expected_objs)
@skipUnlessDBFeature("can_distinct_on_fields")
def test_deep_distinct(self):
query = NullableJSONModel.objects.distinct("value__k__l").values_list(
"value__k__l"
)
self.assertSequenceEqual(query, [("m",), (None,)])
def test_isnull_key(self):
# key__isnull=False works the same as has_key='key'.
self.assertCountEqual(
NullableJSONModel.objects.filter(value__a__isnull=True),
self.objs[:3] + self.objs[5:],
)
self.assertCountEqual(
NullableJSONModel.objects.filter(value__j__isnull=True),
self.objs[:4] + self.objs[5:],
)
self.assertCountEqual(
NullableJSONModel.objects.filter(value__a__isnull=False),
[self.objs[3], self.objs[4]],
)
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__j__isnull=False),
[self.objs[4]],
)
def test_isnull_key_or_none(self):
obj = NullableJSONModel.objects.create(value={"a": None})
self.assertCountEqual(
NullableJSONModel.objects.filter(
Q(value__a__isnull=True) | Q(value__a=None)
),
self.objs[:3] + self.objs[5:] + [obj],
)
def test_none_key(self):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__j=None),
[self.objs[4]],
)
def test_none_key_exclude(self):
obj = NullableJSONModel.objects.create(value={"j": 1})
if connection.vendor == "oracle":
# Oracle supports filtering JSON objects with NULL keys, but the
# current implementation doesn't support it.
self.assertSequenceEqual(
NullableJSONModel.objects.exclude(value__j=None),
self.objs[1:4] + self.objs[5:] + [obj],
)
else:
self.assertSequenceEqual(
NullableJSONModel.objects.exclude(value__j=None), [obj]
)
def test_shallow_list_lookup(self):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__0=1),
[self.objs[5]],
)
def test_shallow_obj_lookup(self):
self.assertCountEqual(
NullableJSONModel.objects.filter(value__a="b"),
[self.objs[3], self.objs[4]],
)
def test_obj_subquery_lookup(self):
qs = NullableJSONModel.objects.annotate(
field=Subquery(
NullableJSONModel.objects.filter(pk=OuterRef("pk")).values("value")
),
).filter(field__a="b")
self.assertCountEqual(qs, [self.objs[3], self.objs[4]])
def test_deep_lookup_objs(self):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__k__l="m"),
[self.objs[4]],
)
def test_shallow_lookup_obj_target(self):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__k={"l": "m"}),
[self.objs[4]],
)
def test_deep_lookup_array(self):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__1__0=2),
[self.objs[5]],
)
def test_deep_lookup_mixed(self):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__d__1__f="g"),
[self.objs[4]],
)
def test_deep_lookup_transform(self):
self.assertCountEqual(
NullableJSONModel.objects.filter(value__c__gt=2),
[self.objs[3], self.objs[4]],
)
self.assertCountEqual(
NullableJSONModel.objects.filter(value__c__gt=2.33),
[self.objs[3], self.objs[4]],
)
self.assertIs(NullableJSONModel.objects.filter(value__c__lt=5).exists(), False)
def test_lookup_exclude(self):
tests = [
(Q(value__a="b"), [self.objs[0]]),
(Q(value__foo="bax"), [self.objs[0], self.objs[7]]),
]
for condition, expected in tests:
self.assertCountEqual(
NullableJSONModel.objects.exclude(condition),
expected,
)
self.assertCountEqual(
NullableJSONModel.objects.filter(~condition),
expected,
)
def test_lookup_exclude_nonexistent_key(self):
# Values without the key are ignored.
condition = Q(value__foo="bax")
objs_with_value = [self.objs[6]]
objs_with_different_value = [self.objs[0], self.objs[7]]
self.assertCountEqual(
NullableJSONModel.objects.exclude(condition),
objs_with_different_value,
)
self.assertSequenceEqual(
NullableJSONModel.objects.exclude(~condition),
objs_with_value,
)
self.assertCountEqual(
NullableJSONModel.objects.filter(condition | ~condition),
objs_with_value + objs_with_different_value,
)
self.assertCountEqual(
NullableJSONModel.objects.exclude(condition & ~condition),
objs_with_value + objs_with_different_value,
)
# Add the __isnull lookup to get an exhaustive set.
self.assertCountEqual(
NullableJSONModel.objects.exclude(condition & Q(value__foo__isnull=False)),
self.objs[0:6] + self.objs[7:],
)
self.assertSequenceEqual(
NullableJSONModel.objects.filter(condition & Q(value__foo__isnull=False)),
objs_with_value,
)
def test_usage_in_subquery(self):
self.assertCountEqual(
NullableJSONModel.objects.filter(
id__in=NullableJSONModel.objects.filter(value__c=14),
),
self.objs[3:5],
)
@skipUnlessDBFeature("supports_json_field_contains")
def test_array_key_contains(self):
tests = [
([], [self.objs[7]]),
("bar", [self.objs[7]]),
(["bar"], [self.objs[7]]),
("ar", []),
]
for value, expected in tests:
with self.subTest(value=value):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__bar__contains=value),
expected,
)
def test_key_iexact(self):
self.assertIs(
NullableJSONModel.objects.filter(value__foo__iexact="BaR").exists(), True
)
self.assertIs(
NullableJSONModel.objects.filter(value__foo__iexact='"BaR"').exists(), False
)
def test_key_in(self):
tests = [
("value__c__in", [14], self.objs[3:5]),
("value__c__in", [14, 15], self.objs[3:5]),
("value__0__in", [1], [self.objs[5]]),
("value__0__in", [1, 3], [self.objs[5]]),
("value__foo__in", ["bar"], [self.objs[7]]),
(
"value__foo__in",
[KeyTransform("foo", KeyTransform("bax", "value"))],
[self.objs[7]],
),
("value__foo__in", [F("value__bax__foo")], [self.objs[7]]),
(
"value__foo__in",
[KeyTransform("foo", KeyTransform("bax", "value")), "baz"],
[self.objs[7]],
),
("value__foo__in", [F("value__bax__foo"), "baz"], [self.objs[7]]),
("value__foo__in", ["bar", "baz"], [self.objs[7]]),
("value__bar__in", [["foo", "bar"]], [self.objs[7]]),
("value__bar__in", [["foo", "bar"], ["a"]], [self.objs[7]]),
("value__bax__in", [{"foo": "bar"}, {"a": "b"}], [self.objs[7]]),
("value__h__in", [True, "foo"], [self.objs[4]]),
("value__i__in", [False, "foo"], [self.objs[4]]),
]
for lookup, value, expected in tests:
with self.subTest(lookup=lookup, value=value):
self.assertCountEqual(
NullableJSONModel.objects.filter(**{lookup: value}),
expected,
)
def test_key_values(self):
qs = NullableJSONModel.objects.filter(value__h=True)
tests = [
("value__a", "b"),
("value__c", 14),
("value__d", ["e", {"f": "g"}]),
("value__h", True),
("value__i", False),
("value__j", None),
("value__k", {"l": "m"}),
("value__n", [None, True, False]),
("value__p", 4.2),
("value__r", {"s": True, "t": False}),
]
for lookup, expected in tests:
with self.subTest(lookup=lookup):
self.assertEqual(qs.values_list(lookup, flat=True).get(), expected)
def test_key_values_boolean(self):
qs = NullableJSONModel.objects.filter(value__h=True, value__i=False)
tests = [
("value__h", True),
("value__i", False),
]
for lookup, expected in tests:
with self.subTest(lookup=lookup):
self.assertIs(qs.values_list(lookup, flat=True).get(), expected)
@skipUnlessDBFeature("supports_json_field_contains")
def test_key_contains(self):
self.assertIs(
NullableJSONModel.objects.filter(value__foo__contains="ar").exists(), False
)
self.assertIs(
NullableJSONModel.objects.filter(value__foo__contains="bar").exists(), True
)
def test_key_icontains(self):
self.assertIs(
NullableJSONModel.objects.filter(value__foo__icontains="Ar").exists(), True
)
def test_key_startswith(self):
self.assertIs(
NullableJSONModel.objects.filter(value__foo__startswith="b").exists(), True
)
def test_key_istartswith(self):
self.assertIs(
NullableJSONModel.objects.filter(value__foo__istartswith="B").exists(), True
)
def test_key_endswith(self):
self.assertIs(
NullableJSONModel.objects.filter(value__foo__endswith="r").exists(), True
)
def test_key_iendswith(self):
self.assertIs(
NullableJSONModel.objects.filter(value__foo__iendswith="R").exists(), True
)
def test_key_regex(self):
self.assertIs(
NullableJSONModel.objects.filter(value__foo__regex=r"^bar$").exists(), True
)
def test_key_iregex(self):
self.assertIs(
NullableJSONModel.objects.filter(value__foo__iregex=r"^bAr$").exists(), True
)
def test_key_quoted_string(self):
self.assertEqual(
NullableJSONModel.objects.filter(value__o='"quoted"').get(),
self.objs[4],
)
@skipUnlessDBFeature("has_json_operators")
def test_key_sql_injection(self):
with CaptureQueriesContext(connection) as queries:
self.assertIs(
NullableJSONModel.objects.filter(
**{
"""value__test' = '"a"') OR 1 = 1 OR ('d""": "x",
}
).exists(),
False,
)
self.assertIn(
"""."value" -> 'test'' = ''"a"'') OR 1 = 1 OR (''d') = '"x"' """,
queries[0]["sql"],
)
@skipIfDBFeature("has_json_operators")
def test_key_sql_injection_escape(self):
query = str(
JSONModel.objects.filter(
**{
"""value__test") = '"a"' OR 1 = 1 OR ("d""": "x",
}
).query
)
self.assertIn('"test\\"', query)
self.assertIn('\\"d', query)
def test_key_escape(self):
obj = NullableJSONModel.objects.create(value={"%total": 10})
self.assertEqual(
NullableJSONModel.objects.filter(**{"value__%total": 10}).get(), obj
)
def test_none_key_and_exact_lookup(self):
self.assertSequenceEqual(
NullableJSONModel.objects.filter(value__a="b", value__j=None),
[self.objs[4]],
)
def test_lookups_with_key_transform(self):
tests = (
("value__baz__has_key", "c"),
("value__baz__has_keys", ["a", "c"]),
("value__baz__has_any_keys", ["a", "x"]),
("value__has_key", KeyTextTransform("foo", "value")),
)
for lookup, value in tests:
with self.subTest(lookup=lookup):
self.assertIs(
NullableJSONModel.objects.filter(
**{lookup: value},
).exists(),
True,
)
@skipUnlessDBFeature("supports_json_field_contains")
def test_contains_contained_by_with_key_transform(self):
tests = [
("value__d__contains", "e"),
("value__d__contains", [{"f": "g"}]),
("value__contains", KeyTransform("bax", "value")),
("value__contains", F("value__bax")),
("value__baz__contains", {"a": "b"}),
("value__baz__contained_by", {"a": "b", "c": "d", "e": "f"}),
(
"value__contained_by",
KeyTransform(
"x",
RawSQL(
self.raw_sql,
['{"x": {"a": "b", "c": 1, "d": "e"}}'],
),
),
),
]
# For databases where {'f': 'g'} (without surrounding []) matches
# [{'f': 'g'}].
if not connection.features.json_key_contains_list_matching_requires_list:
tests.append(("value__d__contains", {"f": "g"}))
for lookup, value in tests:
with self.subTest(lookup=lookup, value=value):
self.assertIs(
NullableJSONModel.objects.filter(
**{lookup: value},
).exists(),
True,
)
def test_join_key_transform_annotation_expression(self):
related_obj = RelatedJSONModel.objects.create(
value={"d": ["f", "e"]},
json_model=self.objs[4],
)
RelatedJSONModel.objects.create(
value={"d": ["e", "f"]},
json_model=self.objs[4],
)
self.assertSequenceEqual(
RelatedJSONModel.objects.annotate(
key=F("value__d"),
related_key=F("json_model__value__d"),
chain=F("key__1"),
expr=Cast("key", models.JSONField()),
).filter(chain=F("related_key__0")),
[related_obj],
)
def test_key_text_transform_from_lookup(self):
qs = NullableJSONModel.objects.annotate(b=KT("value__bax__foo")).filter(
b__contains="ar",
)
self.assertSequenceEqual(qs, [self.objs[7]])
qs = NullableJSONModel.objects.annotate(c=KT("value__o")).filter(
c__contains="uot",
)
self.assertSequenceEqual(qs, [self.objs[4]])
def test_key_text_transform_from_lookup_invalid(self):
msg = "Lookup must contain key or index transforms."
with self.assertRaisesMessage(ValueError, msg):
KT("value")
with self.assertRaisesMessage(ValueError, msg):
KT("")
|
2e9fb6302e9f7923ffa4496d88994891ae8e572cdb9f62c0430338decc9637e8 | import json
import tempfile
import uuid
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.core.files.storage import FileSystemStorage
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from django.db.models.fields.files import ImageFieldFile
from django.utils.translation import gettext_lazy as _
try:
from PIL import Image
except ImportError:
Image = None
class Foo(models.Model):
a = models.CharField(max_length=10)
d = models.DecimalField(max_digits=5, decimal_places=3)
def get_foo():
return Foo.objects.get(id=1).pk
class Bar(models.Model):
b = models.CharField(max_length=10)
a = models.ForeignKey(Foo, models.CASCADE, default=get_foo, related_name="bars")
class Whiz(models.Model):
CHOICES = (
(
"Group 1",
(
(1, "First"),
(2, "Second"),
),
),
(
"Group 2",
(
(3, "Third"),
(4, "Fourth"),
),
),
(0, "Other"),
(5, _("translated")),
)
c = models.IntegerField(choices=CHOICES, null=True)
class WhizDelayed(models.Model):
c = models.IntegerField(choices=(), null=True)
# Contrived way of adding choices later.
WhizDelayed._meta.get_field("c").choices = Whiz.CHOICES
class WhizIter(models.Model):
c = models.IntegerField(choices=iter(Whiz.CHOICES), null=True)
class WhizIterEmpty(models.Model):
c = models.CharField(choices=iter(()), blank=True, max_length=1)
class Choiceful(models.Model):
no_choices = models.IntegerField(null=True)
empty_choices = models.IntegerField(choices=(), null=True)
with_choices = models.IntegerField(choices=[(1, "A")], null=True)
empty_choices_bool = models.BooleanField(choices=())
empty_choices_text = models.TextField(choices=())
class BigD(models.Model):
d = models.DecimalField(max_digits=32, decimal_places=30)
class FloatModel(models.Model):
size = models.FloatField()
class BigS(models.Model):
s = models.SlugField(max_length=255)
class UnicodeSlugField(models.Model):
s = models.SlugField(max_length=255, allow_unicode=True)
class AutoModel(models.Model):
value = models.AutoField(primary_key=True)
class BigAutoModel(models.Model):
value = models.BigAutoField(primary_key=True)
class SmallAutoModel(models.Model):
value = models.SmallAutoField(primary_key=True)
class SmallIntegerModel(models.Model):
value = models.SmallIntegerField()
class IntegerModel(models.Model):
value = models.IntegerField()
class BigIntegerModel(models.Model):
value = models.BigIntegerField()
null_value = models.BigIntegerField(null=True, blank=True)
class PositiveBigIntegerModel(models.Model):
value = models.PositiveBigIntegerField()
class PositiveSmallIntegerModel(models.Model):
value = models.PositiveSmallIntegerField()
class PositiveIntegerModel(models.Model):
value = models.PositiveIntegerField()
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
class NullBooleanModel(models.Model):
nbfield = models.BooleanField(null=True, blank=True)
class BooleanModel(models.Model):
bfield = models.BooleanField()
class DateTimeModel(models.Model):
d = models.DateField()
dt = models.DateTimeField()
t = models.TimeField()
class DurationModel(models.Model):
field = models.DurationField()
class NullDurationModel(models.Model):
field = models.DurationField(null=True)
class PrimaryKeyCharModel(models.Model):
string = models.CharField(max_length=10, primary_key=True)
class FksToBooleans(models.Model):
"""Model with FKs to models with {Null,}BooleanField's, #15040"""
bf = models.ForeignKey(BooleanModel, models.CASCADE)
nbf = models.ForeignKey(NullBooleanModel, models.CASCADE)
class FkToChar(models.Model):
"""Model with FK to a model with a CharField primary key, #19299"""
out = models.ForeignKey(PrimaryKeyCharModel, models.CASCADE)
class RenamedField(models.Model):
modelname = models.IntegerField(name="fieldname", choices=((1, "One"),))
class VerboseNameField(models.Model):
id = models.AutoField("verbose pk", primary_key=True)
field1 = models.BigIntegerField("verbose field1")
field2 = models.BooleanField("verbose field2", default=False)
field3 = models.CharField("verbose field3", max_length=10)
field4 = models.DateField("verbose field4")
field5 = models.DateTimeField("verbose field5")
field6 = models.DecimalField("verbose field6", max_digits=6, decimal_places=1)
field7 = models.EmailField("verbose field7")
field8 = models.FileField("verbose field8", upload_to="unused")
field9 = models.FilePathField("verbose field9")
field10 = models.FloatField("verbose field10")
# Don't want to depend on Pillow in this test
# field_image = models.ImageField("verbose field")
field11 = models.IntegerField("verbose field11")
field12 = models.GenericIPAddressField("verbose field12", protocol="ipv4")
field13 = models.PositiveIntegerField("verbose field13")
field14 = models.PositiveSmallIntegerField("verbose field14")
field15 = models.SlugField("verbose field15")
field16 = models.SmallIntegerField("verbose field16")
field17 = models.TextField("verbose field17")
field18 = models.TimeField("verbose field18")
field19 = models.URLField("verbose field19")
field20 = models.UUIDField("verbose field20")
field21 = models.DurationField("verbose field21")
class GenericIPAddress(models.Model):
ip = models.GenericIPAddressField(null=True, protocol="ipv4")
###############################################################################
# These models aren't used in any test, just here to ensure they validate
# successfully.
# See ticket #16570.
class DecimalLessThanOne(models.Model):
d = models.DecimalField(max_digits=3, decimal_places=3)
# See ticket #18389.
class FieldClassAttributeModel(models.Model):
field_class = models.CharField
###############################################################################
class DataModel(models.Model):
short_data = models.BinaryField(max_length=10, default=b"\x08")
data = models.BinaryField()
###############################################################################
# FileField
class Document(models.Model):
myfile = models.FileField(upload_to="unused", unique=True)
###############################################################################
# ImageField
# If Pillow available, do these tests.
if Image:
class TestImageFieldFile(ImageFieldFile):
"""
Custom Field File class that records whether or not the underlying file
was opened.
"""
def __init__(self, *args, **kwargs):
self.was_opened = False
super().__init__(*args, **kwargs)
def open(self):
self.was_opened = True
super().open()
class TestImageField(models.ImageField):
attr_class = TestImageFieldFile
# Set up a temp directory for file storage.
temp_storage_dir = tempfile.mkdtemp()
temp_storage = FileSystemStorage(temp_storage_dir)
class Person(models.Model):
"""
Model that defines an ImageField with no dimension fields.
"""
name = models.CharField(max_length=50)
mugshot = TestImageField(storage=temp_storage, upload_to="tests")
class AbstractPersonWithHeight(models.Model):
"""
Abstract model that defines an ImageField with only one dimension field
to make sure the dimension update is correctly run on concrete subclass
instance post-initialization.
"""
mugshot = TestImageField(
storage=temp_storage, upload_to="tests", height_field="mugshot_height"
)
mugshot_height = models.PositiveSmallIntegerField()
class Meta:
abstract = True
class PersonWithHeight(AbstractPersonWithHeight):
"""
Concrete model that subclass an abstract one with only on dimension
field.
"""
name = models.CharField(max_length=50)
class PersonWithHeightAndWidth(models.Model):
"""
Model that defines height and width fields after the ImageField.
"""
name = models.CharField(max_length=50)
mugshot = TestImageField(
storage=temp_storage,
upload_to="tests",
height_field="mugshot_height",
width_field="mugshot_width",
)
mugshot_height = models.PositiveSmallIntegerField()
mugshot_width = models.PositiveSmallIntegerField()
class PersonDimensionsFirst(models.Model):
"""
Model that defines height and width fields before the ImageField.
"""
name = models.CharField(max_length=50)
mugshot_height = models.PositiveSmallIntegerField()
mugshot_width = models.PositiveSmallIntegerField()
mugshot = TestImageField(
storage=temp_storage,
upload_to="tests",
height_field="mugshot_height",
width_field="mugshot_width",
)
class PersonTwoImages(models.Model):
"""
Model that:
* Defines two ImageFields
* Defines the height/width fields before the ImageFields
* Has a nullable ImageField
"""
name = models.CharField(max_length=50)
mugshot_height = models.PositiveSmallIntegerField()
mugshot_width = models.PositiveSmallIntegerField()
mugshot = TestImageField(
storage=temp_storage,
upload_to="tests",
height_field="mugshot_height",
width_field="mugshot_width",
)
headshot_height = models.PositiveSmallIntegerField(blank=True, null=True)
headshot_width = models.PositiveSmallIntegerField(blank=True, null=True)
headshot = TestImageField(
blank=True,
null=True,
storage=temp_storage,
upload_to="tests",
height_field="headshot_height",
width_field="headshot_width",
)
class CustomJSONDecoder(json.JSONDecoder):
def __init__(self, object_hook=None, *args, **kwargs):
return super().__init__(object_hook=self.as_uuid, *args, **kwargs)
def as_uuid(self, dct):
if "uuid" in dct:
dct["uuid"] = uuid.UUID(dct["uuid"])
return dct
class JSONModel(models.Model):
value = models.JSONField()
class Meta:
required_db_features = {"supports_json_field"}
class NullableJSONModel(models.Model):
value = models.JSONField(blank=True, null=True)
value_custom = models.JSONField(
encoder=DjangoJSONEncoder,
decoder=CustomJSONDecoder,
null=True,
)
class Meta:
required_db_features = {"supports_json_field"}
class RelatedJSONModel(models.Model):
value = models.JSONField()
json_model = models.ForeignKey(NullableJSONModel, models.CASCADE)
class Meta:
required_db_features = {"supports_json_field"}
class AllFieldsModel(models.Model):
big_integer = models.BigIntegerField()
binary = models.BinaryField()
boolean = models.BooleanField(default=False)
char = models.CharField(max_length=10)
date = models.DateField()
datetime = models.DateTimeField()
decimal = models.DecimalField(decimal_places=2, max_digits=2)
duration = models.DurationField()
email = models.EmailField()
file_path = models.FilePathField()
floatf = models.FloatField()
integer = models.IntegerField()
generic_ip = models.GenericIPAddressField()
positive_integer = models.PositiveIntegerField()
positive_small_integer = models.PositiveSmallIntegerField()
slug = models.SlugField()
small_integer = models.SmallIntegerField()
text = models.TextField()
time = models.TimeField()
url = models.URLField()
uuid = models.UUIDField()
fo = models.ForeignObject(
"self",
on_delete=models.CASCADE,
from_fields=["positive_integer"],
to_fields=["id"],
related_name="reverse",
)
fk = models.ForeignKey("self", models.CASCADE, related_name="reverse2")
m2m = models.ManyToManyField("self")
oto = models.OneToOneField("self", models.CASCADE)
object_id = models.PositiveIntegerField()
content_type = models.ForeignKey(ContentType, models.CASCADE)
gfk = GenericForeignKey()
gr = GenericRelation(DataModel)
class ManyToMany(models.Model):
m2m = models.ManyToManyField("self")
###############################################################################
class UUIDModel(models.Model):
field = models.UUIDField()
class NullableUUIDModel(models.Model):
field = models.UUIDField(blank=True, null=True)
class PrimaryKeyUUIDModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
class RelatedToUUIDModel(models.Model):
uuid_fk = models.ForeignKey("PrimaryKeyUUIDModel", models.CASCADE)
class UUIDChild(PrimaryKeyUUIDModel):
pass
class UUIDGrandchild(UUIDChild):
pass
|
a08b6f7fe8cb264b68bce4133042824785c7d82048a6da02ff4c63cb9d8a39a3 | import math
from decimal import Decimal
from django.core import validators
from django.core.exceptions import ValidationError
from django.db import models
from django.test import TestCase
from .models import BigD, Foo
class DecimalFieldTests(TestCase):
def test_to_python(self):
f = models.DecimalField(max_digits=4, decimal_places=2)
self.assertEqual(f.to_python(3), Decimal("3"))
self.assertEqual(f.to_python("3.14"), Decimal("3.14"))
# to_python() converts floats and honors max_digits.
self.assertEqual(f.to_python(3.1415926535897), Decimal("3.142"))
self.assertEqual(f.to_python(2.4), Decimal("2.400"))
# Uses default rounding of ROUND_HALF_EVEN.
self.assertEqual(f.to_python(2.0625), Decimal("2.062"))
self.assertEqual(f.to_python(2.1875), Decimal("2.188"))
def test_invalid_value(self):
field = models.DecimalField(max_digits=4, decimal_places=2)
msg = "“%s” value must be a decimal number."
tests = [
(),
[],
{},
set(),
object(),
complex(),
"non-numeric string",
b"non-numeric byte-string",
]
for value in tests:
with self.subTest(value):
with self.assertRaisesMessage(ValidationError, msg % (value,)):
field.clean(value, None)
def test_default(self):
f = models.DecimalField(default=Decimal("0.00"))
self.assertEqual(f.get_default(), Decimal("0.00"))
def test_get_prep_value(self):
f = models.DecimalField(max_digits=5, decimal_places=1)
self.assertIsNone(f.get_prep_value(None))
self.assertEqual(f.get_prep_value("2.4"), Decimal("2.4"))
def test_filter_with_strings(self):
"""
Should be able to filter decimal fields using strings (#8023).
"""
foo = Foo.objects.create(a="abc", d=Decimal("12.34"))
self.assertEqual(list(Foo.objects.filter(d="12.34")), [foo])
def test_save_without_float_conversion(self):
"""
Ensure decimals don't go through a corrupting float conversion during
save (#5079).
"""
bd = BigD(d="12.9")
bd.save()
bd = BigD.objects.get(pk=bd.pk)
self.assertEqual(bd.d, Decimal("12.9"))
def test_save_nan_invalid(self):
msg = "“nan” value must be a decimal number."
for value in [float("nan"), math.nan, "nan"]:
with self.subTest(value), self.assertRaisesMessage(ValidationError, msg):
BigD.objects.create(d=value)
def test_save_inf_invalid(self):
msg = "“inf” value must be a decimal number."
for value in [float("inf"), math.inf, "inf"]:
with self.subTest(value), self.assertRaisesMessage(ValidationError, msg):
BigD.objects.create(d=value)
msg = "“-inf” value must be a decimal number."
for value in [float("-inf"), -math.inf, "-inf"]:
with self.subTest(value), self.assertRaisesMessage(ValidationError, msg):
BigD.objects.create(d=value)
def test_fetch_from_db_without_float_rounding(self):
big_decimal = BigD.objects.create(d=Decimal(".100000000000000000000000000005"))
big_decimal.refresh_from_db()
self.assertEqual(big_decimal.d, Decimal(".100000000000000000000000000005"))
def test_lookup_really_big_value(self):
"""
Really big values can be used in a filter statement.
"""
# This should not crash.
Foo.objects.filter(d__gte=100000000000)
def test_max_digits_validation(self):
field = models.DecimalField(max_digits=2)
expected_message = validators.DecimalValidator.messages["max_digits"] % {
"max": 2
}
with self.assertRaisesMessage(ValidationError, expected_message):
field.clean(100, None)
def test_max_decimal_places_validation(self):
field = models.DecimalField(decimal_places=1)
expected_message = validators.DecimalValidator.messages[
"max_decimal_places"
] % {"max": 1}
with self.assertRaisesMessage(ValidationError, expected_message):
field.clean(Decimal("0.99"), None)
def test_max_whole_digits_validation(self):
field = models.DecimalField(max_digits=3, decimal_places=1)
expected_message = validators.DecimalValidator.messages["max_whole_digits"] % {
"max": 2
}
with self.assertRaisesMessage(ValidationError, expected_message):
field.clean(Decimal("999"), None)
def test_roundtrip_with_trailing_zeros(self):
"""Trailing zeros in the fractional part aren't truncated."""
obj = Foo.objects.create(a="bar", d=Decimal("8.320"))
obj.refresh_from_db()
self.assertEqual(obj.d.compare_total(Decimal("8.320")), Decimal("0"))
|
f372d663d75fe79f86b24fb93f894043759d5d3121c906a3a4b4ce59b1d9df7b | from unittest import mock
from django.core.exceptions import ValidationError
from django.db import IntegrityError, connection, models
from django.db.models import F
from django.db.models.constraints import BaseConstraint
from django.db.models.functions import Lower
from django.db.transaction import atomic
from django.test import SimpleTestCase, TestCase, skipIfDBFeature, skipUnlessDBFeature
from .models import (
ChildModel,
ChildUniqueConstraintProduct,
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")
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")
self.assertIs(c.contains_expressions, False)
def test_create_sql(self):
c = BaseConstraint("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")
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")
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")
self.assertEqual(
c.get_violation_error_message(), "Constraint “name” is violated."
)
def test_custom_violation_error_message(self):
c = BaseConstraint(
"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(
"base_name",
violation_error_message="custom %(name)s message",
).clone()
self.assertEqual(
constraint.get_violation_error_message(),
"custom base_name message",
)
def test_deconstruction(self):
constraint = BaseConstraint(
"base_name",
violation_error_message="custom %(name)s message",
)
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"},
)
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(check=check1, name="price"),
models.CheckConstraint(check=check1, name="price"),
)
self.assertEqual(models.CheckConstraint(check=check1, name="price"), mock.ANY)
self.assertNotEqual(
models.CheckConstraint(check=check1, name="price"),
models.CheckConstraint(check=check1, name="price2"),
)
self.assertNotEqual(
models.CheckConstraint(check=check1, name="price"),
models.CheckConstraint(check=check2, name="price"),
)
self.assertNotEqual(models.CheckConstraint(check=check1, name="price"), 1)
self.assertNotEqual(
models.CheckConstraint(check=check1, name="price"),
models.CheckConstraint(
check=check1, name="price", violation_error_message="custom error"
),
)
self.assertNotEqual(
models.CheckConstraint(
check=check1, name="price", violation_error_message="custom error"
),
models.CheckConstraint(
check=check1, name="price", violation_error_message="other custom error"
),
)
self.assertEqual(
models.CheckConstraint(
check=check1, name="price", violation_error_message="custom error"
),
models.CheckConstraint(
check=check1, name="price", violation_error_message="custom error"
),
)
def test_repr(self):
constraint = models.CheckConstraint(
check=models.Q(price__gt=models.F("discounted_price")),
name="price_gt_discounted_price",
)
self.assertEqual(
repr(constraint),
"<CheckConstraint: check=(AND: ('price__gt', F(discounted_price))) "
"name='price_gt_discounted_price'>",
)
def test_invalid_check_types(self):
msg = "CheckConstraint.check must be a Q instance or boolean expression."
with self.assertRaisesMessage(TypeError, msg):
models.CheckConstraint(check=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(check=check, name=name)
path, args, kwargs = constraint.deconstruct()
self.assertEqual(path, "django.db.models.CheckConstraint")
self.assertEqual(args, ())
self.assertEqual(kwargs, {"check": 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(check=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_boolean_expressions(self):
constraint = models.CheckConstraint(
check=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(
check=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(
check=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(
check=models.Q(price__gte=0) | models.Q(price__isnull=True),
name="positive_price",
)
constraint.validate(Product, Product())
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",
),
)
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_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_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_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_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):
UniqueConstraintProduct.objects.create(
name=self.p1.name, color=self.p1.color
)
@skipUnlessDBFeature("supports_partial_indexes")
def test_database_constraint_with_condition(self):
UniqueConstraintConditionProduct.objects.create(name="p1")
UniqueConstraintConditionProduct.objects.create(name="p2")
with self.assertRaises(IntegrityError):
UniqueConstraintConditionProduct.objects.create(name="p1")
def test_model_validation(self):
msg = "Unique constraint product with this Name and Color already exists."
with self.assertRaisesMessage(ValidationError, msg):
UniqueConstraintProduct(
name=self.p1.name, color=self.p1.color
).validate_constraints()
@skipUnlessDBFeature("supports_partial_indexes")
def test_model_validation_with_condition(self):
"""
Partial unique constraints are not ignored by
Model.validate_constraints().
"""
obj1 = UniqueConstraintConditionProduct.objects.create(name="p1", color="red")
obj2 = UniqueConstraintConditionProduct.objects.create(name="p2")
UniqueConstraintConditionProduct(
name=obj1.name, color="blue"
).validate_constraints()
msg = "Constraint “name_without_color_uniq” is violated."
with self.assertRaisesMessage(ValidationError, msg):
UniqueConstraintConditionProduct(name=obj2.name).validate_constraints()
def test_validate(self):
constraint = UniqueConstraintProduct._meta.constraints[0]
msg = "Unique constraint product with this Name and Color already exists."
non_unique_product = UniqueConstraintProduct(
name=self.p1.name, color=self.p1.color
)
with self.assertRaisesMessage(ValidationError, msg):
constraint.validate(UniqueConstraintProduct, non_unique_product)
# Null values are ignored.
constraint.validate(
UniqueConstraintProduct,
UniqueConstraintProduct(name=self.p2.name, color=None),
)
# Existing instances have their existing row excluded.
constraint.validate(UniqueConstraintProduct, self.p1)
# Unique fields are excluded.
constraint.validate(
UniqueConstraintProduct,
non_unique_product,
exclude={"name"},
)
constraint.validate(
UniqueConstraintProduct,
non_unique_product,
exclude={"color"},
)
constraint.validate(
UniqueConstraintProduct,
non_unique_product,
exclude={"name", "color"},
)
# Validation on a child instance.
with self.assertRaisesMessage(ValidationError, msg):
constraint.validate(
UniqueConstraintProduct,
ChildUniqueConstraintProduct(name=self.p1.name, color=self.p1.color),
)
@skipUnlessDBFeature("supports_partial_indexes")
def test_validate_condition(self):
p1 = UniqueConstraintConditionProduct.objects.create(name="p1")
constraint = UniqueConstraintConditionProduct._meta.constraints[0]
msg = "Constraint “name_without_color_uniq” is violated."
with self.assertRaisesMessage(ValidationError, msg):
constraint.validate(
UniqueConstraintConditionProduct,
UniqueConstraintConditionProduct(name=p1.name, color=None),
)
# Values not matching condition are ignored.
constraint.validate(
UniqueConstraintConditionProduct,
UniqueConstraintConditionProduct(name=p1.name, color="anything-but-none"),
)
# Existing instances have their existing row excluded.
constraint.validate(UniqueConstraintConditionProduct, p1)
# Unique field is excluded.
constraint.validate(
UniqueConstraintConditionProduct,
UniqueConstraintConditionProduct(name=p1.name, color=None),
exclude={"name"},
)
def test_validate_expression(self):
constraint = models.UniqueConstraint(Lower("name"), name="name_lower_uniq")
msg = "Constraint “name_lower_uniq” is violated."
with self.assertRaisesMessage(ValidationError, msg):
constraint.validate(
UniqueConstraintProduct,
UniqueConstraintProduct(name=self.p1.name.upper()),
)
constraint.validate(
UniqueConstraintProduct,
UniqueConstraintProduct(name="another-name"),
)
# Existing instances have their existing row excluded.
constraint.validate(UniqueConstraintProduct, self.p1)
# Unique field is excluded.
constraint.validate(
UniqueConstraintProduct,
UniqueConstraintProduct(name=self.p1.name.upper()),
exclude={"name"},
)
def test_validate_expression_condition(self):
constraint = models.UniqueConstraint(
Lower("name"),
name="name_lower_without_color_uniq",
condition=models.Q(color__isnull=True),
)
non_unique_product = UniqueConstraintProduct(name=self.p2.name.upper())
msg = "Constraint “name_lower_without_color_uniq” is violated."
with self.assertRaisesMessage(ValidationError, msg):
constraint.validate(UniqueConstraintProduct, non_unique_product)
# Values not matching condition are ignored.
constraint.validate(
UniqueConstraintProduct,
UniqueConstraintProduct(name=self.p1.name, color=self.p1.color),
)
# Existing instances have their existing row excluded.
constraint.validate(UniqueConstraintProduct, self.p2)
# Unique field is excluded.
constraint.validate(
UniqueConstraintProduct,
non_unique_product,
exclude={"name"},
)
# Field from a condition is excluded.
constraint.validate(
UniqueConstraintProduct,
non_unique_product,
exclude={"color"},
)
def test_validate_expression_str(self):
constraint = models.UniqueConstraint("name", name="name_uniq")
msg = "Constraint “name_uniq” is violated."
with self.assertRaisesMessage(ValidationError, msg):
constraint.validate(
UniqueConstraintProduct,
UniqueConstraintProduct(name=self.p1.name),
)
constraint.validate(
UniqueConstraintProduct,
UniqueConstraintProduct(name=self.p1.name),
exclude={"name"},
)
def test_name(self):
constraints = get_constraints(UniqueConstraintProduct._meta.db_table)
expected_name = "name_color_uniq"
self.assertIn(expected_name, constraints)
def test_condition_must_be_q(self):
with self.assertRaisesMessage(
ValueError, "UniqueConstraint.condition must be a Q instance."
):
models.UniqueConstraint(name="uniq", fields=["name"], condition="invalid")
@skipUnlessDBFeature("supports_deferrable_unique_constraints")
def test_initially_deferred_database_constraint(self):
obj_1 = UniqueConstraintDeferrable.objects.create(name="p1", shelf="front")
obj_2 = UniqueConstraintDeferrable.objects.create(name="p2", shelf="back")
def swap():
obj_1.name, obj_2.name = obj_2.name, obj_1.name
obj_1.save()
obj_2.save()
swap()
# Behavior can be changed with SET CONSTRAINTS.
with self.assertRaises(IntegrityError):
with atomic(), connection.cursor() as cursor:
constraint_name = connection.ops.quote_name("name_init_deferred_uniq")
cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % constraint_name)
swap()
@skipUnlessDBFeature("supports_deferrable_unique_constraints")
def test_initially_immediate_database_constraint(self):
obj_1 = UniqueConstraintDeferrable.objects.create(name="p1", shelf="front")
obj_2 = UniqueConstraintDeferrable.objects.create(name="p2", shelf="back")
obj_1.shelf, obj_2.shelf = obj_2.shelf, obj_1.shelf
with self.assertRaises(IntegrityError), atomic():
obj_1.save()
# Behavior can be changed with SET CONSTRAINTS.
with connection.cursor() as cursor:
constraint_name = connection.ops.quote_name("sheld_init_immediate_uniq")
cursor.execute("SET CONSTRAINTS %s DEFERRED" % constraint_name)
obj_1.save()
obj_2.save()
def test_deferrable_with_condition(self):
message = "UniqueConstraint with conditions cannot be deferred."
with self.assertRaisesMessage(ValueError, message):
models.UniqueConstraint(
fields=["name"],
name="name_without_color_unique",
condition=models.Q(color__isnull=True),
deferrable=models.Deferrable.DEFERRED,
)
def test_deferrable_with_include(self):
message = "UniqueConstraint with include fields cannot be deferred."
with self.assertRaisesMessage(ValueError, message):
models.UniqueConstraint(
fields=["name"],
name="name_inc_color_color_unique",
include=["color"],
deferrable=models.Deferrable.DEFERRED,
)
def test_deferrable_with_opclasses(self):
message = "UniqueConstraint with opclasses cannot be deferred."
with self.assertRaisesMessage(ValueError, message):
models.UniqueConstraint(
fields=["name"],
name="name_text_pattern_ops_unique",
opclasses=["text_pattern_ops"],
deferrable=models.Deferrable.DEFERRED,
)
def test_deferrable_with_expressions(self):
message = "UniqueConstraint with expressions cannot be deferred."
with self.assertRaisesMessage(ValueError, message):
models.UniqueConstraint(
Lower("name"),
name="deferred_expression_unique",
deferrable=models.Deferrable.DEFERRED,
)
def test_invalid_defer_argument(self):
message = "UniqueConstraint.deferrable must be a Deferrable instance."
with self.assertRaisesMessage(ValueError, message):
models.UniqueConstraint(
fields=["name"],
name="name_invalid",
deferrable="invalid",
)
@skipUnlessDBFeature(
"supports_table_check_constraints",
"supports_covering_indexes",
)
def test_include_database_constraint(self):
UniqueConstraintInclude.objects.create(name="p1", color="red")
with self.assertRaises(IntegrityError):
UniqueConstraintInclude.objects.create(name="p1", color="blue")
def test_invalid_include_argument(self):
msg = "UniqueConstraint.include must be a list or tuple."
with self.assertRaisesMessage(ValueError, msg):
models.UniqueConstraint(
name="uniq_include",
fields=["field"],
include="other",
)
def test_invalid_opclasses_argument(self):
msg = "UniqueConstraint.opclasses must be a list or tuple."
with self.assertRaisesMessage(ValueError, msg):
models.UniqueConstraint(
name="uniq_opclasses",
fields=["field"],
opclasses="jsonb_path_ops",
)
def test_opclasses_and_fields_same_length(self):
msg = (
"UniqueConstraint.fields and UniqueConstraint.opclasses must have "
"the same number of elements."
)
with self.assertRaisesMessage(ValueError, msg):
models.UniqueConstraint(
name="uniq_opclasses",
fields=["field"],
opclasses=["foo", "bar"],
)
def test_requires_field_or_expression(self):
msg = (
"At least one field or expression is required to define a unique "
"constraint."
)
with self.assertRaisesMessage(ValueError, msg):
models.UniqueConstraint(name="name")
def test_expressions_and_fields_mutually_exclusive(self):
msg = "UniqueConstraint.fields and expressions are mutually exclusive."
with self.assertRaisesMessage(ValueError, msg):
models.UniqueConstraint(Lower("field_1"), fields=["field_2"], name="name")
def test_expressions_with_opclasses(self):
msg = (
"UniqueConstraint.opclasses cannot be used with expressions. Use "
"django.contrib.postgres.indexes.OpClass() instead."
)
with self.assertRaisesMessage(ValueError, msg):
models.UniqueConstraint(
Lower("field"),
name="test_func_opclass",
opclasses=["jsonb_path_ops"],
)
def test_requires_name(self):
msg = "A unique constraint must be named."
with self.assertRaisesMessage(ValueError, msg):
models.UniqueConstraint(fields=["field"])
|
9011f0dfa50426d54790e4300b96802da61cf6836cea7af1228ec69243ab15ce | import collections.abc
import unittest.mock
import warnings
from datetime import datetime
from django.core.paginator import (
EmptyPage,
InvalidPage,
PageNotAnInteger,
Paginator,
UnorderedObjectListWarning,
)
from django.test import SimpleTestCase, TestCase
from .custom import ValidAdjacentNumsPaginator
from .models import Article
class PaginationTests(SimpleTestCase):
"""
Tests for the Paginator and Page classes.
"""
def check_paginator(self, params, output):
"""
Helper method that instantiates a Paginator object from the passed
params and then checks that its attributes match the passed output.
"""
count, num_pages, page_range = output
paginator = Paginator(*params)
self.check_attribute("count", paginator, count, params)
self.check_attribute("num_pages", paginator, num_pages, params)
self.check_attribute("page_range", paginator, page_range, params, coerce=list)
def check_attribute(self, name, paginator, expected, params, coerce=None):
"""
Helper method that checks a single attribute and gives a nice error
message upon test failure.
"""
got = getattr(paginator, name)
if coerce is not None:
got = coerce(got)
self.assertEqual(
expected,
got,
"For '%s', expected %s but got %s. Paginator parameters were: %s"
% (name, expected, got, params),
)
def test_paginator(self):
"""
Tests the paginator attributes using varying inputs.
"""
nine = [1, 2, 3, 4, 5, 6, 7, 8, 9]
ten = nine + [10]
eleven = ten + [11]
tests = (
# Each item is two tuples:
# First tuple is Paginator parameters - object_list, per_page,
# orphans, and allow_empty_first_page.
# Second tuple is resulting Paginator attributes - count,
# num_pages, and page_range.
# Ten items, varying orphans, no empty first page.
((ten, 4, 0, False), (10, 3, [1, 2, 3])),
((ten, 4, 1, False), (10, 3, [1, 2, 3])),
((ten, 4, 2, False), (10, 2, [1, 2])),
((ten, 4, 5, False), (10, 2, [1, 2])),
((ten, 4, 6, False), (10, 1, [1])),
# Ten items, varying orphans, allow empty first page.
((ten, 4, 0, True), (10, 3, [1, 2, 3])),
((ten, 4, 1, True), (10, 3, [1, 2, 3])),
((ten, 4, 2, True), (10, 2, [1, 2])),
((ten, 4, 5, True), (10, 2, [1, 2])),
((ten, 4, 6, True), (10, 1, [1])),
# One item, varying orphans, no empty first page.
(([1], 4, 0, False), (1, 1, [1])),
(([1], 4, 1, False), (1, 1, [1])),
(([1], 4, 2, False), (1, 1, [1])),
# One item, varying orphans, allow empty first page.
(([1], 4, 0, True), (1, 1, [1])),
(([1], 4, 1, True), (1, 1, [1])),
(([1], 4, 2, True), (1, 1, [1])),
# Zero items, varying orphans, no empty first page.
(([], 4, 0, False), (0, 0, [])),
(([], 4, 1, False), (0, 0, [])),
(([], 4, 2, False), (0, 0, [])),
# Zero items, varying orphans, allow empty first page.
(([], 4, 0, True), (0, 1, [1])),
(([], 4, 1, True), (0, 1, [1])),
(([], 4, 2, True), (0, 1, [1])),
# Number if items one less than per_page.
(([], 1, 0, True), (0, 1, [1])),
(([], 1, 0, False), (0, 0, [])),
(([1], 2, 0, True), (1, 1, [1])),
((nine, 10, 0, True), (9, 1, [1])),
# Number if items equal to per_page.
(([1], 1, 0, True), (1, 1, [1])),
(([1, 2], 2, 0, True), (2, 1, [1])),
((ten, 10, 0, True), (10, 1, [1])),
# Number if items one more than per_page.
(([1, 2], 1, 0, True), (2, 2, [1, 2])),
(([1, 2, 3], 2, 0, True), (3, 2, [1, 2])),
((eleven, 10, 0, True), (11, 2, [1, 2])),
# Number if items one more than per_page with one orphan.
(([1, 2], 1, 1, True), (2, 1, [1])),
(([1, 2, 3], 2, 1, True), (3, 1, [1])),
((eleven, 10, 1, True), (11, 1, [1])),
# Non-integer inputs
((ten, "4", 1, False), (10, 3, [1, 2, 3])),
((ten, "4", 1, False), (10, 3, [1, 2, 3])),
((ten, 4, "1", False), (10, 3, [1, 2, 3])),
((ten, 4, "1", False), (10, 3, [1, 2, 3])),
)
for params, output in tests:
self.check_paginator(params, output)
def test_invalid_page_number(self):
"""
Invalid page numbers result in the correct exception being raised.
"""
paginator = Paginator([1, 2, 3], 2)
with self.assertRaises(InvalidPage):
paginator.page(3)
with self.assertRaises(PageNotAnInteger):
paginator.validate_number(None)
with self.assertRaises(PageNotAnInteger):
paginator.validate_number("x")
with self.assertRaises(PageNotAnInteger):
paginator.validate_number(1.2)
def test_float_integer_page(self):
paginator = Paginator([1, 2, 3], 2)
self.assertEqual(paginator.validate_number(1.0), 1)
def test_no_content_allow_empty_first_page(self):
# With no content and allow_empty_first_page=True, 1 is a valid page number
paginator = Paginator([], 2)
self.assertEqual(paginator.validate_number(1), 1)
def test_paginate_misc_classes(self):
class CountContainer:
def count(self):
return 42
# Paginator can be passed other objects with a count() method.
paginator = Paginator(CountContainer(), 10)
self.assertEqual(42, paginator.count)
self.assertEqual(5, paginator.num_pages)
self.assertEqual([1, 2, 3, 4, 5], list(paginator.page_range))
# Paginator can be passed other objects that implement __len__.
class LenContainer:
def __len__(self):
return 42
paginator = Paginator(LenContainer(), 10)
self.assertEqual(42, paginator.count)
self.assertEqual(5, paginator.num_pages)
self.assertEqual([1, 2, 3, 4, 5], list(paginator.page_range))
def test_count_does_not_silence_attribute_error(self):
class AttributeErrorContainer:
def count(self):
raise AttributeError("abc")
with self.assertRaisesMessage(AttributeError, "abc"):
Paginator(AttributeErrorContainer(), 10).count
def test_count_does_not_silence_type_error(self):
class TypeErrorContainer:
def count(self):
raise TypeError("abc")
with self.assertRaisesMessage(TypeError, "abc"):
Paginator(TypeErrorContainer(), 10).count
def check_indexes(self, params, page_num, indexes):
"""
Helper method that instantiates a Paginator object from the passed
params and then checks that the start and end indexes of the passed
page_num match those given as a 2-tuple in indexes.
"""
paginator = Paginator(*params)
if page_num == "first":
page_num = 1
elif page_num == "last":
page_num = paginator.num_pages
page = paginator.page(page_num)
start, end = indexes
msg = "For %s of page %s, expected %s but got %s. Paginator parameters were: %s"
self.assertEqual(
start,
page.start_index(),
msg % ("start index", page_num, start, page.start_index(), params),
)
self.assertEqual(
end,
page.end_index(),
msg % ("end index", page_num, end, page.end_index(), params),
)
def test_page_indexes(self):
"""
Paginator pages have the correct start and end indexes.
"""
ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
tests = (
# Each item is three tuples:
# First tuple is Paginator parameters - object_list, per_page,
# orphans, and allow_empty_first_page.
# Second tuple is the start and end indexes of the first page.
# Third tuple is the start and end indexes of the last page.
# Ten items, varying per_page, no orphans.
((ten, 1, 0, True), (1, 1), (10, 10)),
((ten, 2, 0, True), (1, 2), (9, 10)),
((ten, 3, 0, True), (1, 3), (10, 10)),
((ten, 5, 0, True), (1, 5), (6, 10)),
# Ten items, varying per_page, with orphans.
((ten, 1, 1, True), (1, 1), (9, 10)),
((ten, 1, 2, True), (1, 1), (8, 10)),
((ten, 3, 1, True), (1, 3), (7, 10)),
((ten, 3, 2, True), (1, 3), (7, 10)),
((ten, 3, 4, True), (1, 3), (4, 10)),
((ten, 5, 1, True), (1, 5), (6, 10)),
((ten, 5, 2, True), (1, 5), (6, 10)),
((ten, 5, 5, True), (1, 10), (1, 10)),
# One item, varying orphans, no empty first page.
(([1], 4, 0, False), (1, 1), (1, 1)),
(([1], 4, 1, False), (1, 1), (1, 1)),
(([1], 4, 2, False), (1, 1), (1, 1)),
# One item, varying orphans, allow empty first page.
(([1], 4, 0, True), (1, 1), (1, 1)),
(([1], 4, 1, True), (1, 1), (1, 1)),
(([1], 4, 2, True), (1, 1), (1, 1)),
# Zero items, varying orphans, allow empty first page.
(([], 4, 0, True), (0, 0), (0, 0)),
(([], 4, 1, True), (0, 0), (0, 0)),
(([], 4, 2, True), (0, 0), (0, 0)),
)
for params, first, last in tests:
self.check_indexes(params, "first", first)
self.check_indexes(params, "last", last)
# When no items and no empty first page, we should get EmptyPage error.
with self.assertRaises(EmptyPage):
self.check_indexes(([], 4, 0, False), 1, None)
with self.assertRaises(EmptyPage):
self.check_indexes(([], 4, 1, False), 1, None)
with self.assertRaises(EmptyPage):
self.check_indexes(([], 4, 2, False), 1, None)
def test_page_sequence(self):
"""
A paginator page acts like a standard sequence.
"""
eleven = "abcdefghijk"
page2 = Paginator(eleven, per_page=5, orphans=1).page(2)
self.assertEqual(len(page2), 6)
self.assertIn("k", page2)
self.assertNotIn("a", page2)
self.assertEqual("".join(page2), "fghijk")
self.assertEqual("".join(reversed(page2)), "kjihgf")
def test_get_page_hook(self):
"""
A Paginator subclass can use the ``_get_page`` hook to
return an alternative to the standard Page class.
"""
eleven = "abcdefghijk"
paginator = ValidAdjacentNumsPaginator(eleven, per_page=6)
page1 = paginator.page(1)
page2 = paginator.page(2)
self.assertIsNone(page1.previous_page_number())
self.assertEqual(page1.next_page_number(), 2)
self.assertEqual(page2.previous_page_number(), 1)
self.assertIsNone(page2.next_page_number())
def test_page_range_iterator(self):
"""
Paginator.page_range should be an iterator.
"""
self.assertIsInstance(Paginator([1, 2, 3], 2).page_range, type(range(0)))
def test_get_page(self):
"""
Paginator.get_page() returns a valid page even with invalid page
arguments.
"""
paginator = Paginator([1, 2, 3], 2)
page = paginator.get_page(1)
self.assertEqual(page.number, 1)
self.assertEqual(page.object_list, [1, 2])
# An empty page returns the last page.
self.assertEqual(paginator.get_page(3).number, 2)
# Non-integer page returns the first page.
self.assertEqual(paginator.get_page(None).number, 1)
def test_get_page_empty_object_list(self):
"""Paginator.get_page() with an empty object_list."""
paginator = Paginator([], 2)
# An empty page returns the last page.
self.assertEqual(paginator.get_page(1).number, 1)
self.assertEqual(paginator.get_page(2).number, 1)
# Non-integer page returns the first page.
self.assertEqual(paginator.get_page(None).number, 1)
def test_get_page_empty_object_list_and_allow_empty_first_page_false(self):
"""
Paginator.get_page() raises EmptyPage if allow_empty_first_page=False
and object_list is empty.
"""
paginator = Paginator([], 2, allow_empty_first_page=False)
with self.assertRaises(EmptyPage):
paginator.get_page(1)
def test_paginator_iteration(self):
paginator = Paginator([1, 2, 3], 2)
page_iterator = iter(paginator)
for page, expected in enumerate(([1, 2], [3]), start=1):
with self.subTest(page=page):
self.assertEqual(expected, list(next(page_iterator)))
self.assertEqual(
[str(page) for page in iter(paginator)],
["<Page 1 of 2>", "<Page 2 of 2>"],
)
def test_get_elided_page_range(self):
# Paginator.validate_number() must be called:
paginator = Paginator([1, 2, 3], 2)
with unittest.mock.patch.object(paginator, "validate_number") as mock:
mock.assert_not_called()
list(paginator.get_elided_page_range(2))
mock.assert_called_with(2)
ELLIPSIS = Paginator.ELLIPSIS
# Range is not elided if not enough pages when using default arguments:
paginator = Paginator(range(10 * 100), 100)
page_range = paginator.get_elided_page_range(1)
self.assertIsInstance(page_range, collections.abc.Generator)
self.assertNotIn(ELLIPSIS, page_range)
paginator = Paginator(range(10 * 100 + 1), 100)
self.assertIsInstance(page_range, collections.abc.Generator)
page_range = paginator.get_elided_page_range(1)
self.assertIn(ELLIPSIS, page_range)
# Range should be elided if enough pages when using default arguments:
tests = [
# on_each_side=3, on_ends=2
(1, [1, 2, 3, 4, ELLIPSIS, 49, 50]),
(6, [1, 2, 3, 4, 5, 6, 7, 8, 9, ELLIPSIS, 49, 50]),
(7, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ELLIPSIS, 49, 50]),
(8, [1, 2, ELLIPSIS, 5, 6, 7, 8, 9, 10, 11, ELLIPSIS, 49, 50]),
(43, [1, 2, ELLIPSIS, 40, 41, 42, 43, 44, 45, 46, ELLIPSIS, 49, 50]),
(44, [1, 2, ELLIPSIS, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]),
(45, [1, 2, ELLIPSIS, 42, 43, 44, 45, 46, 47, 48, 49, 50]),
(50, [1, 2, ELLIPSIS, 47, 48, 49, 50]),
]
paginator = Paginator(range(5000), 100)
for number, expected in tests:
with self.subTest(number=number):
page_range = paginator.get_elided_page_range(number)
self.assertIsInstance(page_range, collections.abc.Generator)
self.assertEqual(list(page_range), expected)
# Range is not elided if not enough pages when using custom arguments:
tests = [
(6, 2, 1, 1),
(8, 1, 3, 1),
(8, 4, 0, 1),
(4, 1, 1, 1),
# When on_each_side and on_ends are both <= 1 but not both == 1 it
# is a special case where the range is not elided until an extra
# page is added.
(2, 0, 1, 2),
(2, 1, 0, 2),
(1, 0, 0, 2),
]
for pages, on_each_side, on_ends, elided_after in tests:
for offset in range(elided_after + 1):
with self.subTest(
pages=pages,
offset=elided_after,
on_each_side=on_each_side,
on_ends=on_ends,
):
paginator = Paginator(range((pages + offset) * 100), 100)
page_range = paginator.get_elided_page_range(
1,
on_each_side=on_each_side,
on_ends=on_ends,
)
self.assertIsInstance(page_range, collections.abc.Generator)
if offset < elided_after:
self.assertNotIn(ELLIPSIS, page_range)
else:
self.assertIn(ELLIPSIS, page_range)
# Range should be elided if enough pages when using custom arguments:
tests = [
# on_each_side=2, on_ends=1
(1, 2, 1, [1, 2, 3, ELLIPSIS, 50]),
(4, 2, 1, [1, 2, 3, 4, 5, 6, ELLIPSIS, 50]),
(5, 2, 1, [1, 2, 3, 4, 5, 6, 7, ELLIPSIS, 50]),
(6, 2, 1, [1, ELLIPSIS, 4, 5, 6, 7, 8, ELLIPSIS, 50]),
(45, 2, 1, [1, ELLIPSIS, 43, 44, 45, 46, 47, ELLIPSIS, 50]),
(46, 2, 1, [1, ELLIPSIS, 44, 45, 46, 47, 48, 49, 50]),
(47, 2, 1, [1, ELLIPSIS, 45, 46, 47, 48, 49, 50]),
(50, 2, 1, [1, ELLIPSIS, 48, 49, 50]),
# on_each_side=1, on_ends=3
(1, 1, 3, [1, 2, ELLIPSIS, 48, 49, 50]),
(5, 1, 3, [1, 2, 3, 4, 5, 6, ELLIPSIS, 48, 49, 50]),
(6, 1, 3, [1, 2, 3, 4, 5, 6, 7, ELLIPSIS, 48, 49, 50]),
(7, 1, 3, [1, 2, 3, ELLIPSIS, 6, 7, 8, ELLIPSIS, 48, 49, 50]),
(44, 1, 3, [1, 2, 3, ELLIPSIS, 43, 44, 45, ELLIPSIS, 48, 49, 50]),
(45, 1, 3, [1, 2, 3, ELLIPSIS, 44, 45, 46, 47, 48, 49, 50]),
(46, 1, 3, [1, 2, 3, ELLIPSIS, 45, 46, 47, 48, 49, 50]),
(50, 1, 3, [1, 2, 3, ELLIPSIS, 49, 50]),
# on_each_side=4, on_ends=0
(1, 4, 0, [1, 2, 3, 4, 5, ELLIPSIS]),
(5, 4, 0, [1, 2, 3, 4, 5, 6, 7, 8, 9, ELLIPSIS]),
(6, 4, 0, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ELLIPSIS]),
(7, 4, 0, [ELLIPSIS, 3, 4, 5, 6, 7, 8, 9, 10, 11, ELLIPSIS]),
(44, 4, 0, [ELLIPSIS, 40, 41, 42, 43, 44, 45, 46, 47, 48, ELLIPSIS]),
(45, 4, 0, [ELLIPSIS, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]),
(46, 4, 0, [ELLIPSIS, 42, 43, 44, 45, 46, 47, 48, 49, 50]),
(50, 4, 0, [ELLIPSIS, 46, 47, 48, 49, 50]),
# on_each_side=0, on_ends=1
(1, 0, 1, [1, ELLIPSIS, 50]),
(2, 0, 1, [1, 2, ELLIPSIS, 50]),
(3, 0, 1, [1, 2, 3, ELLIPSIS, 50]),
(4, 0, 1, [1, ELLIPSIS, 4, ELLIPSIS, 50]),
(47, 0, 1, [1, ELLIPSIS, 47, ELLIPSIS, 50]),
(48, 0, 1, [1, ELLIPSIS, 48, 49, 50]),
(49, 0, 1, [1, ELLIPSIS, 49, 50]),
(50, 0, 1, [1, ELLIPSIS, 50]),
# on_each_side=0, on_ends=0
(1, 0, 0, [1, ELLIPSIS]),
(2, 0, 0, [1, 2, ELLIPSIS]),
(3, 0, 0, [ELLIPSIS, 3, ELLIPSIS]),
(48, 0, 0, [ELLIPSIS, 48, ELLIPSIS]),
(49, 0, 0, [ELLIPSIS, 49, 50]),
(50, 0, 0, [ELLIPSIS, 50]),
]
paginator = Paginator(range(5000), 100)
for number, on_each_side, on_ends, expected in tests:
with self.subTest(
number=number, on_each_side=on_each_side, on_ends=on_ends
):
page_range = paginator.get_elided_page_range(
number,
on_each_side=on_each_side,
on_ends=on_ends,
)
self.assertIsInstance(page_range, collections.abc.Generator)
self.assertEqual(list(page_range), expected)
class ModelPaginationTests(TestCase):
"""
Test pagination with Django model instances
"""
@classmethod
def setUpTestData(cls):
# Prepare a list of objects for pagination.
pub_date = datetime(2005, 7, 29)
cls.articles = [
Article.objects.create(headline=f"Article {x}", pub_date=pub_date)
for x in range(1, 10)
]
def test_first_page(self):
paginator = Paginator(Article.objects.order_by("id"), 5)
p = paginator.page(1)
self.assertEqual("<Page 1 of 2>", str(p))
self.assertSequenceEqual(p.object_list, self.articles[:5])
self.assertTrue(p.has_next())
self.assertFalse(p.has_previous())
self.assertTrue(p.has_other_pages())
self.assertEqual(2, p.next_page_number())
with self.assertRaises(InvalidPage):
p.previous_page_number()
self.assertEqual(1, p.start_index())
self.assertEqual(5, p.end_index())
def test_last_page(self):
paginator = Paginator(Article.objects.order_by("id"), 5)
p = paginator.page(2)
self.assertEqual("<Page 2 of 2>", str(p))
self.assertSequenceEqual(p.object_list, self.articles[5:])
self.assertFalse(p.has_next())
self.assertTrue(p.has_previous())
self.assertTrue(p.has_other_pages())
with self.assertRaises(InvalidPage):
p.next_page_number()
self.assertEqual(1, p.previous_page_number())
self.assertEqual(6, p.start_index())
self.assertEqual(9, p.end_index())
def test_page_getitem(self):
"""
Tests proper behavior of a paginator page __getitem__ (queryset
evaluation, slicing, exception raised).
"""
paginator = Paginator(Article.objects.order_by("id"), 5)
p = paginator.page(1)
# object_list queryset is not evaluated by an invalid __getitem__ call.
# (this happens from the template engine when using e.g.:
# {% page_obj.has_previous %}).
self.assertIsNone(p.object_list._result_cache)
msg = "Page indices must be integers or slices, not str."
with self.assertRaisesMessage(TypeError, msg):
p["has_previous"]
self.assertIsNone(p.object_list._result_cache)
self.assertNotIsInstance(p.object_list, list)
# Make sure slicing the Page object with numbers and slice objects work.
self.assertEqual(p[0], self.articles[0])
self.assertSequenceEqual(p[slice(2)], self.articles[:2])
# After __getitem__ is called, object_list is a list
self.assertIsInstance(p.object_list, list)
def test_paginating_unordered_queryset_raises_warning(self):
msg = (
"Pagination may yield inconsistent results with an unordered "
"object_list: <class 'pagination.models.Article'> QuerySet."
)
with self.assertWarnsMessage(UnorderedObjectListWarning, msg) as cm:
Paginator(Article.objects.all(), 5)
# The warning points at the Paginator caller (i.e. the stacklevel
# is appropriate).
self.assertEqual(cm.filename, __file__)
def test_paginating_empty_queryset_does_not_warn(self):
with warnings.catch_warnings(record=True) as recorded:
Paginator(Article.objects.none(), 5)
self.assertEqual(len(recorded), 0)
def test_paginating_unordered_object_list_raises_warning(self):
"""
Unordered object list warning with an object that has an ordered
attribute but not a model attribute.
"""
class ObjectList:
ordered = False
object_list = ObjectList()
msg = (
"Pagination may yield inconsistent results with an unordered "
"object_list: {!r}.".format(object_list)
)
with self.assertWarnsMessage(UnorderedObjectListWarning, msg):
Paginator(object_list, 5)
|
f5a6b89d96bfcc008843819583b8ac9e3640dc7883929c6dfa7d25cddf2c2651 | from django.test import TestCase
from .models import Person
class SaveDeleteHookTests(TestCase):
def test_basic(self):
p = Person(first_name="John", last_name="Smith")
self.assertEqual(p.data, [])
p.save()
self.assertEqual(
p.data,
[
"Before save",
"After save",
],
)
self.assertQuerySetEqual(
Person.objects.all(),
[
"John Smith",
],
str,
)
p.delete()
self.assertEqual(
p.data,
[
"Before save",
"After save",
"Before deletion",
"After deletion",
],
)
self.assertQuerySetEqual(Person.objects.all(), [])
|
0762309d1d147ce7562e2bafa57c42105ce36bc116f8b30f517cd9057da5e90e | from django.core import management
from django.core.management import CommandError
from django.test import TestCase
from .models import Article
class SampleTestCase(TestCase):
fixtures = ["model_package_fixture1.json", "model_package_fixture2.json"]
def test_class_fixtures(self):
"Test cases can load fixture objects into models defined in packages"
self.assertQuerySetEqual(
Article.objects.all(),
[
"Django conquers world!",
"Copyright is fine the way it is",
"Poker has no place on ESPN",
],
lambda a: a.headline,
)
class FixtureTestCase(TestCase):
def test_loaddata(self):
"Fixtures can load data into models defined in packages"
# Load fixture 1. Single JSON file, with two objects
management.call_command("loaddata", "model_package_fixture1.json", verbosity=0)
self.assertQuerySetEqual(
Article.objects.all(),
[
"Time to reform copyright",
"Poker has no place on ESPN",
],
lambda a: a.headline,
)
# Load fixture 2. JSON file imported by default. Overwrites some
# existing objects
management.call_command("loaddata", "model_package_fixture2.json", verbosity=0)
self.assertQuerySetEqual(
Article.objects.all(),
[
"Django conquers world!",
"Copyright is fine the way it is",
"Poker has no place on ESPN",
],
lambda a: a.headline,
)
# Load a fixture that doesn't exist
with self.assertRaisesMessage(
CommandError, "No fixture named 'unknown' found."
):
management.call_command("loaddata", "unknown.json", verbosity=0)
self.assertQuerySetEqual(
Article.objects.all(),
[
"Django conquers world!",
"Copyright is fine the way it is",
"Poker has no place on ESPN",
],
lambda a: a.headline,
)
|
c623bf43f4925f93b9ed27d74893711da19242517120fb287c917e39f49f3448 | import datetime
import pickle
import unittest
import uuid
from collections import namedtuple
from copy import deepcopy
from decimal import Decimal
from unittest import mock
from django.core.exceptions import FieldError
from django.db import DatabaseError, NotSupportedError, connection
from django.db.models import (
AutoField,
Avg,
BinaryField,
BooleanField,
Case,
CharField,
Count,
DateField,
DateTimeField,
DecimalField,
DurationField,
Exists,
Expression,
ExpressionList,
ExpressionWrapper,
F,
FloatField,
Func,
IntegerField,
Max,
Min,
Model,
OrderBy,
OuterRef,
Q,
StdDev,
Subquery,
Sum,
TimeField,
UUIDField,
Value,
Variance,
When,
)
from django.db.models.expressions import (
Col,
Combinable,
CombinedExpression,
RawSQL,
Ref,
)
from django.db.models.functions import (
Coalesce,
Concat,
Left,
Length,
Lower,
Substr,
Upper,
)
from django.db.models.sql import constants
from django.db.models.sql.datastructures import Join
from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature
from django.test.utils import (
Approximate,
CaptureQueriesContext,
isolate_apps,
register_lookup,
)
from django.utils.deprecation import RemovedInDjango50Warning
from django.utils.functional import SimpleLazyObject
from .models import (
UUID,
UUIDPK,
Company,
Employee,
Experiment,
Manager,
Number,
RemoteEmployee,
Result,
SimulationRun,
Time,
)
class BasicExpressionsTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.example_inc = Company.objects.create(
name="Example Inc.",
num_employees=2300,
num_chairs=5,
ceo=Employee.objects.create(firstname="Joe", lastname="Smith", salary=10),
)
cls.foobar_ltd = Company.objects.create(
name="Foobar Ltd.",
num_employees=3,
num_chairs=4,
based_in_eu=True,
ceo=Employee.objects.create(firstname="Frank", lastname="Meyer", salary=20),
)
cls.max = Employee.objects.create(
firstname="Max", lastname="Mustermann", salary=30
)
cls.gmbh = Company.objects.create(
name="Test GmbH", num_employees=32, num_chairs=1, ceo=cls.max
)
def setUp(self):
self.company_query = Company.objects.values(
"name", "num_employees", "num_chairs"
).order_by("name", "num_employees", "num_chairs")
def test_annotate_values_aggregate(self):
companies = (
Company.objects.annotate(
salaries=F("ceo__salary"),
)
.values("num_employees", "salaries")
.aggregate(
result=Sum(
F("salaries") + F("num_employees"), output_field=IntegerField()
),
)
)
self.assertEqual(companies["result"], 2395)
def test_annotate_values_filter(self):
companies = (
Company.objects.annotate(
foo=RawSQL("%s", ["value"]),
)
.filter(foo="value")
.order_by("name")
)
self.assertSequenceEqual(
companies,
[self.example_inc, self.foobar_ltd, self.gmbh],
)
def test_annotate_values_count(self):
companies = Company.objects.annotate(foo=RawSQL("%s", ["value"]))
self.assertEqual(companies.count(), 3)
@skipUnlessDBFeature("supports_boolean_expr_in_select_clause")
def test_filtering_on_annotate_that_uses_q(self):
self.assertEqual(
Company.objects.annotate(
num_employees_check=ExpressionWrapper(
Q(num_employees__gt=3), output_field=BooleanField()
)
)
.filter(num_employees_check=True)
.count(),
2,
)
def test_filtering_on_q_that_is_boolean(self):
self.assertEqual(
Company.objects.filter(
ExpressionWrapper(Q(num_employees__gt=3), output_field=BooleanField())
).count(),
2,
)
def test_filtering_on_rawsql_that_is_boolean(self):
self.assertEqual(
Company.objects.filter(
RawSQL("num_employees > %s", (3,), output_field=BooleanField()),
).count(),
2,
)
def test_filter_inter_attribute(self):
# We can filter on attribute relationships on same model obj, e.g.
# find companies where the number of employees is greater
# than the number of chairs.
self.assertSequenceEqual(
self.company_query.filter(num_employees__gt=F("num_chairs")),
[
{
"num_chairs": 5,
"name": "Example Inc.",
"num_employees": 2300,
},
{"num_chairs": 1, "name": "Test GmbH", "num_employees": 32},
],
)
def test_update(self):
# We can set one field to have the value of another field
# Make sure we have enough chairs
self.company_query.update(num_chairs=F("num_employees"))
self.assertSequenceEqual(
self.company_query,
[
{"num_chairs": 2300, "name": "Example Inc.", "num_employees": 2300},
{"num_chairs": 3, "name": "Foobar Ltd.", "num_employees": 3},
{"num_chairs": 32, "name": "Test GmbH", "num_employees": 32},
],
)
def test_arithmetic(self):
# We can perform arithmetic operations in expressions
# Make sure we have 2 spare chairs
self.company_query.update(num_chairs=F("num_employees") + 2)
self.assertSequenceEqual(
self.company_query,
[
{"num_chairs": 2302, "name": "Example Inc.", "num_employees": 2300},
{"num_chairs": 5, "name": "Foobar Ltd.", "num_employees": 3},
{"num_chairs": 34, "name": "Test GmbH", "num_employees": 32},
],
)
def test_order_of_operations(self):
# Law of order of operations is followed
self.company_query.update(
num_chairs=F("num_employees") + 2 * F("num_employees")
)
self.assertSequenceEqual(
self.company_query,
[
{"num_chairs": 6900, "name": "Example Inc.", "num_employees": 2300},
{"num_chairs": 9, "name": "Foobar Ltd.", "num_employees": 3},
{"num_chairs": 96, "name": "Test GmbH", "num_employees": 32},
],
)
def test_parenthesis_priority(self):
# Law of order of operations can be overridden by parentheses
self.company_query.update(
num_chairs=(F("num_employees") + 2) * F("num_employees")
)
self.assertSequenceEqual(
self.company_query,
[
{"num_chairs": 5294600, "name": "Example Inc.", "num_employees": 2300},
{"num_chairs": 15, "name": "Foobar Ltd.", "num_employees": 3},
{"num_chairs": 1088, "name": "Test GmbH", "num_employees": 32},
],
)
def test_update_with_fk(self):
# ForeignKey can become updated with the value of another ForeignKey.
self.assertEqual(Company.objects.update(point_of_contact=F("ceo")), 3)
self.assertQuerySetEqual(
Company.objects.all(),
["Joe Smith", "Frank Meyer", "Max Mustermann"],
lambda c: str(c.point_of_contact),
ordered=False,
)
def test_update_with_none(self):
Number.objects.create(integer=1, float=1.0)
Number.objects.create(integer=2)
Number.objects.filter(float__isnull=False).update(float=Value(None))
self.assertQuerySetEqual(
Number.objects.all(), [None, None], lambda n: n.float, ordered=False
)
def test_filter_with_join(self):
# F Expressions can also span joins
Company.objects.update(point_of_contact=F("ceo"))
c = Company.objects.first()
c.point_of_contact = Employee.objects.create(
firstname="Guido", lastname="van Rossum"
)
c.save()
self.assertQuerySetEqual(
Company.objects.filter(ceo__firstname=F("point_of_contact__firstname")),
["Foobar Ltd.", "Test GmbH"],
lambda c: c.name,
ordered=False,
)
Company.objects.exclude(ceo__firstname=F("point_of_contact__firstname")).update(
name="foo"
)
self.assertEqual(
Company.objects.exclude(ceo__firstname=F("point_of_contact__firstname"))
.get()
.name,
"foo",
)
msg = "Joined field references are not permitted in this query"
with self.assertRaisesMessage(FieldError, msg):
Company.objects.exclude(
ceo__firstname=F("point_of_contact__firstname")
).update(name=F("point_of_contact__lastname"))
def test_object_update(self):
# F expressions can be used to update attributes on single objects
self.gmbh.num_employees = F("num_employees") + 4
self.gmbh.save()
self.gmbh.refresh_from_db()
self.assertEqual(self.gmbh.num_employees, 36)
def test_new_object_save(self):
# We should be able to use Funcs when inserting new data
test_co = Company(
name=Lower(Value("UPPER")), num_employees=32, num_chairs=1, ceo=self.max
)
test_co.save()
test_co.refresh_from_db()
self.assertEqual(test_co.name, "upper")
def test_new_object_create(self):
test_co = Company.objects.create(
name=Lower(Value("UPPER")), num_employees=32, num_chairs=1, ceo=self.max
)
test_co.refresh_from_db()
self.assertEqual(test_co.name, "upper")
def test_object_create_with_aggregate(self):
# Aggregates are not allowed when inserting new data
msg = (
"Aggregate functions are not allowed in this query "
"(num_employees=Max(Value(1)))."
)
with self.assertRaisesMessage(FieldError, msg):
Company.objects.create(
name="Company",
num_employees=Max(Value(1)),
num_chairs=1,
ceo=Employee.objects.create(
firstname="Just", lastname="Doit", salary=30
),
)
def test_object_update_fk(self):
# F expressions cannot be used to update attributes which are foreign
# keys, or attributes which involve joins.
test_gmbh = Company.objects.get(pk=self.gmbh.pk)
msg = 'F(ceo)": "Company.point_of_contact" must be a "Employee" instance.'
with self.assertRaisesMessage(ValueError, msg):
test_gmbh.point_of_contact = F("ceo")
test_gmbh.point_of_contact = self.gmbh.ceo
test_gmbh.save()
test_gmbh.name = F("ceo__lastname")
msg = "Joined field references are not permitted in this query"
with self.assertRaisesMessage(FieldError, msg):
test_gmbh.save()
def test_update_inherited_field_value(self):
msg = "Joined field references are not permitted in this query"
with self.assertRaisesMessage(FieldError, msg):
RemoteEmployee.objects.update(adjusted_salary=F("salary") * 5)
def test_object_update_unsaved_objects(self):
# F expressions cannot be used to update attributes on objects which do
# not yet exist in the database
acme = Company(
name="The Acme Widget Co.", num_employees=12, num_chairs=5, ceo=self.max
)
acme.num_employees = F("num_employees") + 16
msg = (
'Failed to insert expression "Col(expressions_company, '
'expressions.Company.num_employees) + Value(16)" on '
"expressions.Company.num_employees. F() expressions can only be "
"used to update, not to insert."
)
with self.assertRaisesMessage(ValueError, msg):
acme.save()
acme.num_employees = 12
acme.name = Lower(F("name"))
msg = (
'Failed to insert expression "Lower(Col(expressions_company, '
'expressions.Company.name))" on expressions.Company.name. F() '
"expressions can only be used to update, not to insert."
)
with self.assertRaisesMessage(ValueError, msg):
acme.save()
def test_ticket_11722_iexact_lookup(self):
Employee.objects.create(firstname="John", lastname="Doe")
test = Employee.objects.create(firstname="Test", lastname="test")
queryset = Employee.objects.filter(firstname__iexact=F("lastname"))
self.assertSequenceEqual(queryset, [test])
def test_ticket_16731_startswith_lookup(self):
Employee.objects.create(firstname="John", lastname="Doe")
e2 = Employee.objects.create(firstname="Jack", lastname="Jackson")
e3 = Employee.objects.create(firstname="Jack", lastname="jackson")
self.assertSequenceEqual(
Employee.objects.filter(lastname__startswith=F("firstname")),
[e2, e3] if connection.features.has_case_insensitive_like else [e2],
)
qs = Employee.objects.filter(lastname__istartswith=F("firstname")).order_by(
"pk"
)
self.assertSequenceEqual(qs, [e2, e3])
def test_ticket_18375_join_reuse(self):
# Reverse multijoin F() references and the lookup target the same join.
# Pre #18375 the F() join was generated first and the lookup couldn't
# reuse that join.
qs = Employee.objects.filter(
company_ceo_set__num_chairs=F("company_ceo_set__num_employees")
)
self.assertEqual(str(qs.query).count("JOIN"), 1)
def test_ticket_18375_kwarg_ordering(self):
# The next query was dict-randomization dependent - if the "gte=1"
# was seen first, then the F() will reuse the join generated by the
# gte lookup, if F() was seen first, then it generated a join the
# other lookups could not reuse.
qs = Employee.objects.filter(
company_ceo_set__num_chairs=F("company_ceo_set__num_employees"),
company_ceo_set__num_chairs__gte=1,
)
self.assertEqual(str(qs.query).count("JOIN"), 1)
def test_ticket_18375_kwarg_ordering_2(self):
# Another similar case for F() than above. Now we have the same join
# in two filter kwargs, one in the lhs lookup, one in F. Here pre
# #18375 the amount of joins generated was random if dict
# randomization was enabled, that is the generated query dependent
# on which clause was seen first.
qs = Employee.objects.filter(
company_ceo_set__num_employees=F("pk"),
pk=F("company_ceo_set__num_employees"),
)
self.assertEqual(str(qs.query).count("JOIN"), 1)
def test_ticket_18375_chained_filters(self):
# F() expressions do not reuse joins from previous filter.
qs = Employee.objects.filter(company_ceo_set__num_employees=F("pk")).filter(
company_ceo_set__num_employees=F("company_ceo_set__num_employees")
)
self.assertEqual(str(qs.query).count("JOIN"), 2)
def test_order_by_exists(self):
mary = Employee.objects.create(
firstname="Mary", lastname="Mustermann", salary=20
)
mustermanns_by_seniority = Employee.objects.filter(
lastname="Mustermann"
).order_by(
# Order by whether the employee is the CEO of a company
Exists(Company.objects.filter(ceo=OuterRef("pk"))).desc()
)
self.assertSequenceEqual(mustermanns_by_seniority, [self.max, mary])
def test_order_by_multiline_sql(self):
raw_order_by = (
RawSQL(
"""
CASE WHEN num_employees > 1000
THEN num_chairs
ELSE 0 END
""",
[],
).desc(),
RawSQL(
"""
CASE WHEN num_chairs > 1
THEN 1
ELSE 0 END
""",
[],
).asc(),
)
for qs in (
Company.objects.all(),
Company.objects.distinct(),
):
with self.subTest(qs=qs):
self.assertSequenceEqual(
qs.order_by(*raw_order_by),
[self.example_inc, self.gmbh, self.foobar_ltd],
)
def test_outerref(self):
inner = Company.objects.filter(point_of_contact=OuterRef("pk"))
msg = (
"This queryset contains a reference to an outer query and may only "
"be used in a subquery."
)
with self.assertRaisesMessage(ValueError, msg):
inner.exists()
outer = Employee.objects.annotate(is_point_of_contact=Exists(inner))
self.assertIs(outer.exists(), True)
def test_exist_single_field_output_field(self):
queryset = Company.objects.values("pk")
self.assertIsInstance(Exists(queryset).output_field, BooleanField)
def test_subquery(self):
Company.objects.filter(name="Example Inc.").update(
point_of_contact=Employee.objects.get(firstname="Joe", lastname="Smith"),
ceo=self.max,
)
Employee.objects.create(firstname="Bob", lastname="Brown", salary=40)
qs = (
Employee.objects.annotate(
is_point_of_contact=Exists(
Company.objects.filter(point_of_contact=OuterRef("pk"))
),
is_not_point_of_contact=~Exists(
Company.objects.filter(point_of_contact=OuterRef("pk"))
),
is_ceo_of_small_company=Exists(
Company.objects.filter(num_employees__lt=200, ceo=OuterRef("pk"))
),
is_ceo_small_2=~~Exists(
Company.objects.filter(num_employees__lt=200, ceo=OuterRef("pk"))
),
largest_company=Subquery(
Company.objects.order_by("-num_employees")
.filter(Q(ceo=OuterRef("pk")) | Q(point_of_contact=OuterRef("pk")))
.values("name")[:1],
output_field=CharField(),
),
)
.values(
"firstname",
"is_point_of_contact",
"is_not_point_of_contact",
"is_ceo_of_small_company",
"is_ceo_small_2",
"largest_company",
)
.order_by("firstname")
)
results = list(qs)
# Could use Coalesce(subq, Value('')) instead except for the bug in
# cx_Oracle mentioned in #23843.
bob = results[0]
if (
bob["largest_company"] == ""
and connection.features.interprets_empty_strings_as_nulls
):
bob["largest_company"] = None
self.assertEqual(
results,
[
{
"firstname": "Bob",
"is_point_of_contact": False,
"is_not_point_of_contact": True,
"is_ceo_of_small_company": False,
"is_ceo_small_2": False,
"largest_company": None,
},
{
"firstname": "Frank",
"is_point_of_contact": False,
"is_not_point_of_contact": True,
"is_ceo_of_small_company": True,
"is_ceo_small_2": True,
"largest_company": "Foobar Ltd.",
},
{
"firstname": "Joe",
"is_point_of_contact": True,
"is_not_point_of_contact": False,
"is_ceo_of_small_company": False,
"is_ceo_small_2": False,
"largest_company": "Example Inc.",
},
{
"firstname": "Max",
"is_point_of_contact": False,
"is_not_point_of_contact": True,
"is_ceo_of_small_company": True,
"is_ceo_small_2": True,
"largest_company": "Example Inc.",
},
],
)
# A less elegant way to write the same query: this uses a LEFT OUTER
# JOIN and an IS NULL, inside a WHERE NOT IN which is probably less
# efficient than EXISTS.
self.assertCountEqual(
qs.filter(is_point_of_contact=True).values("pk"),
Employee.objects.exclude(company_point_of_contact_set=None).values("pk"),
)
def test_subquery_eq(self):
qs = Employee.objects.annotate(
is_ceo=Exists(Company.objects.filter(ceo=OuterRef("pk"))),
is_point_of_contact=Exists(
Company.objects.filter(point_of_contact=OuterRef("pk")),
),
small_company=Exists(
queryset=Company.objects.filter(num_employees__lt=200),
),
).filter(is_ceo=True, is_point_of_contact=False, small_company=True)
self.assertNotEqual(
qs.query.annotations["is_ceo"],
qs.query.annotations["is_point_of_contact"],
)
self.assertNotEqual(
qs.query.annotations["is_ceo"],
qs.query.annotations["small_company"],
)
def test_subquery_sql(self):
employees = Employee.objects.all()
employees_subquery = Subquery(employees)
self.assertIs(employees_subquery.query.subquery, True)
self.assertIs(employees.query.subquery, False)
compiler = employees_subquery.query.get_compiler(connection=connection)
sql, _ = employees_subquery.as_sql(compiler, connection)
self.assertIn("(SELECT ", sql)
def test_in_subquery(self):
# This is a contrived test (and you really wouldn't write this query),
# but it is a succinct way to test the __in=Subquery() construct.
small_companies = Company.objects.filter(num_employees__lt=200).values("pk")
subquery_test = Company.objects.filter(pk__in=Subquery(small_companies))
self.assertCountEqual(subquery_test, [self.foobar_ltd, self.gmbh])
subquery_test2 = Company.objects.filter(
pk=Subquery(small_companies.filter(num_employees=3))
)
self.assertCountEqual(subquery_test2, [self.foobar_ltd])
def test_uuid_pk_subquery(self):
u = UUIDPK.objects.create()
UUID.objects.create(uuid_fk=u)
qs = UUIDPK.objects.filter(id__in=Subquery(UUID.objects.values("uuid_fk__id")))
self.assertCountEqual(qs, [u])
def test_nested_subquery(self):
inner = Company.objects.filter(point_of_contact=OuterRef("pk"))
outer = Employee.objects.annotate(is_point_of_contact=Exists(inner))
contrived = Employee.objects.annotate(
is_point_of_contact=Subquery(
outer.filter(pk=OuterRef("pk")).values("is_point_of_contact"),
output_field=BooleanField(),
),
)
self.assertCountEqual(contrived.values_list(), outer.values_list())
def test_nested_subquery_join_outer_ref(self):
inner = Employee.objects.filter(pk=OuterRef("ceo__pk")).values("pk")
qs = Employee.objects.annotate(
ceo_company=Subquery(
Company.objects.filter(
ceo__in=inner,
ceo__pk=OuterRef("pk"),
).values("pk"),
),
)
self.assertSequenceEqual(
qs.values_list("ceo_company", flat=True),
[self.example_inc.pk, self.foobar_ltd.pk, self.gmbh.pk],
)
def test_nested_subquery_outer_ref_2(self):
first = Time.objects.create(time="09:00")
second = Time.objects.create(time="17:00")
third = Time.objects.create(time="21:00")
SimulationRun.objects.bulk_create(
[
SimulationRun(start=first, end=second, midpoint="12:00"),
SimulationRun(start=first, end=third, midpoint="15:00"),
SimulationRun(start=second, end=first, midpoint="00:00"),
]
)
inner = Time.objects.filter(
time=OuterRef(OuterRef("time")), pk=OuterRef("start")
).values("time")
middle = SimulationRun.objects.annotate(other=Subquery(inner)).values("other")[
:1
]
outer = Time.objects.annotate(other=Subquery(middle, output_field=TimeField()))
# This is a contrived example. It exercises the double OuterRef form.
self.assertCountEqual(outer, [first, second, third])
def test_nested_subquery_outer_ref_with_autofield(self):
first = Time.objects.create(time="09:00")
second = Time.objects.create(time="17:00")
SimulationRun.objects.create(start=first, end=second, midpoint="12:00")
inner = SimulationRun.objects.filter(start=OuterRef(OuterRef("pk"))).values(
"start"
)
middle = Time.objects.annotate(other=Subquery(inner)).values("other")[:1]
outer = Time.objects.annotate(
other=Subquery(middle, output_field=IntegerField())
)
# This exercises the double OuterRef form with AutoField as pk.
self.assertCountEqual(outer, [first, second])
def test_annotations_within_subquery(self):
Company.objects.filter(num_employees__lt=50).update(
ceo=Employee.objects.get(firstname="Frank")
)
inner = (
Company.objects.filter(ceo=OuterRef("pk"))
.values("ceo")
.annotate(total_employees=Sum("num_employees"))
.values("total_employees")
)
outer = Employee.objects.annotate(total_employees=Subquery(inner)).filter(
salary__lte=Subquery(inner)
)
self.assertSequenceEqual(
outer.order_by("-total_employees").values("salary", "total_employees"),
[
{"salary": 10, "total_employees": 2300},
{"salary": 20, "total_employees": 35},
],
)
def test_subquery_references_joined_table_twice(self):
inner = Company.objects.filter(
num_chairs__gte=OuterRef("ceo__salary"),
num_employees__gte=OuterRef("point_of_contact__salary"),
)
# Another contrived example (there is no need to have a subquery here)
outer = Company.objects.filter(pk__in=Subquery(inner.values("pk")))
self.assertFalse(outer.exists())
def test_subquery_filter_by_aggregate(self):
Number.objects.create(integer=1000, float=1.2)
Employee.objects.create(salary=1000)
qs = Number.objects.annotate(
min_valuable_count=Subquery(
Employee.objects.filter(
salary=OuterRef("integer"),
)
.annotate(cnt=Count("salary"))
.filter(cnt__gt=0)
.values("cnt")[:1]
),
)
self.assertEqual(qs.get().float, 1.2)
def test_subquery_filter_by_lazy(self):
self.max.manager = Manager.objects.create(name="Manager")
self.max.save()
max_manager = SimpleLazyObject(
lambda: Manager.objects.get(pk=self.max.manager.pk)
)
qs = Company.objects.annotate(
ceo_manager=Subquery(
Employee.objects.filter(
lastname=OuterRef("ceo__lastname"),
).values("manager"),
),
).filter(ceo_manager=max_manager)
self.assertEqual(qs.get(), self.gmbh)
def test_aggregate_subquery_annotation(self):
with self.assertNumQueries(1) as ctx:
aggregate = Company.objects.annotate(
ceo_salary=Subquery(
Employee.objects.filter(
id=OuterRef("ceo_id"),
).values("salary")
),
).aggregate(
ceo_salary_gt_20=Count("pk", filter=Q(ceo_salary__gt=20)),
)
self.assertEqual(aggregate, {"ceo_salary_gt_20": 1})
# Aggregation over a subquery annotation doesn't annotate the subquery
# twice in the inner query.
sql = ctx.captured_queries[0]["sql"]
self.assertLessEqual(sql.count("SELECT"), 3)
# GROUP BY isn't required to aggregate over a query that doesn't
# contain nested aggregates.
self.assertNotIn("GROUP BY", sql)
@skipUnlessDBFeature("supports_over_clause")
def test_aggregate_rawsql_annotation(self):
with self.assertNumQueries(1) as ctx:
aggregate = Company.objects.annotate(
salary=RawSQL("SUM(num_chairs) OVER (ORDER BY num_employees)", []),
).aggregate(
count=Count("pk"),
)
self.assertEqual(aggregate, {"count": 3})
sql = ctx.captured_queries[0]["sql"]
self.assertNotIn("GROUP BY", sql)
def test_explicit_output_field(self):
class FuncA(Func):
output_field = CharField()
class FuncB(Func):
pass
expr = FuncB(FuncA())
self.assertEqual(expr.output_field, FuncA.output_field)
def test_outerref_mixed_case_table_name(self):
inner = Result.objects.filter(result_time__gte=OuterRef("experiment__assigned"))
outer = Result.objects.filter(pk__in=Subquery(inner.values("pk")))
self.assertFalse(outer.exists())
def test_outerref_with_operator(self):
inner = Company.objects.filter(num_employees=OuterRef("ceo__salary") + 2)
outer = Company.objects.filter(pk__in=Subquery(inner.values("pk")))
self.assertEqual(outer.get().name, "Test GmbH")
def test_nested_outerref_with_function(self):
self.gmbh.point_of_contact = Employee.objects.get(lastname="Meyer")
self.gmbh.save()
inner = Employee.objects.filter(
lastname__startswith=Left(OuterRef(OuterRef("lastname")), 1),
)
qs = Employee.objects.annotate(
ceo_company=Subquery(
Company.objects.filter(
point_of_contact__in=inner,
ceo__pk=OuterRef("pk"),
).values("name"),
),
).filter(ceo_company__isnull=False)
self.assertEqual(qs.get().ceo_company, "Test GmbH")
def test_annotation_with_outerref(self):
gmbh_salary = Company.objects.annotate(
max_ceo_salary_raise=Subquery(
Company.objects.annotate(
salary_raise=OuterRef("num_employees") + F("num_employees"),
)
.order_by("-salary_raise")
.values("salary_raise")[:1],
output_field=IntegerField(),
),
).get(pk=self.gmbh.pk)
self.assertEqual(gmbh_salary.max_ceo_salary_raise, 2332)
def test_annotation_with_nested_outerref(self):
self.gmbh.point_of_contact = Employee.objects.get(lastname="Meyer")
self.gmbh.save()
inner = Employee.objects.annotate(
outer_lastname=OuterRef(OuterRef("lastname")),
).filter(lastname__startswith=Left("outer_lastname", 1))
qs = Employee.objects.annotate(
ceo_company=Subquery(
Company.objects.filter(
point_of_contact__in=inner,
ceo__pk=OuterRef("pk"),
).values("name"),
),
).filter(ceo_company__isnull=False)
self.assertEqual(qs.get().ceo_company, "Test GmbH")
def test_pickle_expression(self):
expr = Value(1)
expr.convert_value # populate cached property
self.assertEqual(pickle.loads(pickle.dumps(expr)), expr)
def test_incorrect_field_in_F_expression(self):
with self.assertRaisesMessage(
FieldError, "Cannot resolve keyword 'nope' into field."
):
list(Employee.objects.filter(firstname=F("nope")))
def test_incorrect_joined_field_in_F_expression(self):
with self.assertRaisesMessage(
FieldError, "Cannot resolve keyword 'nope' into field."
):
list(Company.objects.filter(ceo__pk=F("point_of_contact__nope")))
def test_exists_in_filter(self):
inner = Company.objects.filter(ceo=OuterRef("pk")).values("pk")
qs1 = Employee.objects.filter(Exists(inner))
qs2 = Employee.objects.annotate(found=Exists(inner)).filter(found=True)
self.assertCountEqual(qs1, qs2)
self.assertFalse(Employee.objects.exclude(Exists(inner)).exists())
self.assertCountEqual(qs2, Employee.objects.exclude(~Exists(inner)))
def test_subquery_in_filter(self):
inner = Company.objects.filter(ceo=OuterRef("pk")).values("based_in_eu")
self.assertSequenceEqual(
Employee.objects.filter(Subquery(inner)),
[self.foobar_ltd.ceo],
)
def test_subquery_group_by_outerref_in_filter(self):
inner = (
Company.objects.annotate(
employee=OuterRef("pk"),
)
.values("employee")
.annotate(
min_num_chairs=Min("num_chairs"),
)
.values("ceo")
)
self.assertIs(Employee.objects.filter(pk__in=Subquery(inner)).exists(), True)
def test_case_in_filter_if_boolean_output_field(self):
is_ceo = Company.objects.filter(ceo=OuterRef("pk"))
is_poc = Company.objects.filter(point_of_contact=OuterRef("pk"))
qs = Employee.objects.filter(
Case(
When(Exists(is_ceo), then=True),
When(Exists(is_poc), then=True),
default=False,
output_field=BooleanField(),
),
)
self.assertCountEqual(qs, [self.example_inc.ceo, self.foobar_ltd.ceo, self.max])
def test_boolean_expression_combined(self):
is_ceo = Company.objects.filter(ceo=OuterRef("pk"))
is_poc = Company.objects.filter(point_of_contact=OuterRef("pk"))
self.gmbh.point_of_contact = self.max
self.gmbh.save()
self.assertCountEqual(
Employee.objects.filter(Exists(is_ceo) | Exists(is_poc)),
[self.example_inc.ceo, self.foobar_ltd.ceo, self.max],
)
self.assertCountEqual(
Employee.objects.filter(Exists(is_ceo) & Exists(is_poc)),
[self.max],
)
self.assertCountEqual(
Employee.objects.filter(Exists(is_ceo) & Q(salary__gte=30)),
[self.max],
)
self.assertCountEqual(
Employee.objects.filter(Exists(is_poc) | Q(salary__lt=15)),
[self.example_inc.ceo, self.max],
)
self.assertCountEqual(
Employee.objects.filter(Q(salary__gte=30) & Exists(is_ceo)),
[self.max],
)
self.assertCountEqual(
Employee.objects.filter(Q(salary__lt=15) | Exists(is_poc)),
[self.example_inc.ceo, self.max],
)
def test_boolean_expression_combined_with_empty_Q(self):
is_poc = Company.objects.filter(point_of_contact=OuterRef("pk"))
self.gmbh.point_of_contact = self.max
self.gmbh.save()
tests = [
Exists(is_poc) & Q(),
Q() & Exists(is_poc),
Exists(is_poc) | Q(),
Q() | Exists(is_poc),
Q(Exists(is_poc)) & Q(),
Q() & Q(Exists(is_poc)),
Q(Exists(is_poc)) | Q(),
Q() | Q(Exists(is_poc)),
]
for conditions in tests:
with self.subTest(conditions):
self.assertCountEqual(Employee.objects.filter(conditions), [self.max])
def test_boolean_expression_in_Q(self):
is_poc = Company.objects.filter(point_of_contact=OuterRef("pk"))
self.gmbh.point_of_contact = self.max
self.gmbh.save()
self.assertCountEqual(Employee.objects.filter(Q(Exists(is_poc))), [self.max])
class IterableLookupInnerExpressionsTests(TestCase):
@classmethod
def setUpTestData(cls):
ceo = Employee.objects.create(firstname="Just", lastname="Doit", salary=30)
# MySQL requires that the values calculated for expressions don't pass
# outside of the field's range, so it's inconvenient to use the values
# in the more general tests.
cls.c5020 = Company.objects.create(
name="5020 Ltd", num_employees=50, num_chairs=20, ceo=ceo
)
cls.c5040 = Company.objects.create(
name="5040 Ltd", num_employees=50, num_chairs=40, ceo=ceo
)
cls.c5050 = Company.objects.create(
name="5050 Ltd", num_employees=50, num_chairs=50, ceo=ceo
)
cls.c5060 = Company.objects.create(
name="5060 Ltd", num_employees=50, num_chairs=60, ceo=ceo
)
cls.c99300 = Company.objects.create(
name="99300 Ltd", num_employees=99, num_chairs=300, ceo=ceo
)
def test_in_lookup_allows_F_expressions_and_expressions_for_integers(self):
# __in lookups can use F() expressions for integers.
queryset = Company.objects.filter(num_employees__in=([F("num_chairs") - 10]))
self.assertSequenceEqual(queryset, [self.c5060])
self.assertCountEqual(
Company.objects.filter(
num_employees__in=([F("num_chairs") - 10, F("num_chairs") + 10])
),
[self.c5040, self.c5060],
)
self.assertCountEqual(
Company.objects.filter(
num_employees__in=(
[F("num_chairs") - 10, F("num_chairs"), F("num_chairs") + 10]
)
),
[self.c5040, self.c5050, self.c5060],
)
def test_expressions_in_lookups_join_choice(self):
midpoint = datetime.time(13, 0)
t1 = Time.objects.create(time=datetime.time(12, 0))
t2 = Time.objects.create(time=datetime.time(14, 0))
s1 = SimulationRun.objects.create(start=t1, end=t2, midpoint=midpoint)
SimulationRun.objects.create(start=t1, end=None, midpoint=midpoint)
SimulationRun.objects.create(start=None, end=t2, midpoint=midpoint)
SimulationRun.objects.create(start=None, end=None, midpoint=midpoint)
queryset = SimulationRun.objects.filter(
midpoint__range=[F("start__time"), F("end__time")]
)
self.assertSequenceEqual(queryset, [s1])
for alias in queryset.query.alias_map.values():
if isinstance(alias, Join):
self.assertEqual(alias.join_type, constants.INNER)
queryset = SimulationRun.objects.exclude(
midpoint__range=[F("start__time"), F("end__time")]
)
self.assertQuerySetEqual(queryset, [], ordered=False)
for alias in queryset.query.alias_map.values():
if isinstance(alias, Join):
self.assertEqual(alias.join_type, constants.LOUTER)
def test_range_lookup_allows_F_expressions_and_expressions_for_integers(self):
# Range lookups can use F() expressions for integers.
Company.objects.filter(num_employees__exact=F("num_chairs"))
self.assertCountEqual(
Company.objects.filter(num_employees__range=(F("num_chairs"), 100)),
[self.c5020, self.c5040, self.c5050],
)
self.assertCountEqual(
Company.objects.filter(
num_employees__range=(F("num_chairs") - 10, F("num_chairs") + 10)
),
[self.c5040, self.c5050, self.c5060],
)
self.assertCountEqual(
Company.objects.filter(num_employees__range=(F("num_chairs") - 10, 100)),
[self.c5020, self.c5040, self.c5050, self.c5060],
)
self.assertCountEqual(
Company.objects.filter(num_employees__range=(1, 100)),
[self.c5020, self.c5040, self.c5050, self.c5060, self.c99300],
)
def test_range_lookup_namedtuple(self):
EmployeeRange = namedtuple("EmployeeRange", ["minimum", "maximum"])
qs = Company.objects.filter(
num_employees__range=EmployeeRange(minimum=51, maximum=100),
)
self.assertSequenceEqual(qs, [self.c99300])
@unittest.skipUnless(
connection.vendor == "sqlite",
"This defensive test only works on databases that don't validate parameter "
"types",
)
def test_expressions_not_introduce_sql_injection_via_untrusted_string_inclusion(
self,
):
"""
This tests that SQL injection isn't possible using compilation of
expressions in iterable filters, as their compilation happens before
the main query compilation. It's limited to SQLite, as PostgreSQL,
Oracle and other vendors have defense in depth against this by type
checking. Testing against SQLite (the most permissive of the built-in
databases) demonstrates that the problem doesn't exist while keeping
the test simple.
"""
queryset = Company.objects.filter(name__in=[F("num_chairs") + "1)) OR ((1==1"])
self.assertQuerySetEqual(queryset, [], ordered=False)
def test_in_lookup_allows_F_expressions_and_expressions_for_datetimes(self):
start = datetime.datetime(2016, 2, 3, 15, 0, 0)
end = datetime.datetime(2016, 2, 5, 15, 0, 0)
experiment_1 = Experiment.objects.create(
name="Integrity testing",
assigned=start.date(),
start=start,
end=end,
completed=end.date(),
estimated_time=end - start,
)
experiment_2 = Experiment.objects.create(
name="Taste testing",
assigned=start.date(),
start=start,
end=end,
completed=end.date(),
estimated_time=end - start,
)
r1 = Result.objects.create(
experiment=experiment_1,
result_time=datetime.datetime(2016, 2, 4, 15, 0, 0),
)
Result.objects.create(
experiment=experiment_1,
result_time=datetime.datetime(2016, 3, 10, 2, 0, 0),
)
Result.objects.create(
experiment=experiment_2,
result_time=datetime.datetime(2016, 1, 8, 5, 0, 0),
)
within_experiment_time = [F("experiment__start"), F("experiment__end")]
queryset = Result.objects.filter(result_time__range=within_experiment_time)
self.assertSequenceEqual(queryset, [r1])
class FTests(SimpleTestCase):
def test_deepcopy(self):
f = F("foo")
g = deepcopy(f)
self.assertEqual(f.name, g.name)
def test_deconstruct(self):
f = F("name")
path, args, kwargs = f.deconstruct()
self.assertEqual(path, "django.db.models.F")
self.assertEqual(args, (f.name,))
self.assertEqual(kwargs, {})
def test_equal(self):
f = F("name")
same_f = F("name")
other_f = F("username")
self.assertEqual(f, same_f)
self.assertNotEqual(f, other_f)
def test_hash(self):
d = {F("name"): "Bob"}
self.assertIn(F("name"), d)
self.assertEqual(d[F("name")], "Bob")
def test_not_equal_Value(self):
f = F("name")
value = Value("name")
self.assertNotEqual(f, value)
self.assertNotEqual(value, f)
class ExpressionsTests(TestCase):
def test_F_reuse(self):
f = F("id")
n = Number.objects.create(integer=-1)
c = Company.objects.create(
name="Example Inc.",
num_employees=2300,
num_chairs=5,
ceo=Employee.objects.create(firstname="Joe", lastname="Smith"),
)
c_qs = Company.objects.filter(id=f)
self.assertEqual(c_qs.get(), c)
# Reuse the same F-object for another queryset
n_qs = Number.objects.filter(id=f)
self.assertEqual(n_qs.get(), n)
# The original query still works correctly
self.assertEqual(c_qs.get(), c)
def test_patterns_escape(self):
r"""
Special characters (e.g. %, _ and \) stored in database are
properly escaped when using a pattern lookup with an expression
refs #16731
"""
Employee.objects.bulk_create(
[
Employee(firstname="Johnny", lastname="%John"),
Employee(firstname="Jean-Claude", lastname="Claud_"),
Employee(firstname="Jean-Claude", lastname="Claude%"),
Employee(firstname="Johnny", lastname="Joh\\n"),
Employee(firstname="Johnny", lastname="_ohn"),
]
)
claude = Employee.objects.create(firstname="Jean-Claude", lastname="Claude")
john = Employee.objects.create(firstname="Johnny", lastname="John")
john_sign = Employee.objects.create(firstname="%Joh\\nny", lastname="%Joh\\n")
self.assertCountEqual(
Employee.objects.filter(firstname__contains=F("lastname")),
[john_sign, john, claude],
)
self.assertCountEqual(
Employee.objects.filter(firstname__startswith=F("lastname")),
[john_sign, john],
)
self.assertSequenceEqual(
Employee.objects.filter(firstname__endswith=F("lastname")),
[claude],
)
def test_insensitive_patterns_escape(self):
r"""
Special characters (e.g. %, _ and \) stored in database are
properly escaped when using a case insensitive pattern lookup with an
expression -- refs #16731
"""
Employee.objects.bulk_create(
[
Employee(firstname="Johnny", lastname="%john"),
Employee(firstname="Jean-Claude", lastname="claud_"),
Employee(firstname="Jean-Claude", lastname="claude%"),
Employee(firstname="Johnny", lastname="joh\\n"),
Employee(firstname="Johnny", lastname="_ohn"),
]
)
claude = Employee.objects.create(firstname="Jean-Claude", lastname="claude")
john = Employee.objects.create(firstname="Johnny", lastname="john")
john_sign = Employee.objects.create(firstname="%Joh\\nny", lastname="%joh\\n")
self.assertCountEqual(
Employee.objects.filter(firstname__icontains=F("lastname")),
[john_sign, john, claude],
)
self.assertCountEqual(
Employee.objects.filter(firstname__istartswith=F("lastname")),
[john_sign, john],
)
self.assertSequenceEqual(
Employee.objects.filter(firstname__iendswith=F("lastname")),
[claude],
)
@isolate_apps("expressions")
class SimpleExpressionTests(SimpleTestCase):
def test_equal(self):
self.assertEqual(Expression(), Expression())
self.assertEqual(
Expression(IntegerField()), Expression(output_field=IntegerField())
)
self.assertEqual(Expression(IntegerField()), mock.ANY)
self.assertNotEqual(Expression(IntegerField()), Expression(CharField()))
class TestModel(Model):
field = IntegerField()
other_field = IntegerField()
self.assertNotEqual(
Expression(TestModel._meta.get_field("field")),
Expression(TestModel._meta.get_field("other_field")),
)
def test_hash(self):
self.assertEqual(hash(Expression()), hash(Expression()))
self.assertEqual(
hash(Expression(IntegerField())),
hash(Expression(output_field=IntegerField())),
)
self.assertNotEqual(
hash(Expression(IntegerField())),
hash(Expression(CharField())),
)
class TestModel(Model):
field = IntegerField()
other_field = IntegerField()
self.assertNotEqual(
hash(Expression(TestModel._meta.get_field("field"))),
hash(Expression(TestModel._meta.get_field("other_field"))),
)
class ExpressionsNumericTests(TestCase):
@classmethod
def setUpTestData(cls):
Number(integer=-1).save()
Number(integer=42).save()
Number(integer=1337).save()
Number.objects.update(float=F("integer"))
def test_fill_with_value_from_same_object(self):
"""
We can fill a value in all objects with an other value of the
same object.
"""
self.assertQuerySetEqual(
Number.objects.all(),
[(-1, -1), (42, 42), (1337, 1337)],
lambda n: (n.integer, round(n.float)),
ordered=False,
)
def test_increment_value(self):
"""
We can increment a value of all objects in a query set.
"""
self.assertEqual(
Number.objects.filter(integer__gt=0).update(integer=F("integer") + 1), 2
)
self.assertQuerySetEqual(
Number.objects.all(),
[(-1, -1), (43, 42), (1338, 1337)],
lambda n: (n.integer, round(n.float)),
ordered=False,
)
def test_filter_not_equals_other_field(self):
"""
We can filter for objects, where a value is not equals the value
of an other field.
"""
self.assertEqual(
Number.objects.filter(integer__gt=0).update(integer=F("integer") + 1), 2
)
self.assertQuerySetEqual(
Number.objects.exclude(float=F("integer")),
[(43, 42), (1338, 1337)],
lambda n: (n.integer, round(n.float)),
ordered=False,
)
def test_filter_decimal_expression(self):
obj = Number.objects.create(integer=0, float=1, decimal_value=Decimal("1"))
qs = Number.objects.annotate(
x=ExpressionWrapper(Value(1), output_field=DecimalField()),
).filter(Q(x=1, integer=0) & Q(x=Decimal("1")))
self.assertSequenceEqual(qs, [obj])
def test_complex_expressions(self):
"""
Complex expressions of different connection types are possible.
"""
n = Number.objects.create(integer=10, float=123.45)
self.assertEqual(
Number.objects.filter(pk=n.pk).update(float=F("integer") + F("float") * 2),
1,
)
self.assertEqual(Number.objects.get(pk=n.pk).integer, 10)
self.assertEqual(
Number.objects.get(pk=n.pk).float, Approximate(256.900, places=3)
)
def test_decimal_expression(self):
n = Number.objects.create(integer=1, decimal_value=Decimal("0.5"))
n.decimal_value = F("decimal_value") - Decimal("0.4")
n.save()
n.refresh_from_db()
self.assertEqual(n.decimal_value, Decimal("0.1"))
class ExpressionOperatorTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.n = Number.objects.create(integer=42, float=15.5)
cls.n1 = Number.objects.create(integer=-42, float=-15.5)
def test_lefthand_addition(self):
# LH Addition of floats and integers
Number.objects.filter(pk=self.n.pk).update(
integer=F("integer") + 15, float=F("float") + 42.7
)
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 57)
self.assertEqual(
Number.objects.get(pk=self.n.pk).float, Approximate(58.200, places=3)
)
def test_lefthand_subtraction(self):
# LH Subtraction of floats and integers
Number.objects.filter(pk=self.n.pk).update(
integer=F("integer") - 15, float=F("float") - 42.7
)
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 27)
self.assertEqual(
Number.objects.get(pk=self.n.pk).float, Approximate(-27.200, places=3)
)
def test_lefthand_multiplication(self):
# Multiplication of floats and integers
Number.objects.filter(pk=self.n.pk).update(
integer=F("integer") * 15, float=F("float") * 42.7
)
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 630)
self.assertEqual(
Number.objects.get(pk=self.n.pk).float, Approximate(661.850, places=3)
)
def test_lefthand_division(self):
# LH Division of floats and integers
Number.objects.filter(pk=self.n.pk).update(
integer=F("integer") / 2, float=F("float") / 42.7
)
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 21)
self.assertEqual(
Number.objects.get(pk=self.n.pk).float, Approximate(0.363, places=3)
)
def test_lefthand_modulo(self):
# LH Modulo arithmetic on integers
Number.objects.filter(pk=self.n.pk).update(integer=F("integer") % 20)
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 2)
def test_lefthand_modulo_null(self):
# LH Modulo arithmetic on integers.
Employee.objects.create(firstname="John", lastname="Doe", salary=None)
qs = Employee.objects.annotate(modsalary=F("salary") % 20)
self.assertIsNone(qs.get().salary)
def test_lefthand_bitwise_and(self):
# LH Bitwise ands on integers
Number.objects.filter(pk=self.n.pk).update(integer=F("integer").bitand(56))
Number.objects.filter(pk=self.n1.pk).update(integer=F("integer").bitand(-56))
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 40)
self.assertEqual(Number.objects.get(pk=self.n1.pk).integer, -64)
def test_lefthand_bitwise_left_shift_operator(self):
Number.objects.update(integer=F("integer").bitleftshift(2))
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 168)
self.assertEqual(Number.objects.get(pk=self.n1.pk).integer, -168)
def test_lefthand_bitwise_right_shift_operator(self):
Number.objects.update(integer=F("integer").bitrightshift(2))
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 10)
self.assertEqual(Number.objects.get(pk=self.n1.pk).integer, -11)
def test_lefthand_bitwise_or(self):
# LH Bitwise or on integers
Number.objects.update(integer=F("integer").bitor(48))
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 58)
self.assertEqual(Number.objects.get(pk=self.n1.pk).integer, -10)
def test_lefthand_transformed_field_bitwise_or(self):
Employee.objects.create(firstname="Max", lastname="Mustermann")
with register_lookup(CharField, Length):
qs = Employee.objects.annotate(bitor=F("lastname__length").bitor(48))
self.assertEqual(qs.get().bitor, 58)
def test_lefthand_power(self):
# LH Power arithmetic operation on floats and integers
Number.objects.filter(pk=self.n.pk).update(
integer=F("integer") ** 2, float=F("float") ** 1.5
)
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 1764)
self.assertEqual(
Number.objects.get(pk=self.n.pk).float, Approximate(61.02, places=2)
)
def test_lefthand_bitwise_xor(self):
Number.objects.update(integer=F("integer").bitxor(48))
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 26)
self.assertEqual(Number.objects.get(pk=self.n1.pk).integer, -26)
def test_lefthand_bitwise_xor_null(self):
employee = Employee.objects.create(firstname="John", lastname="Doe")
Employee.objects.update(salary=F("salary").bitxor(48))
employee.refresh_from_db()
self.assertIsNone(employee.salary)
def test_lefthand_bitwise_xor_right_null(self):
employee = Employee.objects.create(firstname="John", lastname="Doe", salary=48)
Employee.objects.update(salary=F("salary").bitxor(None))
employee.refresh_from_db()
self.assertIsNone(employee.salary)
@unittest.skipUnless(
connection.vendor == "oracle", "Oracle doesn't support bitwise XOR."
)
def test_lefthand_bitwise_xor_not_supported(self):
msg = "Bitwise XOR is not supported in Oracle."
with self.assertRaisesMessage(NotSupportedError, msg):
Number.objects.update(integer=F("integer").bitxor(48))
def test_right_hand_addition(self):
# Right hand operators
Number.objects.filter(pk=self.n.pk).update(
integer=15 + F("integer"), float=42.7 + F("float")
)
# RH Addition of floats and integers
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 57)
self.assertEqual(
Number.objects.get(pk=self.n.pk).float, Approximate(58.200, places=3)
)
def test_right_hand_subtraction(self):
Number.objects.filter(pk=self.n.pk).update(
integer=15 - F("integer"), float=42.7 - F("float")
)
# RH Subtraction of floats and integers
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, -27)
self.assertEqual(
Number.objects.get(pk=self.n.pk).float, Approximate(27.200, places=3)
)
def test_right_hand_multiplication(self):
# RH Multiplication of floats and integers
Number.objects.filter(pk=self.n.pk).update(
integer=15 * F("integer"), float=42.7 * F("float")
)
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 630)
self.assertEqual(
Number.objects.get(pk=self.n.pk).float, Approximate(661.850, places=3)
)
def test_right_hand_division(self):
# RH Division of floats and integers
Number.objects.filter(pk=self.n.pk).update(
integer=640 / F("integer"), float=42.7 / F("float")
)
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 15)
self.assertEqual(
Number.objects.get(pk=self.n.pk).float, Approximate(2.755, places=3)
)
def test_right_hand_modulo(self):
# RH Modulo arithmetic on integers
Number.objects.filter(pk=self.n.pk).update(integer=69 % F("integer"))
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 27)
def test_righthand_power(self):
# RH Power arithmetic operation on floats and integers
Number.objects.filter(pk=self.n.pk).update(
integer=2 ** F("integer"), float=1.5 ** F("float")
)
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 4398046511104)
self.assertEqual(
Number.objects.get(pk=self.n.pk).float, Approximate(536.308, places=3)
)
class FTimeDeltaTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.sday = sday = datetime.date(2010, 6, 25)
cls.stime = stime = datetime.datetime(2010, 6, 25, 12, 15, 30, 747000)
midnight = datetime.time(0)
delta0 = datetime.timedelta(0)
delta1 = datetime.timedelta(microseconds=253000)
delta2 = datetime.timedelta(seconds=44)
delta3 = datetime.timedelta(hours=21, minutes=8)
delta4 = datetime.timedelta(days=10)
delta5 = datetime.timedelta(days=90)
# Test data is set so that deltas and delays will be
# strictly increasing.
cls.deltas = []
cls.delays = []
cls.days_long = []
# e0: started same day as assigned, zero duration
end = stime + delta0
cls.e0 = Experiment.objects.create(
name="e0",
assigned=sday,
start=stime,
end=end,
completed=end.date(),
estimated_time=delta0,
)
cls.deltas.append(delta0)
cls.delays.append(
cls.e0.start - datetime.datetime.combine(cls.e0.assigned, midnight)
)
cls.days_long.append(cls.e0.completed - cls.e0.assigned)
# e1: started one day after assigned, tiny duration, data
# set so that end time has no fractional seconds, which
# tests an edge case on sqlite.
delay = datetime.timedelta(1)
end = stime + delay + delta1
e1 = Experiment.objects.create(
name="e1",
assigned=sday,
start=stime + delay,
end=end,
completed=end.date(),
estimated_time=delta1,
)
cls.deltas.append(delta1)
cls.delays.append(e1.start - datetime.datetime.combine(e1.assigned, midnight))
cls.days_long.append(e1.completed - e1.assigned)
# e2: started three days after assigned, small duration
end = stime + delta2
e2 = Experiment.objects.create(
name="e2",
assigned=sday - datetime.timedelta(3),
start=stime,
end=end,
completed=end.date(),
estimated_time=datetime.timedelta(hours=1),
)
cls.deltas.append(delta2)
cls.delays.append(e2.start - datetime.datetime.combine(e2.assigned, midnight))
cls.days_long.append(e2.completed - e2.assigned)
# e3: started four days after assigned, medium duration
delay = datetime.timedelta(4)
end = stime + delay + delta3
e3 = Experiment.objects.create(
name="e3",
assigned=sday,
start=stime + delay,
end=end,
completed=end.date(),
estimated_time=delta3,
)
cls.deltas.append(delta3)
cls.delays.append(e3.start - datetime.datetime.combine(e3.assigned, midnight))
cls.days_long.append(e3.completed - e3.assigned)
# e4: started 10 days after assignment, long duration
end = stime + delta4
e4 = Experiment.objects.create(
name="e4",
assigned=sday - datetime.timedelta(10),
start=stime,
end=end,
completed=end.date(),
estimated_time=delta4 - datetime.timedelta(1),
)
cls.deltas.append(delta4)
cls.delays.append(e4.start - datetime.datetime.combine(e4.assigned, midnight))
cls.days_long.append(e4.completed - e4.assigned)
# e5: started a month after assignment, very long duration
delay = datetime.timedelta(30)
end = stime + delay + delta5
e5 = Experiment.objects.create(
name="e5",
assigned=sday,
start=stime + delay,
end=end,
completed=end.date(),
estimated_time=delta5,
)
cls.deltas.append(delta5)
cls.delays.append(e5.start - datetime.datetime.combine(e5.assigned, midnight))
cls.days_long.append(e5.completed - e5.assigned)
cls.expnames = [e.name for e in Experiment.objects.all()]
def test_multiple_query_compilation(self):
# Ticket #21643
queryset = Experiment.objects.filter(
end__lt=F("start") + datetime.timedelta(hours=1)
)
q1 = str(queryset.query)
q2 = str(queryset.query)
self.assertEqual(q1, q2)
def test_query_clone(self):
# Ticket #21643 - Crash when compiling query more than once
qs = Experiment.objects.filter(end__lt=F("start") + datetime.timedelta(hours=1))
qs2 = qs.all()
list(qs)
list(qs2)
# Intentionally no assert
def test_delta_add(self):
for i, delta in enumerate(self.deltas):
test_set = [
e.name for e in Experiment.objects.filter(end__lt=F("start") + delta)
]
self.assertEqual(test_set, self.expnames[:i])
test_set = [
e.name for e in Experiment.objects.filter(end__lt=delta + F("start"))
]
self.assertEqual(test_set, self.expnames[:i])
test_set = [
e.name for e in Experiment.objects.filter(end__lte=F("start") + delta)
]
self.assertEqual(test_set, self.expnames[: i + 1])
def test_delta_subtract(self):
for i, delta in enumerate(self.deltas):
test_set = [
e.name for e in Experiment.objects.filter(start__gt=F("end") - delta)
]
self.assertEqual(test_set, self.expnames[:i])
test_set = [
e.name for e in Experiment.objects.filter(start__gte=F("end") - delta)
]
self.assertEqual(test_set, self.expnames[: i + 1])
def test_exclude(self):
for i, delta in enumerate(self.deltas):
test_set = [
e.name for e in Experiment.objects.exclude(end__lt=F("start") + delta)
]
self.assertEqual(test_set, self.expnames[i:])
test_set = [
e.name for e in Experiment.objects.exclude(end__lte=F("start") + delta)
]
self.assertEqual(test_set, self.expnames[i + 1 :])
def test_date_comparison(self):
for i, days in enumerate(self.days_long):
test_set = [
e.name
for e in Experiment.objects.filter(completed__lt=F("assigned") + days)
]
self.assertEqual(test_set, self.expnames[:i])
test_set = [
e.name
for e in Experiment.objects.filter(completed__lte=F("assigned") + days)
]
self.assertEqual(test_set, self.expnames[: i + 1])
def test_datetime_and_durationfield_addition_with_filter(self):
test_set = Experiment.objects.filter(end=F("start") + F("estimated_time"))
self.assertGreater(test_set.count(), 0)
self.assertEqual(
[e.name for e in test_set],
[
e.name
for e in Experiment.objects.all()
if e.end == e.start + e.estimated_time
],
)
def test_datetime_and_duration_field_addition_with_annotate_and_no_output_field(
self,
):
test_set = Experiment.objects.annotate(
estimated_end=F("start") + F("estimated_time")
)
self.assertEqual(
[e.estimated_end for e in test_set],
[e.start + e.estimated_time for e in test_set],
)
@skipUnlessDBFeature("supports_temporal_subtraction")
def test_datetime_subtraction_with_annotate_and_no_output_field(self):
test_set = Experiment.objects.annotate(
calculated_duration=F("end") - F("start")
)
self.assertEqual(
[e.calculated_duration for e in test_set],
[e.end - e.start for e in test_set],
)
def test_mixed_comparisons1(self):
for i, delay in enumerate(self.delays):
test_set = [
e.name
for e in Experiment.objects.filter(assigned__gt=F("start") - delay)
]
self.assertEqual(test_set, self.expnames[:i])
test_set = [
e.name
for e in Experiment.objects.filter(assigned__gte=F("start") - delay)
]
self.assertEqual(test_set, self.expnames[: i + 1])
def test_mixed_comparisons2(self):
for i, delay in enumerate(self.delays):
delay = datetime.timedelta(delay.days)
test_set = [
e.name
for e in Experiment.objects.filter(start__lt=F("assigned") + delay)
]
self.assertEqual(test_set, self.expnames[:i])
test_set = [
e.name
for e in Experiment.objects.filter(
start__lte=F("assigned") + delay + datetime.timedelta(1)
)
]
self.assertEqual(test_set, self.expnames[: i + 1])
def test_delta_update(self):
for delta in self.deltas:
exps = Experiment.objects.all()
expected_durations = [e.duration() for e in exps]
expected_starts = [e.start + delta for e in exps]
expected_ends = [e.end + delta for e in exps]
Experiment.objects.update(start=F("start") + delta, end=F("end") + delta)
exps = Experiment.objects.all()
new_starts = [e.start for e in exps]
new_ends = [e.end for e in exps]
new_durations = [e.duration() for e in exps]
self.assertEqual(expected_starts, new_starts)
self.assertEqual(expected_ends, new_ends)
self.assertEqual(expected_durations, new_durations)
def test_invalid_operator(self):
with self.assertRaises(DatabaseError):
list(Experiment.objects.filter(start=F("start") * datetime.timedelta(0)))
def test_durationfield_add(self):
zeros = [
e.name
for e in Experiment.objects.filter(start=F("start") + F("estimated_time"))
]
self.assertEqual(zeros, ["e0"])
end_less = [
e.name
for e in Experiment.objects.filter(end__lt=F("start") + F("estimated_time"))
]
self.assertEqual(end_less, ["e2"])
delta_math = [
e.name
for e in Experiment.objects.filter(
end__gte=F("start") + F("estimated_time") + datetime.timedelta(hours=1)
)
]
self.assertEqual(delta_math, ["e4"])
queryset = Experiment.objects.annotate(
shifted=ExpressionWrapper(
F("start") + Value(None, output_field=DurationField()),
output_field=DateTimeField(),
)
)
self.assertIsNone(queryset.first().shifted)
def test_durationfield_multiply_divide(self):
Experiment.objects.update(scalar=2)
tests = [
(Decimal("2"), 2),
(F("scalar"), 2),
(2, 2),
(3.2, 3.2),
]
for expr, scalar in tests:
with self.subTest(expr=expr):
qs = Experiment.objects.annotate(
multiplied=ExpressionWrapper(
expr * F("estimated_time"),
output_field=DurationField(),
),
divided=ExpressionWrapper(
F("estimated_time") / expr,
output_field=DurationField(),
),
)
for experiment in qs:
self.assertEqual(
experiment.multiplied,
experiment.estimated_time * scalar,
)
self.assertEqual(
experiment.divided,
experiment.estimated_time / scalar,
)
def test_duration_expressions(self):
for delta in self.deltas:
qs = Experiment.objects.annotate(duration=F("estimated_time") + delta)
for obj in qs:
self.assertEqual(obj.duration, obj.estimated_time + delta)
@skipUnlessDBFeature("supports_temporal_subtraction")
def test_date_subtraction(self):
queryset = Experiment.objects.annotate(
completion_duration=F("completed") - F("assigned"),
)
at_least_5_days = {
e.name
for e in queryset.filter(
completion_duration__gte=datetime.timedelta(days=5)
)
}
self.assertEqual(at_least_5_days, {"e3", "e4", "e5"})
at_least_120_days = {
e.name
for e in queryset.filter(
completion_duration__gte=datetime.timedelta(days=120)
)
}
self.assertEqual(at_least_120_days, {"e5"})
less_than_5_days = {
e.name
for e in queryset.filter(completion_duration__lt=datetime.timedelta(days=5))
}
self.assertEqual(less_than_5_days, {"e0", "e1", "e2"})
queryset = Experiment.objects.annotate(
difference=F("completed") - Value(None, output_field=DateField()),
)
self.assertIsNone(queryset.first().difference)
queryset = Experiment.objects.annotate(
shifted=ExpressionWrapper(
F("completed") - Value(None, output_field=DurationField()),
output_field=DateField(),
)
)
self.assertIsNone(queryset.first().shifted)
@skipUnlessDBFeature("supports_temporal_subtraction")
def test_date_subquery_subtraction(self):
subquery = Experiment.objects.filter(pk=OuterRef("pk")).values("completed")
queryset = Experiment.objects.annotate(
difference=subquery - F("completed"),
).filter(difference=datetime.timedelta())
self.assertTrue(queryset.exists())
@skipUnlessDBFeature("supports_temporal_subtraction")
def test_date_case_subtraction(self):
queryset = Experiment.objects.annotate(
date_case=Case(
When(Q(name="e0"), then=F("completed")),
output_field=DateField(),
),
completed_value=Value(
self.e0.completed,
output_field=DateField(),
),
difference=F("date_case") - F("completed_value"),
).filter(difference=datetime.timedelta())
self.assertEqual(queryset.get(), self.e0)
@skipUnlessDBFeature("supports_temporal_subtraction")
def test_time_subtraction(self):
Time.objects.create(time=datetime.time(12, 30, 15, 2345))
queryset = Time.objects.annotate(
difference=F("time") - Value(datetime.time(11, 15, 0)),
)
self.assertEqual(
queryset.get().difference,
datetime.timedelta(hours=1, minutes=15, seconds=15, microseconds=2345),
)
queryset = Time.objects.annotate(
difference=F("time") - Value(None, output_field=TimeField()),
)
self.assertIsNone(queryset.first().difference)
queryset = Time.objects.annotate(
shifted=ExpressionWrapper(
F("time") - Value(None, output_field=DurationField()),
output_field=TimeField(),
)
)
self.assertIsNone(queryset.first().shifted)
@skipUnlessDBFeature("supports_temporal_subtraction")
def test_time_subquery_subtraction(self):
Time.objects.create(time=datetime.time(12, 30, 15, 2345))
subquery = Time.objects.filter(pk=OuterRef("pk")).values("time")
queryset = Time.objects.annotate(
difference=subquery - F("time"),
).filter(difference=datetime.timedelta())
self.assertTrue(queryset.exists())
@skipUnlessDBFeature("supports_temporal_subtraction")
def test_datetime_subtraction(self):
under_estimate = [
e.name
for e in Experiment.objects.filter(estimated_time__gt=F("end") - F("start"))
]
self.assertEqual(under_estimate, ["e2"])
over_estimate = [
e.name
for e in Experiment.objects.filter(estimated_time__lt=F("end") - F("start"))
]
self.assertEqual(over_estimate, ["e4"])
queryset = Experiment.objects.annotate(
difference=F("start") - Value(None, output_field=DateTimeField()),
)
self.assertIsNone(queryset.first().difference)
queryset = Experiment.objects.annotate(
shifted=ExpressionWrapper(
F("start") - Value(None, output_field=DurationField()),
output_field=DateTimeField(),
)
)
self.assertIsNone(queryset.first().shifted)
@skipUnlessDBFeature("supports_temporal_subtraction")
def test_datetime_subquery_subtraction(self):
subquery = Experiment.objects.filter(pk=OuterRef("pk")).values("start")
queryset = Experiment.objects.annotate(
difference=subquery - F("start"),
).filter(difference=datetime.timedelta())
self.assertTrue(queryset.exists())
@skipUnlessDBFeature("supports_temporal_subtraction")
def test_datetime_subtraction_microseconds(self):
delta = datetime.timedelta(microseconds=8999999999999999)
Experiment.objects.update(end=F("start") + delta)
qs = Experiment.objects.annotate(delta=F("end") - F("start"))
for e in qs:
self.assertEqual(e.delta, delta)
def test_duration_with_datetime(self):
# Exclude e1 which has very high precision so we can test this on all
# backends regardless of whether or not it supports
# microsecond_precision.
over_estimate = (
Experiment.objects.exclude(name="e1")
.filter(
completed__gt=self.stime + F("estimated_time"),
)
.order_by("name")
)
self.assertQuerySetEqual(over_estimate, ["e3", "e4", "e5"], lambda e: e.name)
def test_duration_with_datetime_microseconds(self):
delta = datetime.timedelta(microseconds=8999999999999999)
qs = Experiment.objects.annotate(
dt=ExpressionWrapper(
F("start") + delta,
output_field=DateTimeField(),
)
)
for e in qs:
self.assertEqual(e.dt, e.start + delta)
def test_date_minus_duration(self):
more_than_4_days = Experiment.objects.filter(
assigned__lt=F("completed") - Value(datetime.timedelta(days=4))
)
self.assertQuerySetEqual(more_than_4_days, ["e3", "e4", "e5"], lambda e: e.name)
def test_negative_timedelta_update(self):
# subtract 30 seconds, 30 minutes, 2 hours and 2 days
experiments = (
Experiment.objects.filter(name="e0")
.annotate(
start_sub_seconds=F("start") + datetime.timedelta(seconds=-30),
)
.annotate(
start_sub_minutes=F("start_sub_seconds")
+ datetime.timedelta(minutes=-30),
)
.annotate(
start_sub_hours=F("start_sub_minutes") + datetime.timedelta(hours=-2),
)
.annotate(
new_start=F("start_sub_hours") + datetime.timedelta(days=-2),
)
)
expected_start = datetime.datetime(2010, 6, 23, 9, 45, 0)
# subtract 30 microseconds
experiments = experiments.annotate(
new_start=F("new_start") + datetime.timedelta(microseconds=-30)
)
expected_start += datetime.timedelta(microseconds=+746970)
experiments.update(start=F("new_start"))
e0 = Experiment.objects.get(name="e0")
self.assertEqual(e0.start, expected_start)
class ValueTests(TestCase):
def test_update_TimeField_using_Value(self):
Time.objects.create()
Time.objects.update(time=Value(datetime.time(1), output_field=TimeField()))
self.assertEqual(Time.objects.get().time, datetime.time(1))
def test_update_UUIDField_using_Value(self):
UUID.objects.create()
UUID.objects.update(
uuid=Value(
uuid.UUID("12345678901234567890123456789012"), output_field=UUIDField()
)
)
self.assertEqual(
UUID.objects.get().uuid, uuid.UUID("12345678901234567890123456789012")
)
def test_deconstruct(self):
value = Value("name")
path, args, kwargs = value.deconstruct()
self.assertEqual(path, "django.db.models.Value")
self.assertEqual(args, (value.value,))
self.assertEqual(kwargs, {})
def test_deconstruct_output_field(self):
value = Value("name", output_field=CharField())
path, args, kwargs = value.deconstruct()
self.assertEqual(path, "django.db.models.Value")
self.assertEqual(args, (value.value,))
self.assertEqual(len(kwargs), 1)
self.assertEqual(
kwargs["output_field"].deconstruct(), CharField().deconstruct()
)
def test_repr(self):
tests = [
(None, "Value(None)"),
("str", "Value('str')"),
(True, "Value(True)"),
(42, "Value(42)"),
(
datetime.datetime(2019, 5, 15),
"Value(datetime.datetime(2019, 5, 15, 0, 0))",
),
(Decimal("3.14"), "Value(Decimal('3.14'))"),
]
for value, expected in tests:
with self.subTest(value=value):
self.assertEqual(repr(Value(value)), expected)
def test_equal(self):
value = Value("name")
self.assertEqual(value, Value("name"))
self.assertNotEqual(value, Value("username"))
def test_hash(self):
d = {Value("name"): "Bob"}
self.assertIn(Value("name"), d)
self.assertEqual(d[Value("name")], "Bob")
def test_equal_output_field(self):
value = Value("name", output_field=CharField())
same_value = Value("name", output_field=CharField())
other_value = Value("name", output_field=TimeField())
no_output_field = Value("name")
self.assertEqual(value, same_value)
self.assertNotEqual(value, other_value)
self.assertNotEqual(value, no_output_field)
def test_raise_empty_expressionlist(self):
msg = "ExpressionList requires at least one expression"
with self.assertRaisesMessage(ValueError, msg):
ExpressionList()
def test_compile_unresolved(self):
# This test might need to be revisited later on if #25425 is enforced.
compiler = Time.objects.all().query.get_compiler(connection=connection)
value = Value("foo")
self.assertEqual(value.as_sql(compiler, connection), ("%s", ["foo"]))
value = Value("foo", output_field=CharField())
self.assertEqual(value.as_sql(compiler, connection), ("%s", ["foo"]))
def test_output_field_decimalfield(self):
Time.objects.create()
time = Time.objects.annotate(one=Value(1, output_field=DecimalField())).first()
self.assertEqual(time.one, 1)
def test_resolve_output_field(self):
value_types = [
("str", CharField),
(True, BooleanField),
(42, IntegerField),
(3.14, FloatField),
(datetime.date(2019, 5, 15), DateField),
(datetime.datetime(2019, 5, 15), DateTimeField),
(datetime.time(3, 16), TimeField),
(datetime.timedelta(1), DurationField),
(Decimal("3.14"), DecimalField),
(b"", BinaryField),
(uuid.uuid4(), UUIDField),
]
for value, output_field_type in value_types:
with self.subTest(type=type(value)):
expr = Value(value)
self.assertIsInstance(expr.output_field, output_field_type)
def test_resolve_output_field_failure(self):
msg = "Cannot resolve expression type, unknown output_field"
with self.assertRaisesMessage(FieldError, msg):
Value(object()).output_field
def test_output_field_does_not_create_broken_validators(self):
"""
The output field for a given Value doesn't get cleaned & validated,
however validators may still be instantiated for a given field type
and this demonstrates that they don't throw an exception.
"""
value_types = [
"str",
True,
42,
3.14,
datetime.date(2019, 5, 15),
datetime.datetime(2019, 5, 15),
datetime.time(3, 16),
datetime.timedelta(1),
Decimal("3.14"),
b"",
uuid.uuid4(),
]
for value in value_types:
with self.subTest(type=type(value)):
field = Value(value)._resolve_output_field()
field.clean(value, model_instance=None)
class ExistsTests(TestCase):
def test_optimizations(self):
with CaptureQueriesContext(connection) as context:
list(
Experiment.objects.values(
exists=Exists(
Experiment.objects.order_by("pk"),
)
).order_by()
)
captured_queries = context.captured_queries
self.assertEqual(len(captured_queries), 1)
captured_sql = captured_queries[0]["sql"]
self.assertNotIn(
connection.ops.quote_name(Experiment._meta.pk.column),
captured_sql,
)
self.assertIn(
connection.ops.limit_offset_sql(None, 1),
captured_sql,
)
self.assertNotIn("ORDER BY", captured_sql)
def test_negated_empty_exists(self):
manager = Manager.objects.create()
qs = Manager.objects.filter(~Exists(Manager.objects.none()) & Q(pk=manager.pk))
self.assertSequenceEqual(qs, [manager])
def test_select_negated_empty_exists(self):
manager = Manager.objects.create()
qs = Manager.objects.annotate(
not_exists=~Exists(Manager.objects.none())
).filter(pk=manager.pk)
self.assertSequenceEqual(qs, [manager])
self.assertIs(qs.get().not_exists, True)
class FieldTransformTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.sday = sday = datetime.date(2010, 6, 25)
cls.stime = stime = datetime.datetime(2010, 6, 25, 12, 15, 30, 747000)
cls.ex1 = Experiment.objects.create(
name="Experiment 1",
assigned=sday,
completed=sday + datetime.timedelta(2),
estimated_time=datetime.timedelta(2),
start=stime,
end=stime + datetime.timedelta(2),
)
def test_month_aggregation(self):
self.assertEqual(
Experiment.objects.aggregate(month_count=Count("assigned__month")),
{"month_count": 1},
)
def test_transform_in_values(self):
self.assertSequenceEqual(
Experiment.objects.values("assigned__month"),
[{"assigned__month": 6}],
)
def test_multiple_transforms_in_values(self):
self.assertSequenceEqual(
Experiment.objects.values("end__date__month"),
[{"end__date__month": 6}],
)
class ReprTests(SimpleTestCase):
def test_expressions(self):
self.assertEqual(
repr(Case(When(a=1))),
"<Case: CASE WHEN <Q: (AND: ('a', 1))> THEN Value(None), ELSE Value(None)>",
)
self.assertEqual(
repr(When(Q(age__gte=18), then=Value("legal"))),
"<When: WHEN <Q: (AND: ('age__gte', 18))> THEN Value('legal')>",
)
self.assertEqual(repr(Col("alias", "field")), "Col(alias, field)")
self.assertEqual(repr(F("published")), "F(published)")
self.assertEqual(
repr(F("cost") + F("tax")), "<CombinedExpression: F(cost) + F(tax)>"
)
self.assertEqual(
repr(ExpressionWrapper(F("cost") + F("tax"), IntegerField())),
"ExpressionWrapper(F(cost) + F(tax))",
)
self.assertEqual(
repr(Func("published", function="TO_CHAR")),
"Func(F(published), function=TO_CHAR)",
)
self.assertEqual(repr(OrderBy(Value(1))), "OrderBy(Value(1), descending=False)")
self.assertEqual(repr(RawSQL("table.col", [])), "RawSQL(table.col, [])")
self.assertEqual(
repr(Ref("sum_cost", Sum("cost"))), "Ref(sum_cost, Sum(F(cost)))"
)
self.assertEqual(repr(Value(1)), "Value(1)")
self.assertEqual(
repr(ExpressionList(F("col"), F("anothercol"))),
"ExpressionList(F(col), F(anothercol))",
)
self.assertEqual(
repr(ExpressionList(OrderBy(F("col"), descending=False))),
"ExpressionList(OrderBy(F(col), descending=False))",
)
def test_functions(self):
self.assertEqual(repr(Coalesce("a", "b")), "Coalesce(F(a), F(b))")
self.assertEqual(repr(Concat("a", "b")), "Concat(ConcatPair(F(a), F(b)))")
self.assertEqual(repr(Length("a")), "Length(F(a))")
self.assertEqual(repr(Lower("a")), "Lower(F(a))")
self.assertEqual(repr(Substr("a", 1, 3)), "Substr(F(a), Value(1), Value(3))")
self.assertEqual(repr(Upper("a")), "Upper(F(a))")
def test_aggregates(self):
self.assertEqual(repr(Avg("a")), "Avg(F(a))")
self.assertEqual(repr(Count("a")), "Count(F(a))")
self.assertEqual(repr(Count("*")), "Count('*')")
self.assertEqual(repr(Max("a")), "Max(F(a))")
self.assertEqual(repr(Min("a")), "Min(F(a))")
self.assertEqual(repr(StdDev("a")), "StdDev(F(a), sample=False)")
self.assertEqual(repr(Sum("a")), "Sum(F(a))")
self.assertEqual(
repr(Variance("a", sample=True)), "Variance(F(a), sample=True)"
)
def test_distinct_aggregates(self):
self.assertEqual(repr(Count("a", distinct=True)), "Count(F(a), distinct=True)")
self.assertEqual(repr(Count("*", distinct=True)), "Count('*', distinct=True)")
def test_filtered_aggregates(self):
filter = Q(a=1)
self.assertEqual(
repr(Avg("a", filter=filter)), "Avg(F(a), filter=(AND: ('a', 1)))"
)
self.assertEqual(
repr(Count("a", filter=filter)), "Count(F(a), filter=(AND: ('a', 1)))"
)
self.assertEqual(
repr(Max("a", filter=filter)), "Max(F(a), filter=(AND: ('a', 1)))"
)
self.assertEqual(
repr(Min("a", filter=filter)), "Min(F(a), filter=(AND: ('a', 1)))"
)
self.assertEqual(
repr(StdDev("a", filter=filter)),
"StdDev(F(a), filter=(AND: ('a', 1)), sample=False)",
)
self.assertEqual(
repr(Sum("a", filter=filter)), "Sum(F(a), filter=(AND: ('a', 1)))"
)
self.assertEqual(
repr(Variance("a", sample=True, filter=filter)),
"Variance(F(a), filter=(AND: ('a', 1)), sample=True)",
)
self.assertEqual(
repr(Count("a", filter=filter, distinct=True)),
"Count(F(a), distinct=True, filter=(AND: ('a', 1)))",
)
class CombinableTests(SimpleTestCase):
bitwise_msg = (
"Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
)
def test_negation(self):
c = Combinable()
self.assertEqual(-c, c * -1)
def test_and(self):
with self.assertRaisesMessage(NotImplementedError, self.bitwise_msg):
Combinable() & Combinable()
def test_or(self):
with self.assertRaisesMessage(NotImplementedError, self.bitwise_msg):
Combinable() | Combinable()
def test_xor(self):
with self.assertRaisesMessage(NotImplementedError, self.bitwise_msg):
Combinable() ^ Combinable()
def test_reversed_and(self):
with self.assertRaisesMessage(NotImplementedError, self.bitwise_msg):
object() & Combinable()
def test_reversed_or(self):
with self.assertRaisesMessage(NotImplementedError, self.bitwise_msg):
object() | Combinable()
def test_reversed_xor(self):
with self.assertRaisesMessage(NotImplementedError, self.bitwise_msg):
object() ^ Combinable()
class CombinedExpressionTests(SimpleTestCase):
def test_resolve_output_field_number(self):
tests = [
(IntegerField, AutoField, IntegerField),
(AutoField, IntegerField, IntegerField),
(IntegerField, DecimalField, DecimalField),
(DecimalField, IntegerField, DecimalField),
(IntegerField, FloatField, FloatField),
(FloatField, IntegerField, FloatField),
]
connectors = [
Combinable.ADD,
Combinable.SUB,
Combinable.MUL,
Combinable.DIV,
Combinable.MOD,
]
for lhs, rhs, combined in tests:
for connector in connectors:
with self.subTest(
lhs=lhs, connector=connector, rhs=rhs, combined=combined
):
expr = CombinedExpression(
Expression(lhs()),
connector,
Expression(rhs()),
)
self.assertIsInstance(expr.output_field, combined)
def test_resolve_output_field_with_null(self):
def null():
return Value(None)
tests = [
# Numbers.
(AutoField, Combinable.ADD, null),
(DecimalField, Combinable.ADD, null),
(FloatField, Combinable.ADD, null),
(IntegerField, Combinable.ADD, null),
(IntegerField, Combinable.SUB, null),
(null, Combinable.ADD, IntegerField),
# Dates.
(DateField, Combinable.ADD, null),
(DateTimeField, Combinable.ADD, null),
(DurationField, Combinable.ADD, null),
(TimeField, Combinable.ADD, null),
(TimeField, Combinable.SUB, null),
(null, Combinable.ADD, DateTimeField),
(DateField, Combinable.SUB, null),
]
for lhs, connector, rhs in tests:
msg = (
f"Cannot infer type of {connector!r} expression involving these types: "
)
with self.subTest(lhs=lhs, connector=connector, rhs=rhs):
expr = CombinedExpression(
Expression(lhs()),
connector,
Expression(rhs()),
)
with self.assertRaisesMessage(FieldError, msg):
expr.output_field
def test_resolve_output_field_dates(self):
tests = [
# Add - same type.
(DateField, Combinable.ADD, DateField, FieldError),
(DateTimeField, Combinable.ADD, DateTimeField, FieldError),
(TimeField, Combinable.ADD, TimeField, FieldError),
(DurationField, Combinable.ADD, DurationField, DurationField),
# Add - different type.
(DateField, Combinable.ADD, DurationField, DateTimeField),
(DateTimeField, Combinable.ADD, DurationField, DateTimeField),
(TimeField, Combinable.ADD, DurationField, TimeField),
(DurationField, Combinable.ADD, DateField, DateTimeField),
(DurationField, Combinable.ADD, DateTimeField, DateTimeField),
(DurationField, Combinable.ADD, TimeField, TimeField),
# Subtract - same type.
(DateField, Combinable.SUB, DateField, DurationField),
(DateTimeField, Combinable.SUB, DateTimeField, DurationField),
(TimeField, Combinable.SUB, TimeField, DurationField),
(DurationField, Combinable.SUB, DurationField, DurationField),
# Subtract - different type.
(DateField, Combinable.SUB, DurationField, DateTimeField),
(DateTimeField, Combinable.SUB, DurationField, DateTimeField),
(TimeField, Combinable.SUB, DurationField, TimeField),
(DurationField, Combinable.SUB, DateField, FieldError),
(DurationField, Combinable.SUB, DateTimeField, FieldError),
(DurationField, Combinable.SUB, DateTimeField, FieldError),
]
for lhs, connector, rhs, combined in tests:
msg = (
f"Cannot infer type of {connector!r} expression involving these types: "
)
with self.subTest(lhs=lhs, connector=connector, rhs=rhs, combined=combined):
expr = CombinedExpression(
Expression(lhs()),
connector,
Expression(rhs()),
)
if issubclass(combined, Exception):
with self.assertRaisesMessage(combined, msg):
expr.output_field
else:
self.assertIsInstance(expr.output_field, combined)
def test_mixed_char_date_with_annotate(self):
queryset = Experiment.objects.annotate(nonsense=F("name") + F("assigned"))
msg = (
"Cannot infer type of '+' expression involving these types: CharField, "
"DateField. You must set output_field."
)
with self.assertRaisesMessage(FieldError, msg):
list(queryset)
class ExpressionWrapperTests(SimpleTestCase):
def test_empty_group_by(self):
expr = ExpressionWrapper(Value(3), output_field=IntegerField())
self.assertEqual(expr.get_group_by_cols(), [])
def test_non_empty_group_by(self):
value = Value("f")
value.output_field = None
expr = ExpressionWrapper(Lower(value), output_field=IntegerField())
group_by_cols = expr.get_group_by_cols()
self.assertEqual(group_by_cols, [expr.expression])
self.assertEqual(group_by_cols[0].output_field, expr.output_field)
class OrderByTests(SimpleTestCase):
def test_equal(self):
self.assertEqual(
OrderBy(F("field"), nulls_last=True),
OrderBy(F("field"), nulls_last=True),
)
self.assertNotEqual(
OrderBy(F("field"), nulls_last=True),
OrderBy(F("field")),
)
def test_hash(self):
self.assertEqual(
hash(OrderBy(F("field"), nulls_last=True)),
hash(OrderBy(F("field"), nulls_last=True)),
)
self.assertNotEqual(
hash(OrderBy(F("field"), nulls_last=True)),
hash(OrderBy(F("field"))),
)
def test_nulls_false(self):
# These tests will catch ValueError in Django 5.0 when passing False to
# nulls_first and nulls_last becomes forbidden.
# msg = "nulls_first and nulls_last values must be True or None."
msg = (
"Passing nulls_first=False or nulls_last=False is deprecated, use None "
"instead."
)
with self.assertRaisesMessage(RemovedInDjango50Warning, msg):
OrderBy(F("field"), nulls_first=False)
with self.assertRaisesMessage(RemovedInDjango50Warning, msg):
OrderBy(F("field"), nulls_last=False)
with self.assertRaisesMessage(RemovedInDjango50Warning, msg):
F("field").asc(nulls_first=False)
with self.assertRaisesMessage(RemovedInDjango50Warning, msg):
F("field").desc(nulls_last=False)
|
374cc66f6746dcb27bb0f3ad12370501aa44405b01bb989321f926fcab2a2029 | import copy
import datetime
import pickle
from operator import attrgetter
from django.core.exceptions import FieldError
from django.db import models
from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature
from django.test.utils import isolate_apps
from django.utils import translation
from .models import (
Article,
ArticleIdea,
ArticleTag,
ArticleTranslation,
Country,
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.timezone.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_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_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(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_foreignkey_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):
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)
@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(
membership_country=self.usa, person=self.bob, group_id=None
)
m2 = Membership.objects.create(
membership_country=self.usa, person=self.bob, group=self.cia
)
self.assertSequenceEqual(
Membership.objects.filter(group__isnull=True),
[m1],
)
self.assertSequenceEqual(
Membership.objects.filter(group__isnull=False),
[m2],
)
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 behaviour.
"""
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__)
|
b20e18b4d4bcb0ab451c934d02afbe456935fdecc8ba18c875af81172a90fa44 | 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"),
)
|
0f676f9b93525d44f5274c90d3101479231dac61b4573b3e99dc3813fb1031c1 | import datetime
import re
import sys
from contextlib import contextmanager
from unittest import SkipTest, skipIf
from xml.dom.minidom import parseString
try:
import zoneinfo
except ImportError:
from backports import zoneinfo
try:
import pytz
except ImportError:
pytz = None
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.http import HttpRequest
from django.template import (
Context,
RequestContext,
Template,
TemplateSyntaxError,
context_processors,
)
from django.test import (
SimpleTestCase,
TestCase,
TransactionTestCase,
ignore_warnings,
override_settings,
skipIfDBFeature,
skipUnlessDBFeature,
)
from django.test.utils import requires_tz_support
from django.urls import reverse
from django.utils import timezone
from django.utils.deprecation import RemovedInDjango50Warning
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.timezone.utc
EAT = timezone.get_fixed_timezone(180) # Africa/Nairobi
ICT = timezone.get_fixed_timezone(420) # Asia/Bangkok
ZONE_CONSTRUCTORS = (zoneinfo.ZoneInfo,)
if pytz is not None:
ZONE_CONSTRUCTORS += (pytz.timezone,)
def get_timezones(key):
return [constructor(key) for constructor in ZONE_CONSTRUCTORS]
class UTCAliasTests(SimpleTestCase):
def test_alias_deprecation_warning(self):
msg = (
"The django.utils.timezone.utc alias is deprecated. "
"Please update your code to use datetime.timezone.utc instead."
)
with self.assertRaisesMessage(RemovedInDjango50Warning, msg):
timezone.utc
def test_timezone_module_dir_includes_utc(self):
self.assertIn("utc", dir(timezone))
@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_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_pytz_timezones(self):
for tz in get_timezones("Europe/Paris"):
with self.subTest(repr(tz)):
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
)
@ignore_warnings(category=RemovedInDjango50Warning)
def test_connection_timezone(self):
tests = [
(False, None, datetime.timezone),
(False, "Africa/Nairobi", zoneinfo.ZoneInfo),
]
if pytz is not None:
tests += [
(True, None, datetime.timezone),
(True, "Africa/Nairobi", pytz.BaseTzInfo),
]
for use_pytz, connection_tz, expected_type in tests:
with self.subTest(use_pytz=use_pytz, connection_tz=connection_tz):
with self.settings(USE_DEPRECATED_PYTZ=use_pytz):
with override_database_connection_timezone(connection_tz):
self.assertIsInstance(connection.timezone, expected_type)
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, datetime.timezone.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, datetime.timezone.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)
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.405")
obj = next(serializers.deserialize("json", data)).object
self.assertEqual(obj.dt, dt.replace(microsecond=405000))
data = serializers.serialize("xml", [Event(dt=dt)])
self.assert_xml_contains_datetime(data, "2011-09-01T13:20:30.405060")
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.405060")
obj = next(serializers.deserialize("yaml", data)).object
self.assertEqual(obj.dt, dt)
def test_aware_datetime_with_microsecond(self):
dt = datetime.datetime(2011, 9, 1, 17, 20, 30, 405060, tzinfo=ICT)
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-01T17:20:30.405+07:00")
obj = next(serializers.deserialize("json", data)).object
self.assertEqual(obj.dt, dt.replace(microsecond=405000))
data = serializers.serialize("xml", [Event(dt=dt)])
self.assert_xml_contains_datetime(data, "2011-09-01T17:20:30.405060+07:00")
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 17:20:30.405060+07:00")
obj = next(serializers.deserialize("yaml", data)).object
if HAS_YAML and yaml.__version__ < "5.3":
self.assertEqual(obj.dt.replace(tzinfo=UTC), dt)
else:
self.assertEqual(obj.dt, dt)
def test_aware_datetime_in_utc(self):
dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)
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-01T10:20:30Z")
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-01T10:20:30+00:00")
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 10:20:30+00:00")
obj = next(serializers.deserialize("yaml", data)).object
self.assertEqual(obj.dt.replace(tzinfo=UTC), dt)
def test_aware_datetime_in_local_timezone(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)
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+03:00")
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+03:00")
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+03:00")
obj = next(serializers.deserialize("yaml", data)).object
if HAS_YAML and yaml.__version__ < "5.3":
self.assertEqual(obj.dt.replace(tzinfo=UTC), dt)
else:
self.assertEqual(obj.dt, dt)
def test_aware_datetime_in_other_timezone(self):
dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT)
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-01T17:20:30+07:00")
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-01T17:20:30+07:00")
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 17:20:30+07:00")
obj = next(serializers.deserialize("yaml", data)).object
if HAS_YAML and yaml.__version__ < "5.3":
self.assertEqual(obj.dt.replace(tzinfo=UTC), dt)
else:
self.assertEqual(obj.dt, dt)
# RemovedInDjango50Warning: When the deprecation ends, remove setUpClass() and
# USE_L10N=False. The tests should remain because format-related settings will
# take precedence over locale-dictated formats.
@override_settings(
DATETIME_FORMAT="c", TIME_ZONE="Africa/Nairobi", USE_L10N=False, USE_TZ=True
)
class TemplateTests(SimpleTestCase):
@classmethod
def setUpClass(cls):
with ignore_warnings(category=RemovedInDjango50Warning):
super().setUpClass()
@requires_tz_support
def test_localtime_templatetag_and_filters(self):
"""
Test the {% localtime %} templatetag and related filters.
"""
datetimes = {
"utc": datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC),
"eat": datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT),
"ict": datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT),
"naive": datetime.datetime(2011, 9, 1, 13, 20, 30),
}
templates = {
"notag": Template(
"{% load tz %}"
"{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:ICT }}"
),
"noarg": Template(
"{% load tz %}{% localtime %}{{ dt }}|{{ dt|localtime }}|"
"{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}"
),
"on": Template(
"{% load tz %}{% localtime on %}{{ dt }}|{{ dt|localtime }}|"
"{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}"
),
"off": Template(
"{% load tz %}{% localtime off %}{{ dt }}|{{ dt|localtime }}|"
"{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}"
),
}
# Transform a list of keys in 'datetimes' to the expected template
# output. This makes the definition of 'results' more readable.
def t(*result):
return "|".join(datetimes[key].isoformat() for key in result)
# Results for USE_TZ = True
results = {
"utc": {
"notag": t("eat", "eat", "utc", "ict"),
"noarg": t("eat", "eat", "utc", "ict"),
"on": t("eat", "eat", "utc", "ict"),
"off": t("utc", "eat", "utc", "ict"),
},
"eat": {
"notag": t("eat", "eat", "utc", "ict"),
"noarg": t("eat", "eat", "utc", "ict"),
"on": t("eat", "eat", "utc", "ict"),
"off": t("eat", "eat", "utc", "ict"),
},
"ict": {
"notag": t("eat", "eat", "utc", "ict"),
"noarg": t("eat", "eat", "utc", "ict"),
"on": t("eat", "eat", "utc", "ict"),
"off": t("ict", "eat", "utc", "ict"),
},
"naive": {
"notag": t("naive", "eat", "utc", "ict"),
"noarg": t("naive", "eat", "utc", "ict"),
"on": t("naive", "eat", "utc", "ict"),
"off": t("naive", "eat", "utc", "ict"),
},
}
for k1, dt in datetimes.items():
for k2, tpl in templates.items():
ctx = Context({"dt": dt, "ICT": ICT})
actual = tpl.render(ctx)
expected = results[k1][k2]
self.assertEqual(
actual, expected, "%s / %s: %r != %r" % (k1, k2, actual, expected)
)
# Changes for USE_TZ = False
results["utc"]["notag"] = t("utc", "eat", "utc", "ict")
results["ict"]["notag"] = t("ict", "eat", "utc", "ict")
with self.settings(USE_TZ=False):
for k1, dt in datetimes.items():
for k2, tpl in templates.items():
ctx = Context({"dt": dt, "ICT": ICT})
actual = tpl.render(ctx)
expected = results[k1][k2]
self.assertEqual(
actual,
expected,
"%s / %s: %r != %r" % (k1, k2, actual, expected),
)
def test_localtime_filters_with_iana(self):
"""
Test the |localtime, |utc, and |timezone filters with iana zones.
"""
# Use an IANA timezone as local time
tpl = Template("{% load tz %}{{ dt|localtime }}|{{ dt|utc }}")
ctx = Context({"dt": datetime.datetime(2011, 9, 1, 12, 20, 30)})
with self.settings(TIME_ZONE="Europe/Paris"):
self.assertEqual(
tpl.render(ctx), "2011-09-01T12:20:30+02:00|2011-09-01T10:20:30+00:00"
)
# Use an IANA timezone as argument
for tz in get_timezones("Europe/Paris"):
with self.subTest(repr(tz)):
tpl = Template("{% load tz %}{{ dt|timezone:tz }}")
ctx = Context(
{
"dt": datetime.datetime(2011, 9, 1, 13, 20, 30),
"tz": tz,
}
)
self.assertEqual(tpl.render(ctx), "2011-09-01T12:20:30+02:00")
def test_localtime_templatetag_invalid_argument(self):
with self.assertRaises(TemplateSyntaxError):
Template("{% load tz %}{% localtime foo %}{% endlocaltime %}").render()
def test_localtime_filters_do_not_raise_exceptions(self):
"""
Test the |localtime, |utc, and |timezone filters on bad inputs.
"""
tpl = Template(
"{% load tz %}{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:tz }}"
)
with self.settings(USE_TZ=True):
# bad datetime value
ctx = Context({"dt": None, "tz": ICT})
self.assertEqual(tpl.render(ctx), "None|||")
ctx = Context({"dt": "not a date", "tz": ICT})
self.assertEqual(tpl.render(ctx), "not a date|||")
# bad timezone value
tpl = Template("{% load tz %}{{ dt|timezone:tz }}")
ctx = Context({"dt": datetime.datetime(2011, 9, 1, 13, 20, 30), "tz": None})
self.assertEqual(tpl.render(ctx), "")
ctx = Context(
{"dt": datetime.datetime(2011, 9, 1, 13, 20, 30), "tz": "not a tz"}
)
self.assertEqual(tpl.render(ctx), "")
@requires_tz_support
def test_timezone_templatetag(self):
"""
Test the {% timezone %} templatetag.
"""
tpl = Template(
"{% load tz %}"
"{{ dt }}|"
"{% timezone tz1 %}"
"{{ dt }}|"
"{% timezone tz2 %}"
"{{ dt }}"
"{% endtimezone %}"
"{% endtimezone %}"
)
ctx = Context(
{
"dt": datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC),
"tz1": ICT,
"tz2": None,
}
)
self.assertEqual(
tpl.render(ctx),
"2011-09-01T13:20:30+03:00|2011-09-01T17:20:30+07:00|"
"2011-09-01T13:20:30+03:00",
)
def test_timezone_templatetag_with_iana(self):
"""
Test the {% timezone %} templatetag with IANA time zone providers.
"""
tpl = Template("{% load tz %}{% timezone tz %}{{ dt }}{% endtimezone %}")
# Use a IANA timezone as argument
for tz in get_timezones("Europe/Paris"):
with self.subTest(repr(tz)):
ctx = Context(
{
"dt": datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT),
"tz": tz,
}
)
self.assertEqual(tpl.render(ctx), "2011-09-01T12:20:30+02:00")
# Use a IANA timezone name as argument
ctx = Context(
{
"dt": datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT),
"tz": "Europe/Paris",
}
)
self.assertEqual(tpl.render(ctx), "2011-09-01T12:20:30+02:00")
@ignore_warnings(category=RemovedInDjango50Warning)
def test_timezone_templatetag_invalid_argument(self):
with self.assertRaises(TemplateSyntaxError):
Template("{% load tz %}{% timezone %}{% endtimezone %}").render()
with self.assertRaises(zoneinfo.ZoneInfoNotFoundError):
Template("{% load tz %}{% timezone tz %}{% endtimezone %}").render(
Context({"tz": "foobar"})
)
if pytz is not None:
with override_settings(USE_DEPRECATED_PYTZ=True), self.assertRaises(
pytz.UnknownTimeZoneError
):
Template("{% load tz %}{% timezone tz %}{% endtimezone %}").render(
Context({"tz": "foobar"})
)
@skipIf(sys.platform == "win32", "Windows uses non-standard time zone names")
def test_get_current_timezone_templatetag(self):
"""
Test the {% get_current_timezone %} templatetag.
"""
tpl = Template(
"{% load tz %}{% get_current_timezone as time_zone %}{{ time_zone }}"
)
self.assertEqual(tpl.render(Context()), "Africa/Nairobi")
with timezone.override(UTC):
self.assertEqual(tpl.render(Context()), "UTC")
tpl = Template(
"{% load tz %}{% timezone tz %}{% get_current_timezone as time_zone %}"
"{% endtimezone %}{{ time_zone }}"
)
self.assertEqual(tpl.render(Context({"tz": ICT})), "+0700")
with timezone.override(UTC):
self.assertEqual(tpl.render(Context({"tz": ICT})), "+0700")
def test_get_current_timezone_templatetag_with_iana(self):
"""
Test the {% get_current_timezone %} templatetag with pytz.
"""
tpl = Template(
"{% load tz %}{% get_current_timezone as time_zone %}{{ time_zone }}"
)
for tz in get_timezones("Europe/Paris"):
with self.subTest(repr(tz)):
with timezone.override(tz):
self.assertEqual(tpl.render(Context()), "Europe/Paris")
tpl = Template(
"{% load tz %}{% timezone 'Europe/Paris' %}"
"{% get_current_timezone as time_zone %}{% endtimezone %}"
"{{ time_zone }}"
)
self.assertEqual(tpl.render(Context()), "Europe/Paris")
def test_get_current_timezone_templatetag_invalid_argument(self):
msg = (
"'get_current_timezone' requires 'as variable' (got "
"['get_current_timezone'])"
)
with self.assertRaisesMessage(TemplateSyntaxError, msg):
Template("{% load tz %}{% get_current_timezone %}").render()
@skipIf(sys.platform == "win32", "Windows uses non-standard time zone names")
def test_tz_template_context_processor(self):
"""
Test the django.template.context_processors.tz template context processor.
"""
tpl = Template("{{ TIME_ZONE }}")
context = Context()
self.assertEqual(tpl.render(context), "")
request_context = RequestContext(
HttpRequest(), processors=[context_processors.tz]
)
self.assertEqual(tpl.render(request_context), "Africa/Nairobi")
@requires_tz_support
def test_date_and_time_template_filters(self):
tpl = Template("{{ dt|date:'Y-m-d' }} at {{ dt|time:'H:i:s' }}")
ctx = Context({"dt": datetime.datetime(2011, 9, 1, 20, 20, 20, tzinfo=UTC)})
self.assertEqual(tpl.render(ctx), "2011-09-01 at 23:20:20")
with timezone.override(ICT):
self.assertEqual(tpl.render(ctx), "2011-09-02 at 03:20:20")
def test_date_and_time_template_filters_honor_localtime(self):
tpl = Template(
"{% load tz %}{% localtime off %}{{ dt|date:'Y-m-d' }} at "
"{{ dt|time:'H:i:s' }}{% endlocaltime %}"
)
ctx = Context({"dt": datetime.datetime(2011, 9, 1, 20, 20, 20, tzinfo=UTC)})
self.assertEqual(tpl.render(ctx), "2011-09-01 at 20:20:20")
with timezone.override(ICT):
self.assertEqual(tpl.render(ctx), "2011-09-01 at 20:20:20")
@requires_tz_support
def test_now_template_tag_uses_current_time_zone(self):
# Regression for #17343
tpl = Template('{% now "O" %}')
self.assertEqual(tpl.render(Context({})), "+0300")
with timezone.override(ICT):
self.assertEqual(tpl.render(Context({})), "+0700")
# RemovedInDjango50Warning: When the deprecation ends, remove setUpClass() and
# USE_L10N=False. The tests should remain because format-related settings will
# take precedence over locale-dictated formats.
@override_settings(
DATETIME_FORMAT="c", TIME_ZONE="Africa/Nairobi", USE_L10N=False, USE_TZ=False
)
class LegacyFormsTests(TestCase):
@classmethod
def setUpClass(cls):
with ignore_warnings(category=RemovedInDjango50Warning):
super().setUpClass()
def test_form(self):
form = EventForm({"dt": "2011-09-01 13:20:30"})
self.assertTrue(form.is_valid())
self.assertEqual(
form.cleaned_data["dt"], datetime.datetime(2011, 9, 1, 13, 20, 30)
)
def test_form_with_non_existent_time(self):
form = EventForm({"dt": "2011-03-27 02:30:00"})
for tz in get_timezones("Europe/Paris"):
with self.subTest(repr(tz)):
with timezone.override(tz):
# This is a bug.
self.assertTrue(form.is_valid())
self.assertEqual(
form.cleaned_data["dt"],
datetime.datetime(2011, 3, 27, 2, 30, 0),
)
def test_form_with_ambiguous_time(self):
form = EventForm({"dt": "2011-10-30 02:30:00"})
for tz in get_timezones("Europe/Paris"):
with self.subTest(repr(tz)):
with timezone.override(tz):
# This is a bug.
self.assertTrue(form.is_valid())
self.assertEqual(
form.cleaned_data["dt"],
datetime.datetime(2011, 10, 30, 2, 30, 0),
)
def test_split_form(self):
form = EventSplitForm({"dt_0": "2011-09-01", "dt_1": "13:20:30"})
self.assertTrue(form.is_valid())
self.assertEqual(
form.cleaned_data["dt"], datetime.datetime(2011, 9, 1, 13, 20, 30)
)
def test_model_form(self):
EventModelForm({"dt": "2011-09-01 13:20:30"}).save()
e = Event.objects.get()
self.assertEqual(e.dt, datetime.datetime(2011, 9, 1, 13, 20, 30))
# RemovedInDjango50Warning: When the deprecation ends, remove setUpClass() and
# USE_L10N=False. The tests should remain because format-related settings will
# take precedence over locale-dictated formats.
@override_settings(
DATETIME_FORMAT="c", TIME_ZONE="Africa/Nairobi", USE_L10N=False, USE_TZ=True
)
class NewFormsTests(TestCase):
@classmethod
def setUpClass(cls):
with ignore_warnings(category=RemovedInDjango50Warning):
super().setUpClass()
@requires_tz_support
def test_form(self):
form = EventForm({"dt": "2011-09-01 13:20:30"})
self.assertTrue(form.is_valid())
self.assertEqual(
form.cleaned_data["dt"],
datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC),
)
def test_form_with_other_timezone(self):
form = EventForm({"dt": "2011-09-01 17:20:30"})
with timezone.override(ICT):
self.assertTrue(form.is_valid())
self.assertEqual(
form.cleaned_data["dt"],
datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC),
)
def test_form_with_non_existent_time(self):
for tz in get_timezones("Europe/Paris"):
with self.subTest(repr(tz)):
with timezone.override(tz):
form = EventForm({"dt": "2011-03-27 02:30:00"})
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors["dt"],
[
"2011-03-27 02:30:00 couldn’t be interpreted in time zone "
"Europe/Paris; it may be ambiguous or it may not exist."
],
)
def test_form_with_ambiguous_time(self):
for tz in get_timezones("Europe/Paris"):
with self.subTest(repr(tz)):
with timezone.override(tz):
form = EventForm({"dt": "2011-10-30 02:30:00"})
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors["dt"],
[
"2011-10-30 02:30:00 couldn’t be interpreted in time zone "
"Europe/Paris; it may be ambiguous or it may not exist."
],
)
@requires_tz_support
def test_split_form(self):
form = EventSplitForm({"dt_0": "2011-09-01", "dt_1": "13:20:30"})
self.assertTrue(form.is_valid())
self.assertEqual(
form.cleaned_data["dt"],
datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC),
)
@requires_tz_support
def test_localized_form(self):
form = EventLocalizedForm(
initial={"dt": datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)}
)
with timezone.override(ICT):
self.assertIn("2011-09-01 17:20:30", str(form))
@requires_tz_support
def test_model_form(self):
EventModelForm({"dt": "2011-09-01 13:20:30"}).save()
e = Event.objects.get()
self.assertEqual(e.dt, datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC))
@requires_tz_support
def test_localized_model_form(self):
form = EventLocalizedModelForm(
instance=Event(dt=datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT))
)
with timezone.override(ICT):
self.assertIn("2011-09-01 17:20:30", str(form))
@override_settings(
DATETIME_FORMAT="c",
TIME_ZONE="Africa/Nairobi",
USE_L10N=False,
USE_TZ=True,
ROOT_URLCONF="timezones.urls",
)
class AdminTests(TestCase):
@classmethod
def setUpClass(cls):
with ignore_warnings(category=RemovedInDjango50Warning):
super().setUpClass()
@classmethod
def setUpTestData(cls):
cls.u1 = User.objects.create_user(
password="secret",
last_login=datetime.datetime(2007, 5, 30, 13, 20, 10, tzinfo=UTC),
is_superuser=True,
username="super",
first_name="Super",
last_name="User",
email="[email protected]",
is_staff=True,
is_active=True,
date_joined=datetime.datetime(2007, 5, 30, 13, 20, 10, tzinfo=UTC),
)
def setUp(self):
self.client.force_login(self.u1)
@requires_tz_support
def test_changelist(self):
e = Event.objects.create(
dt=datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)
)
response = self.client.get(reverse("admin_tz:timezones_event_changelist"))
self.assertContains(response, e.dt.astimezone(EAT).isoformat())
def test_changelist_in_other_timezone(self):
e = Event.objects.create(
dt=datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)
)
with timezone.override(ICT):
response = self.client.get(reverse("admin_tz:timezones_event_changelist"))
self.assertContains(response, e.dt.astimezone(ICT).isoformat())
@requires_tz_support
def test_change_editable(self):
e = Event.objects.create(
dt=datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)
)
response = self.client.get(
reverse("admin_tz:timezones_event_change", args=(e.pk,))
)
self.assertContains(response, e.dt.astimezone(EAT).date().isoformat())
self.assertContains(response, e.dt.astimezone(EAT).time().isoformat())
def test_change_editable_in_other_timezone(self):
e = Event.objects.create(
dt=datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)
)
with timezone.override(ICT):
response = self.client.get(
reverse("admin_tz:timezones_event_change", args=(e.pk,))
)
self.assertContains(response, e.dt.astimezone(ICT).date().isoformat())
self.assertContains(response, e.dt.astimezone(ICT).time().isoformat())
@requires_tz_support
def test_change_readonly(self):
t = Timestamp.objects.create()
response = self.client.get(
reverse("admin_tz:timezones_timestamp_change", args=(t.pk,))
)
self.assertContains(response, t.created.astimezone(EAT).isoformat())
def test_change_readonly_in_other_timezone(self):
t = Timestamp.objects.create()
with timezone.override(ICT):
response = self.client.get(
reverse("admin_tz:timezones_timestamp_change", args=(t.pk,))
)
self.assertContains(response, t.created.astimezone(ICT).isoformat())
|
8f4dfbad25f69a43a00fa1f9d3648b9fac48e192f01312e54bbe3bc3a1eca6f0 | 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))
|
bcf631b25aac6b58eb91a0d264f7a102f3111ce5e014455dc5d11e6660dbad14 | from unittest import mock
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from django.db import NotSupportedError, connection
from django.db.models import Prefetch, QuerySet, prefetch_related_objects
from django.db.models.query import get_prefetcher
from django.db.models.sql import Query
from django.test import (
TestCase,
override_settings,
skipIfDBFeature,
skipUnlessDBFeature,
)
from django.test.utils import CaptureQueriesContext, ignore_warnings
from django.utils.deprecation import RemovedInDjango50Warning
from .models import (
Article,
Author,
Author2,
AuthorAddress,
AuthorWithAge,
Bio,
Book,
Bookmark,
BookReview,
BookWithYear,
Comment,
Department,
Employee,
FavoriteAuthors,
House,
LessonEntry,
ModelIterableSubclass,
Person,
Qualification,
Reader,
Room,
TaggedItem,
Teacher,
WordEntry,
)
class TestDataMixin:
@classmethod
def setUpTestData(cls):
cls.book1 = Book.objects.create(title="Poems")
cls.book2 = Book.objects.create(title="Jane Eyre")
cls.book3 = Book.objects.create(title="Wuthering Heights")
cls.book4 = Book.objects.create(title="Sense and Sensibility")
cls.author1 = Author.objects.create(name="Charlotte", first_book=cls.book1)
cls.author2 = Author.objects.create(name="Anne", first_book=cls.book1)
cls.author3 = Author.objects.create(name="Emily", first_book=cls.book1)
cls.author4 = Author.objects.create(name="Jane", first_book=cls.book4)
cls.book1.authors.add(cls.author1, cls.author2, cls.author3)
cls.book2.authors.add(cls.author1)
cls.book3.authors.add(cls.author3)
cls.book4.authors.add(cls.author4)
cls.reader1 = Reader.objects.create(name="Amy")
cls.reader2 = Reader.objects.create(name="Belinda")
cls.reader1.books_read.add(cls.book1, cls.book4)
cls.reader2.books_read.add(cls.book2, cls.book4)
class PrefetchRelatedTests(TestDataMixin, TestCase):
def assertWhereContains(self, sql, needle):
where_idx = sql.index("WHERE")
self.assertEqual(
sql.count(str(needle), where_idx),
1,
msg="WHERE clause doesn't contain %s, actual SQL: %s"
% (needle, sql[where_idx:]),
)
def test_m2m_forward(self):
with self.assertNumQueries(2):
lists = [
list(b.authors.all()) for b in Book.objects.prefetch_related("authors")
]
normal_lists = [list(b.authors.all()) for b in Book.objects.all()]
self.assertEqual(lists, normal_lists)
def test_m2m_reverse(self):
with self.assertNumQueries(2):
lists = [
list(a.books.all()) for a in Author.objects.prefetch_related("books")
]
normal_lists = [list(a.books.all()) for a in Author.objects.all()]
self.assertEqual(lists, normal_lists)
def test_foreignkey_forward(self):
with self.assertNumQueries(2):
books = [
a.first_book for a in Author.objects.prefetch_related("first_book")
]
normal_books = [a.first_book for a in Author.objects.all()]
self.assertEqual(books, normal_books)
def test_foreignkey_reverse(self):
with self.assertNumQueries(2):
[
list(b.first_time_authors.all())
for b in Book.objects.prefetch_related("first_time_authors")
]
self.assertSequenceEqual(self.book2.authors.all(), [self.author1])
def test_onetoone_reverse_no_match(self):
# Regression for #17439
with self.assertNumQueries(2):
book = Book.objects.prefetch_related("bookwithyear").all()[0]
with self.assertNumQueries(0):
with self.assertRaises(BookWithYear.DoesNotExist):
book.bookwithyear
def test_onetoone_reverse_with_to_field_pk(self):
"""
A model (Bio) with a OneToOneField primary key (author) that references
a non-pk field (name) on the related model (Author) is prefetchable.
"""
Bio.objects.bulk_create(
[
Bio(author=self.author1),
Bio(author=self.author2),
Bio(author=self.author3),
]
)
authors = Author.objects.filter(
name__in=[self.author1, self.author2, self.author3],
).prefetch_related("bio")
with self.assertNumQueries(2):
for author in authors:
self.assertEqual(author.name, author.bio.author.name)
def test_survives_clone(self):
with self.assertNumQueries(2):
[
list(b.first_time_authors.all())
for b in Book.objects.prefetch_related("first_time_authors").exclude(
id=1000
)
]
def test_len(self):
with self.assertNumQueries(2):
qs = Book.objects.prefetch_related("first_time_authors")
len(qs)
[list(b.first_time_authors.all()) for b in qs]
def test_bool(self):
with self.assertNumQueries(2):
qs = Book.objects.prefetch_related("first_time_authors")
bool(qs)
[list(b.first_time_authors.all()) for b in qs]
def test_count(self):
with self.assertNumQueries(2):
qs = Book.objects.prefetch_related("first_time_authors")
[b.first_time_authors.count() for b in qs]
def test_exists(self):
with self.assertNumQueries(2):
qs = Book.objects.prefetch_related("first_time_authors")
[b.first_time_authors.exists() for b in qs]
def test_in_and_prefetch_related(self):
"""
Regression test for #20242 - QuerySet "in" didn't work the first time
when using prefetch_related. This was fixed by the removal of chunked
reads from QuerySet iteration in
70679243d1786e03557c28929f9762a119e3ac14.
"""
qs = Book.objects.prefetch_related("first_time_authors")
self.assertIn(qs[0], qs)
def test_clear(self):
with self.assertNumQueries(5):
with_prefetch = Author.objects.prefetch_related("books")
without_prefetch = with_prefetch.prefetch_related(None)
[list(a.books.all()) for a in without_prefetch]
def test_m2m_then_m2m(self):
"""A m2m can be followed through another m2m."""
with self.assertNumQueries(3):
qs = Author.objects.prefetch_related("books__read_by")
lists = [
[[str(r) for r in b.read_by.all()] for b in a.books.all()] for a in qs
]
self.assertEqual(
lists,
[
[["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre
[["Amy"]], # Anne - Poems
[["Amy"], []], # Emily - Poems, Wuthering Heights
[["Amy", "Belinda"]], # Jane - Sense and Sense
],
)
def test_overriding_prefetch(self):
with self.assertNumQueries(3):
qs = Author.objects.prefetch_related("books", "books__read_by")
lists = [
[[str(r) for r in b.read_by.all()] for b in a.books.all()] for a in qs
]
self.assertEqual(
lists,
[
[["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre
[["Amy"]], # Anne - Poems
[["Amy"], []], # Emily - Poems, Wuthering Heights
[["Amy", "Belinda"]], # Jane - Sense and Sense
],
)
with self.assertNumQueries(3):
qs = Author.objects.prefetch_related("books__read_by", "books")
lists = [
[[str(r) for r in b.read_by.all()] for b in a.books.all()] for a in qs
]
self.assertEqual(
lists,
[
[["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre
[["Amy"]], # Anne - Poems
[["Amy"], []], # Emily - Poems, Wuthering Heights
[["Amy", "Belinda"]], # Jane - Sense and Sense
],
)
def test_get(self):
"""
Objects retrieved with .get() get the prefetch behavior.
"""
# Need a double
with self.assertNumQueries(3):
author = Author.objects.prefetch_related("books__read_by").get(
name="Charlotte"
)
lists = [[str(r) for r in b.read_by.all()] for b in author.books.all()]
self.assertEqual(lists, [["Amy"], ["Belinda"]]) # Poems, Jane Eyre
def test_foreign_key_then_m2m(self):
"""
A m2m relation can be followed after a relation like ForeignKey that
doesn't have many objects.
"""
with self.assertNumQueries(2):
qs = Author.objects.select_related("first_book").prefetch_related(
"first_book__read_by"
)
lists = [[str(r) for r in a.first_book.read_by.all()] for a in qs]
self.assertEqual(lists, [["Amy"], ["Amy"], ["Amy"], ["Amy", "Belinda"]])
def test_reverse_one_to_one_then_m2m(self):
"""
A m2m relation can be followed after going through the select_related
reverse of an o2o.
"""
qs = Author.objects.prefetch_related("bio__books").select_related("bio")
with self.assertNumQueries(1):
list(qs.all())
Bio.objects.create(author=self.author1)
with self.assertNumQueries(2):
list(qs.all())
def test_attribute_error(self):
qs = Reader.objects.prefetch_related("books_read__xyz")
msg = (
"Cannot find 'xyz' on Book object, 'books_read__xyz' "
"is an invalid parameter to prefetch_related()"
)
with self.assertRaisesMessage(AttributeError, msg) as cm:
list(qs)
self.assertIn("prefetch_related", str(cm.exception))
def test_invalid_final_lookup(self):
qs = Book.objects.prefetch_related("authors__name")
msg = (
"'authors__name' does not resolve to an item that supports "
"prefetching - this is an invalid parameter to prefetch_related()."
)
with self.assertRaisesMessage(ValueError, msg) as cm:
list(qs)
self.assertIn("prefetch_related", str(cm.exception))
self.assertIn("name", str(cm.exception))
def test_prefetch_eq(self):
prefetch_1 = Prefetch("authors", queryset=Author.objects.all())
prefetch_2 = Prefetch("books", queryset=Book.objects.all())
self.assertEqual(prefetch_1, prefetch_1)
self.assertEqual(prefetch_1, mock.ANY)
self.assertNotEqual(prefetch_1, prefetch_2)
def test_forward_m2m_to_attr_conflict(self):
msg = "to_attr=authors conflicts with a field on the Book model."
authors = Author.objects.all()
with self.assertRaisesMessage(ValueError, msg):
list(
Book.objects.prefetch_related(
Prefetch("authors", queryset=authors, to_attr="authors"),
)
)
# Without the ValueError, an author was deleted due to the implicit
# save of the relation assignment.
self.assertEqual(self.book1.authors.count(), 3)
def test_reverse_m2m_to_attr_conflict(self):
msg = "to_attr=books conflicts with a field on the Author model."
poems = Book.objects.filter(title="Poems")
with self.assertRaisesMessage(ValueError, msg):
list(
Author.objects.prefetch_related(
Prefetch("books", queryset=poems, to_attr="books"),
)
)
# Without the ValueError, a book was deleted due to the implicit
# save of reverse relation assignment.
self.assertEqual(self.author1.books.count(), 2)
def test_m2m_then_reverse_fk_object_ids(self):
with CaptureQueriesContext(connection) as queries:
list(Book.objects.prefetch_related("authors__addresses"))
sql = queries[-1]["sql"]
self.assertWhereContains(sql, self.author1.name)
def test_m2m_then_m2m_object_ids(self):
with CaptureQueriesContext(connection) as queries:
list(Book.objects.prefetch_related("authors__favorite_authors"))
sql = queries[-1]["sql"]
self.assertWhereContains(sql, self.author1.name)
def test_m2m_then_reverse_one_to_one_object_ids(self):
with CaptureQueriesContext(connection) as queries:
list(Book.objects.prefetch_related("authors__authorwithage"))
sql = queries[-1]["sql"]
self.assertWhereContains(sql, self.author1.id)
def test_filter_deferred(self):
"""
Related filtering of prefetched querysets is deferred on m2m and
reverse m2o relations until necessary.
"""
add_q = Query.add_q
for relation in ["authors", "first_time_authors"]:
with self.subTest(relation=relation):
with mock.patch.object(
Query,
"add_q",
autospec=True,
side_effect=lambda self, q: add_q(self, q),
) as add_q_mock:
list(Book.objects.prefetch_related(relation))
self.assertEqual(add_q_mock.call_count, 1)
def test_named_values_list(self):
qs = Author.objects.prefetch_related("books")
self.assertCountEqual(
[value.name for value in qs.values_list("name", named=True)],
["Anne", "Charlotte", "Emily", "Jane"],
)
def test_m2m_prefetching_iterator_with_chunks(self):
with self.assertNumQueries(3):
authors = [
b.authors.first()
for b in Book.objects.prefetch_related("authors").iterator(chunk_size=2)
]
self.assertEqual(
authors,
[self.author1, self.author1, self.author3, self.author4],
)
@ignore_warnings(category=RemovedInDjango50Warning)
def test_m2m_prefetching_iterator_without_chunks(self):
# prefetch_related() is ignored.
with self.assertNumQueries(5):
authors = [
b.authors.first()
for b in Book.objects.prefetch_related("authors").iterator()
]
self.assertEqual(
authors,
[self.author1, self.author1, self.author3, self.author4],
)
def test_m2m_prefetching_iterator_without_chunks_warning(self):
msg = (
"Using QuerySet.iterator() after prefetch_related() without "
"specifying chunk_size is deprecated."
)
with self.assertWarnsMessage(RemovedInDjango50Warning, msg):
Book.objects.prefetch_related("authors").iterator()
class RawQuerySetTests(TestDataMixin, TestCase):
def test_basic(self):
with self.assertNumQueries(2):
books = Book.objects.raw(
"SELECT * FROM prefetch_related_book WHERE id = %s", (self.book1.id,)
).prefetch_related("authors")
book1 = list(books)[0]
with self.assertNumQueries(0):
self.assertCountEqual(
book1.authors.all(), [self.author1, self.author2, self.author3]
)
def test_prefetch_before_raw(self):
with self.assertNumQueries(2):
books = Book.objects.prefetch_related("authors").raw(
"SELECT * FROM prefetch_related_book WHERE id = %s", (self.book1.id,)
)
book1 = list(books)[0]
with self.assertNumQueries(0):
self.assertCountEqual(
book1.authors.all(), [self.author1, self.author2, self.author3]
)
def test_clear(self):
with self.assertNumQueries(5):
with_prefetch = Author.objects.raw(
"SELECT * FROM prefetch_related_author"
).prefetch_related("books")
without_prefetch = with_prefetch.prefetch_related(None)
[list(a.books.all()) for a in without_prefetch]
class CustomPrefetchTests(TestCase):
@classmethod
def traverse_qs(cls, obj_iter, path):
"""
Helper method that returns a list containing a list of the objects in the
obj_iter. Then for each object in the obj_iter, the path will be
recursively travelled and the found objects are added to the return value.
"""
ret_val = []
if hasattr(obj_iter, "all"):
obj_iter = obj_iter.all()
try:
iter(obj_iter)
except TypeError:
obj_iter = [obj_iter]
for obj in obj_iter:
rel_objs = []
for part in path:
if not part:
continue
try:
related = getattr(obj, part[0])
except ObjectDoesNotExist:
continue
if related is not None:
rel_objs.extend(cls.traverse_qs(related, [part[1:]]))
ret_val.append((obj, rel_objs))
return ret_val
@classmethod
def setUpTestData(cls):
cls.person1 = Person.objects.create(name="Joe")
cls.person2 = Person.objects.create(name="Mary")
# Set main_room for each house before creating the next one for
# databases where supports_nullable_unique_constraints is False.
cls.house1 = House.objects.create(
name="House 1", address="123 Main St", owner=cls.person1
)
cls.room1_1 = Room.objects.create(name="Dining room", house=cls.house1)
cls.room1_2 = Room.objects.create(name="Lounge", house=cls.house1)
cls.room1_3 = Room.objects.create(name="Kitchen", house=cls.house1)
cls.house1.main_room = cls.room1_1
cls.house1.save()
cls.person1.houses.add(cls.house1)
cls.house2 = House.objects.create(
name="House 2", address="45 Side St", owner=cls.person1
)
cls.room2_1 = Room.objects.create(name="Dining room", house=cls.house2)
cls.room2_2 = Room.objects.create(name="Lounge", house=cls.house2)
cls.room2_3 = Room.objects.create(name="Kitchen", house=cls.house2)
cls.house2.main_room = cls.room2_1
cls.house2.save()
cls.person1.houses.add(cls.house2)
cls.house3 = House.objects.create(
name="House 3", address="6 Downing St", owner=cls.person2
)
cls.room3_1 = Room.objects.create(name="Dining room", house=cls.house3)
cls.room3_2 = Room.objects.create(name="Lounge", house=cls.house3)
cls.room3_3 = Room.objects.create(name="Kitchen", house=cls.house3)
cls.house3.main_room = cls.room3_1
cls.house3.save()
cls.person2.houses.add(cls.house3)
cls.house4 = House.objects.create(
name="house 4", address="7 Regents St", owner=cls.person2
)
cls.room4_1 = Room.objects.create(name="Dining room", house=cls.house4)
cls.room4_2 = Room.objects.create(name="Lounge", house=cls.house4)
cls.room4_3 = Room.objects.create(name="Kitchen", house=cls.house4)
cls.house4.main_room = cls.room4_1
cls.house4.save()
cls.person2.houses.add(cls.house4)
def test_traverse_qs(self):
qs = Person.objects.prefetch_related("houses")
related_objs_normal = ([list(p.houses.all()) for p in qs],)
related_objs_from_traverse = [
[inner[0] for inner in o[1]] for o in self.traverse_qs(qs, [["houses"]])
]
self.assertEqual(related_objs_normal, (related_objs_from_traverse,))
def test_ambiguous(self):
# Ambiguous: Lookup was already seen with a different queryset.
msg = (
"'houses' lookup was already seen with a different queryset. You "
"may need to adjust the ordering of your lookups."
)
# lookup.queryset shouldn't be evaluated.
with self.assertNumQueries(3):
with self.assertRaisesMessage(ValueError, msg):
self.traverse_qs(
Person.objects.prefetch_related(
"houses__rooms",
Prefetch("houses", queryset=House.objects.all()),
),
[["houses", "rooms"]],
)
# Ambiguous: Lookup houses_lst doesn't yet exist when performing
# houses_lst__rooms.
msg = (
"Cannot find 'houses_lst' on Person object, 'houses_lst__rooms' is "
"an invalid parameter to prefetch_related()"
)
with self.assertRaisesMessage(AttributeError, msg):
self.traverse_qs(
Person.objects.prefetch_related(
"houses_lst__rooms",
Prefetch(
"houses", queryset=House.objects.all(), to_attr="houses_lst"
),
),
[["houses", "rooms"]],
)
# Not ambiguous.
self.traverse_qs(
Person.objects.prefetch_related("houses__rooms", "houses"),
[["houses", "rooms"]],
)
self.traverse_qs(
Person.objects.prefetch_related(
"houses__rooms",
Prefetch("houses", queryset=House.objects.all(), to_attr="houses_lst"),
),
[["houses", "rooms"]],
)
def test_m2m(self):
# Control lookups.
with self.assertNumQueries(2):
lst1 = self.traverse_qs(
Person.objects.prefetch_related("houses"), [["houses"]]
)
# Test lookups.
with self.assertNumQueries(2):
lst2 = self.traverse_qs(
Person.objects.prefetch_related(Prefetch("houses")), [["houses"]]
)
self.assertEqual(lst1, lst2)
with self.assertNumQueries(2):
lst2 = self.traverse_qs(
Person.objects.prefetch_related(
Prefetch("houses", to_attr="houses_lst")
),
[["houses_lst"]],
)
self.assertEqual(lst1, lst2)
def test_reverse_m2m(self):
# Control lookups.
with self.assertNumQueries(2):
lst1 = self.traverse_qs(
House.objects.prefetch_related("occupants"), [["occupants"]]
)
# Test lookups.
with self.assertNumQueries(2):
lst2 = self.traverse_qs(
House.objects.prefetch_related(Prefetch("occupants")), [["occupants"]]
)
self.assertEqual(lst1, lst2)
with self.assertNumQueries(2):
lst2 = self.traverse_qs(
House.objects.prefetch_related(
Prefetch("occupants", to_attr="occupants_lst")
),
[["occupants_lst"]],
)
self.assertEqual(lst1, lst2)
def test_m2m_through_fk(self):
# Control lookups.
with self.assertNumQueries(3):
lst1 = self.traverse_qs(
Room.objects.prefetch_related("house__occupants"),
[["house", "occupants"]],
)
# Test lookups.
with self.assertNumQueries(3):
lst2 = self.traverse_qs(
Room.objects.prefetch_related(Prefetch("house__occupants")),
[["house", "occupants"]],
)
self.assertEqual(lst1, lst2)
with self.assertNumQueries(3):
lst2 = self.traverse_qs(
Room.objects.prefetch_related(
Prefetch("house__occupants", to_attr="occupants_lst")
),
[["house", "occupants_lst"]],
)
self.assertEqual(lst1, lst2)
def test_m2m_through_gfk(self):
TaggedItem.objects.create(tag="houses", content_object=self.house1)
TaggedItem.objects.create(tag="houses", content_object=self.house2)
# Control lookups.
with self.assertNumQueries(3):
lst1 = self.traverse_qs(
TaggedItem.objects.filter(tag="houses").prefetch_related(
"content_object__rooms"
),
[["content_object", "rooms"]],
)
# Test lookups.
with self.assertNumQueries(3):
lst2 = self.traverse_qs(
TaggedItem.objects.prefetch_related(
Prefetch("content_object"),
Prefetch("content_object__rooms", to_attr="rooms_lst"),
),
[["content_object", "rooms_lst"]],
)
self.assertEqual(lst1, lst2)
def test_o2m_through_m2m(self):
# Control lookups.
with self.assertNumQueries(3):
lst1 = self.traverse_qs(
Person.objects.prefetch_related("houses", "houses__rooms"),
[["houses", "rooms"]],
)
# Test lookups.
with self.assertNumQueries(3):
lst2 = self.traverse_qs(
Person.objects.prefetch_related(Prefetch("houses"), "houses__rooms"),
[["houses", "rooms"]],
)
self.assertEqual(lst1, lst2)
with self.assertNumQueries(3):
lst2 = self.traverse_qs(
Person.objects.prefetch_related(
Prefetch("houses"), Prefetch("houses__rooms")
),
[["houses", "rooms"]],
)
self.assertEqual(lst1, lst2)
with self.assertNumQueries(3):
lst2 = self.traverse_qs(
Person.objects.prefetch_related(
Prefetch("houses", to_attr="houses_lst"), "houses_lst__rooms"
),
[["houses_lst", "rooms"]],
)
self.assertEqual(lst1, lst2)
with self.assertNumQueries(3):
lst2 = self.traverse_qs(
Person.objects.prefetch_related(
Prefetch("houses", to_attr="houses_lst"),
Prefetch("houses_lst__rooms", to_attr="rooms_lst"),
),
[["houses_lst", "rooms_lst"]],
)
self.assertEqual(lst1, lst2)
def test_generic_rel(self):
bookmark = Bookmark.objects.create(url="http://www.djangoproject.com/")
TaggedItem.objects.create(content_object=bookmark, tag="django")
TaggedItem.objects.create(
content_object=bookmark, favorite=bookmark, tag="python"
)
# Control lookups.
with self.assertNumQueries(4):
lst1 = self.traverse_qs(
Bookmark.objects.prefetch_related(
"tags", "tags__content_object", "favorite_tags"
),
[["tags", "content_object"], ["favorite_tags"]],
)
# Test lookups.
with self.assertNumQueries(4):
lst2 = self.traverse_qs(
Bookmark.objects.prefetch_related(
Prefetch("tags", to_attr="tags_lst"),
Prefetch("tags_lst__content_object"),
Prefetch("favorite_tags"),
),
[["tags_lst", "content_object"], ["favorite_tags"]],
)
self.assertEqual(lst1, lst2)
def test_traverse_single_item_property(self):
# Control lookups.
with self.assertNumQueries(5):
lst1 = self.traverse_qs(
Person.objects.prefetch_related(
"houses__rooms",
"primary_house__occupants__houses",
),
[["primary_house", "occupants", "houses"]],
)
# Test lookups.
with self.assertNumQueries(5):
lst2 = self.traverse_qs(
Person.objects.prefetch_related(
"houses__rooms",
Prefetch("primary_house__occupants", to_attr="occupants_lst"),
"primary_house__occupants_lst__houses",
),
[["primary_house", "occupants_lst", "houses"]],
)
self.assertEqual(lst1, lst2)
def test_traverse_multiple_items_property(self):
# Control lookups.
with self.assertNumQueries(4):
lst1 = self.traverse_qs(
Person.objects.prefetch_related(
"houses",
"all_houses__occupants__houses",
),
[["all_houses", "occupants", "houses"]],
)
# Test lookups.
with self.assertNumQueries(4):
lst2 = self.traverse_qs(
Person.objects.prefetch_related(
"houses",
Prefetch("all_houses__occupants", to_attr="occupants_lst"),
"all_houses__occupants_lst__houses",
),
[["all_houses", "occupants_lst", "houses"]],
)
self.assertEqual(lst1, lst2)
def test_custom_qs(self):
# Test basic.
with self.assertNumQueries(2):
lst1 = list(Person.objects.prefetch_related("houses"))
with self.assertNumQueries(2):
lst2 = list(
Person.objects.prefetch_related(
Prefetch(
"houses", queryset=House.objects.all(), to_attr="houses_lst"
)
)
)
self.assertEqual(
self.traverse_qs(lst1, [["houses"]]),
self.traverse_qs(lst2, [["houses_lst"]]),
)
# Test queryset filtering.
with self.assertNumQueries(2):
lst2 = list(
Person.objects.prefetch_related(
Prefetch(
"houses",
queryset=House.objects.filter(
pk__in=[self.house1.pk, self.house3.pk]
),
to_attr="houses_lst",
)
)
)
self.assertEqual(len(lst2[0].houses_lst), 1)
self.assertEqual(lst2[0].houses_lst[0], self.house1)
self.assertEqual(len(lst2[1].houses_lst), 1)
self.assertEqual(lst2[1].houses_lst[0], self.house3)
# Test flattened.
with self.assertNumQueries(3):
lst1 = list(Person.objects.prefetch_related("houses__rooms"))
with self.assertNumQueries(3):
lst2 = list(
Person.objects.prefetch_related(
Prefetch(
"houses__rooms",
queryset=Room.objects.all(),
to_attr="rooms_lst",
)
)
)
self.assertEqual(
self.traverse_qs(lst1, [["houses", "rooms"]]),
self.traverse_qs(lst2, [["houses", "rooms_lst"]]),
)
# Test inner select_related.
with self.assertNumQueries(3):
lst1 = list(Person.objects.prefetch_related("houses__owner"))
with self.assertNumQueries(2):
lst2 = list(
Person.objects.prefetch_related(
Prefetch("houses", queryset=House.objects.select_related("owner"))
)
)
self.assertEqual(
self.traverse_qs(lst1, [["houses", "owner"]]),
self.traverse_qs(lst2, [["houses", "owner"]]),
)
# Test inner prefetch.
inner_rooms_qs = Room.objects.filter(pk__in=[self.room1_1.pk, self.room1_2.pk])
houses_qs_prf = House.objects.prefetch_related(
Prefetch("rooms", queryset=inner_rooms_qs, to_attr="rooms_lst")
)
with self.assertNumQueries(4):
lst2 = list(
Person.objects.prefetch_related(
Prefetch(
"houses",
queryset=houses_qs_prf.filter(pk=self.house1.pk),
to_attr="houses_lst",
),
Prefetch("houses_lst__rooms_lst__main_room_of"),
)
)
self.assertEqual(len(lst2[0].houses_lst[0].rooms_lst), 2)
self.assertEqual(lst2[0].houses_lst[0].rooms_lst[0], self.room1_1)
self.assertEqual(lst2[0].houses_lst[0].rooms_lst[1], self.room1_2)
self.assertEqual(lst2[0].houses_lst[0].rooms_lst[0].main_room_of, self.house1)
self.assertEqual(len(lst2[1].houses_lst), 0)
# Test ForwardManyToOneDescriptor.
houses = House.objects.select_related("owner")
with self.assertNumQueries(6):
rooms = Room.objects.prefetch_related("house")
lst1 = self.traverse_qs(rooms, [["house", "owner"]])
with self.assertNumQueries(2):
rooms = Room.objects.prefetch_related(Prefetch("house", queryset=houses))
lst2 = self.traverse_qs(rooms, [["house", "owner"]])
self.assertEqual(lst1, lst2)
with self.assertNumQueries(2):
houses = House.objects.select_related("owner")
rooms = Room.objects.prefetch_related(
Prefetch("house", queryset=houses, to_attr="house_attr")
)
lst2 = self.traverse_qs(rooms, [["house_attr", "owner"]])
self.assertEqual(lst1, lst2)
room = Room.objects.prefetch_related(
Prefetch("house", queryset=houses.filter(address="DoesNotExist"))
).first()
with self.assertRaises(ObjectDoesNotExist):
getattr(room, "house")
room = Room.objects.prefetch_related(
Prefetch(
"house",
queryset=houses.filter(address="DoesNotExist"),
to_attr="house_attr",
)
).first()
self.assertIsNone(room.house_attr)
rooms = Room.objects.prefetch_related(
Prefetch("house", queryset=House.objects.only("name"))
)
with self.assertNumQueries(2):
getattr(rooms.first().house, "name")
with self.assertNumQueries(3):
getattr(rooms.first().house, "address")
# Test ReverseOneToOneDescriptor.
houses = House.objects.select_related("owner")
with self.assertNumQueries(6):
rooms = Room.objects.prefetch_related("main_room_of")
lst1 = self.traverse_qs(rooms, [["main_room_of", "owner"]])
with self.assertNumQueries(2):
rooms = Room.objects.prefetch_related(
Prefetch("main_room_of", queryset=houses)
)
lst2 = self.traverse_qs(rooms, [["main_room_of", "owner"]])
self.assertEqual(lst1, lst2)
with self.assertNumQueries(2):
rooms = list(
Room.objects.prefetch_related(
Prefetch(
"main_room_of",
queryset=houses,
to_attr="main_room_of_attr",
)
)
)
lst2 = self.traverse_qs(rooms, [["main_room_of_attr", "owner"]])
self.assertEqual(lst1, lst2)
room = (
Room.objects.filter(main_room_of__isnull=False)
.prefetch_related(
Prefetch("main_room_of", queryset=houses.filter(address="DoesNotExist"))
)
.first()
)
with self.assertRaises(ObjectDoesNotExist):
getattr(room, "main_room_of")
room = (
Room.objects.filter(main_room_of__isnull=False)
.prefetch_related(
Prefetch(
"main_room_of",
queryset=houses.filter(address="DoesNotExist"),
to_attr="main_room_of_attr",
)
)
.first()
)
self.assertIsNone(room.main_room_of_attr)
# The custom queryset filters should be applied to the queryset
# instance returned by the manager.
person = Person.objects.prefetch_related(
Prefetch("houses", queryset=House.objects.filter(name="House 1")),
).get(pk=self.person1.pk)
self.assertEqual(
list(person.houses.all()),
list(person.houses.all().all()),
)
def test_nested_prefetch_related_are_not_overwritten(self):
# Regression test for #24873
houses_2 = House.objects.prefetch_related(Prefetch("rooms"))
persons = Person.objects.prefetch_related(Prefetch("houses", queryset=houses_2))
houses = House.objects.prefetch_related(Prefetch("occupants", queryset=persons))
list(houses) # queryset must be evaluated once to reproduce the bug.
self.assertEqual(
houses.all()[0].occupants.all()[0].houses.all()[1].rooms.all()[0],
self.room2_1,
)
def test_nested_prefetch_related_with_duplicate_prefetcher(self):
"""
Nested prefetches whose name clashes with descriptor names
(Person.houses here) are allowed.
"""
occupants = Person.objects.prefetch_related(
Prefetch("houses", to_attr="some_attr_name"),
Prefetch("houses", queryset=House.objects.prefetch_related("main_room")),
)
houses = House.objects.prefetch_related(
Prefetch("occupants", queryset=occupants)
)
with self.assertNumQueries(5):
self.traverse_qs(list(houses), [["occupants", "houses", "main_room"]])
def test_values_queryset(self):
msg = "Prefetch querysets cannot use raw(), values(), and values_list()."
with self.assertRaisesMessage(ValueError, msg):
Prefetch("houses", House.objects.values("pk"))
with self.assertRaisesMessage(ValueError, msg):
Prefetch("houses", House.objects.values_list("pk"))
# That error doesn't affect managers with custom ModelIterable subclasses
self.assertIs(
Teacher.objects_custom.all()._iterable_class, ModelIterableSubclass
)
Prefetch("teachers", Teacher.objects_custom.all())
def test_raw_queryset(self):
msg = "Prefetch querysets cannot use raw(), values(), and values_list()."
with self.assertRaisesMessage(ValueError, msg):
Prefetch("houses", House.objects.raw("select pk from house"))
def test_to_attr_doesnt_cache_through_attr_as_list(self):
house = House.objects.prefetch_related(
Prefetch("rooms", queryset=Room.objects.all(), to_attr="to_rooms"),
).get(pk=self.house3.pk)
self.assertIsInstance(house.rooms.all(), QuerySet)
def test_to_attr_cached_property(self):
persons = Person.objects.prefetch_related(
Prefetch("houses", House.objects.all(), to_attr="cached_all_houses"),
)
for person in persons:
# To bypass caching at the related descriptor level, don't use
# person.houses.all() here.
all_houses = list(House.objects.filter(occupants=person))
with self.assertNumQueries(0):
self.assertEqual(person.cached_all_houses, all_houses)
def test_filter_deferred(self):
"""
Related filtering of prefetched querysets is deferred until necessary.
"""
add_q = Query.add_q
with mock.patch.object(
Query,
"add_q",
autospec=True,
side_effect=lambda self, q: add_q(self, q),
) as add_q_mock:
list(
House.objects.prefetch_related(
Prefetch("occupants", queryset=Person.objects.all())
)
)
self.assertEqual(add_q_mock.call_count, 1)
class DefaultManagerTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.qual1 = Qualification.objects.create(name="BA")
cls.qual2 = Qualification.objects.create(name="BSci")
cls.qual3 = Qualification.objects.create(name="MA")
cls.qual4 = Qualification.objects.create(name="PhD")
cls.teacher1 = Teacher.objects.create(name="Mr Cleese")
cls.teacher2 = Teacher.objects.create(name="Mr Idle")
cls.teacher3 = Teacher.objects.create(name="Mr Chapman")
cls.teacher1.qualifications.add(cls.qual1, cls.qual2, cls.qual3, cls.qual4)
cls.teacher2.qualifications.add(cls.qual1)
cls.teacher3.qualifications.add(cls.qual2)
cls.dept1 = Department.objects.create(name="English")
cls.dept2 = Department.objects.create(name="Physics")
cls.dept1.teachers.add(cls.teacher1, cls.teacher2)
cls.dept2.teachers.add(cls.teacher1, cls.teacher3)
def test_m2m_then_m2m(self):
with self.assertNumQueries(3):
# When we prefetch the teachers, and force the query, we don't want
# the default manager on teachers to immediately get all the related
# qualifications, since this will do one query per teacher.
qs = Department.objects.prefetch_related("teachers")
depts = "".join(
"%s department: %s\n"
% (dept.name, ", ".join(str(t) for t in dept.teachers.all()))
for dept in qs
)
self.assertEqual(
depts,
"English department: Mr Cleese (BA, BSci, MA, PhD), Mr Idle (BA)\n"
"Physics department: Mr Cleese (BA, BSci, MA, PhD), Mr Chapman "
"(BSci)\n",
)
class GenericRelationTests(TestCase):
@classmethod
def setUpTestData(cls):
book1 = Book.objects.create(title="Winnie the Pooh")
book2 = Book.objects.create(title="Do you like green eggs and spam?")
book3 = Book.objects.create(title="Three Men In A Boat")
reader1 = Reader.objects.create(name="me")
reader2 = Reader.objects.create(name="you")
reader3 = Reader.objects.create(name="someone")
book1.read_by.add(reader1, reader2)
book2.read_by.add(reader2)
book3.read_by.add(reader3)
cls.book1, cls.book2, cls.book3 = book1, book2, book3
cls.reader1, cls.reader2, cls.reader3 = reader1, reader2, reader3
def test_prefetch_GFK(self):
TaggedItem.objects.create(tag="awesome", content_object=self.book1)
TaggedItem.objects.create(tag="great", content_object=self.reader1)
TaggedItem.objects.create(tag="outstanding", content_object=self.book2)
TaggedItem.objects.create(tag="amazing", content_object=self.reader3)
# 1 for TaggedItem table, 1 for Book table, 1 for Reader table
with self.assertNumQueries(3):
qs = TaggedItem.objects.prefetch_related("content_object")
list(qs)
def test_prefetch_GFK_nonint_pk(self):
Comment.objects.create(comment="awesome", content_object=self.book1)
# 1 for Comment table, 1 for Book table
with self.assertNumQueries(2):
qs = Comment.objects.prefetch_related("content_object")
[c.content_object for c in qs]
def test_prefetch_GFK_uuid_pk(self):
article = Article.objects.create(name="Django")
Comment.objects.create(comment="awesome", content_object_uuid=article)
qs = Comment.objects.prefetch_related("content_object_uuid")
self.assertEqual([c.content_object_uuid for c in qs], [article])
def test_prefetch_GFK_fk_pk(self):
book = Book.objects.create(title="Poems")
book_with_year = BookWithYear.objects.create(book=book, published_year=2019)
Comment.objects.create(comment="awesome", content_object=book_with_year)
qs = Comment.objects.prefetch_related("content_object")
self.assertEqual([c.content_object for c in qs], [book_with_year])
def test_traverse_GFK(self):
"""
A 'content_object' can be traversed with prefetch_related() and
get to related objects on the other side (assuming it is suitably
filtered)
"""
TaggedItem.objects.create(tag="awesome", content_object=self.book1)
TaggedItem.objects.create(tag="awesome", content_object=self.book2)
TaggedItem.objects.create(tag="awesome", content_object=self.book3)
TaggedItem.objects.create(tag="awesome", content_object=self.reader1)
TaggedItem.objects.create(tag="awesome", content_object=self.reader2)
ct = ContentType.objects.get_for_model(Book)
# We get 3 queries - 1 for main query, 1 for content_objects since they
# all use the same table, and 1 for the 'read_by' relation.
with self.assertNumQueries(3):
# If we limit to books, we know that they will have 'read_by'
# attributes, so the following makes sense:
qs = TaggedItem.objects.filter(
content_type=ct, tag="awesome"
).prefetch_related("content_object__read_by")
readers_of_awesome_books = {
r.name for tag in qs for r in tag.content_object.read_by.all()
}
self.assertEqual(readers_of_awesome_books, {"me", "you", "someone"})
def test_nullable_GFK(self):
TaggedItem.objects.create(
tag="awesome", content_object=self.book1, created_by=self.reader1
)
TaggedItem.objects.create(tag="great", content_object=self.book2)
TaggedItem.objects.create(tag="rubbish", content_object=self.book3)
with self.assertNumQueries(2):
result = [
t.created_by for t in TaggedItem.objects.prefetch_related("created_by")
]
self.assertEqual(result, [t.created_by for t in TaggedItem.objects.all()])
def test_generic_relation(self):
bookmark = Bookmark.objects.create(url="http://www.djangoproject.com/")
TaggedItem.objects.create(content_object=bookmark, tag="django")
TaggedItem.objects.create(content_object=bookmark, tag="python")
with self.assertNumQueries(2):
tags = [
t.tag
for b in Bookmark.objects.prefetch_related("tags")
for t in b.tags.all()
]
self.assertEqual(sorted(tags), ["django", "python"])
def test_charfield_GFK(self):
b = Bookmark.objects.create(url="http://www.djangoproject.com/")
TaggedItem.objects.create(content_object=b, tag="django")
TaggedItem.objects.create(content_object=b, favorite=b, tag="python")
with self.assertNumQueries(3):
bookmark = Bookmark.objects.filter(pk=b.pk).prefetch_related(
"tags", "favorite_tags"
)[0]
self.assertEqual(
sorted(i.tag for i in bookmark.tags.all()), ["django", "python"]
)
self.assertEqual([i.tag for i in bookmark.favorite_tags.all()], ["python"])
def test_custom_queryset(self):
bookmark = Bookmark.objects.create(url="http://www.djangoproject.com/")
django_tag = TaggedItem.objects.create(content_object=bookmark, tag="django")
TaggedItem.objects.create(content_object=bookmark, tag="python")
with self.assertNumQueries(2):
bookmark = Bookmark.objects.prefetch_related(
Prefetch("tags", TaggedItem.objects.filter(tag="django")),
).get()
with self.assertNumQueries(0):
self.assertEqual(list(bookmark.tags.all()), [django_tag])
# The custom queryset filters should be applied to the queryset
# instance returned by the manager.
self.assertEqual(list(bookmark.tags.all()), list(bookmark.tags.all().all()))
def test_deleted_GFK(self):
TaggedItem.objects.create(tag="awesome", content_object=self.book1)
TaggedItem.objects.create(tag="awesome", content_object=self.book2)
ct = ContentType.objects.get_for_model(Book)
book1_pk = self.book1.pk
self.book1.delete()
with self.assertNumQueries(2):
qs = TaggedItem.objects.filter(tag="awesome").prefetch_related(
"content_object"
)
result = [
(tag.object_id, tag.content_type_id, tag.content_object) for tag in qs
]
self.assertEqual(
result,
[
(book1_pk, ct.pk, None),
(self.book2.pk, ct.pk, self.book2),
],
)
class MultiTableInheritanceTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.book1 = BookWithYear.objects.create(title="Poems", published_year=2010)
cls.book2 = BookWithYear.objects.create(title="More poems", published_year=2011)
cls.author1 = AuthorWithAge.objects.create(
name="Jane", first_book=cls.book1, age=50
)
cls.author2 = AuthorWithAge.objects.create(
name="Tom", first_book=cls.book1, age=49
)
cls.author3 = AuthorWithAge.objects.create(
name="Robert", first_book=cls.book2, age=48
)
cls.author_address = AuthorAddress.objects.create(
author=cls.author1, address="SomeStreet 1"
)
cls.book2.aged_authors.add(cls.author2, cls.author3)
cls.br1 = BookReview.objects.create(book=cls.book1, notes="review book1")
cls.br2 = BookReview.objects.create(book=cls.book2, notes="review book2")
def test_foreignkey(self):
with self.assertNumQueries(2):
qs = AuthorWithAge.objects.prefetch_related("addresses")
addresses = [
[str(address) for address in obj.addresses.all()] for obj in qs
]
self.assertEqual(addresses, [[str(self.author_address)], [], []])
def test_foreignkey_to_inherited(self):
with self.assertNumQueries(2):
qs = BookReview.objects.prefetch_related("book")
titles = [obj.book.title for obj in qs]
self.assertCountEqual(titles, ["Poems", "More poems"])
def test_m2m_to_inheriting_model(self):
qs = AuthorWithAge.objects.prefetch_related("books_with_year")
with self.assertNumQueries(2):
lst = [
[str(book) for book in author.books_with_year.all()] for author in qs
]
qs = AuthorWithAge.objects.all()
lst2 = [[str(book) for book in author.books_with_year.all()] for author in qs]
self.assertEqual(lst, lst2)
qs = BookWithYear.objects.prefetch_related("aged_authors")
with self.assertNumQueries(2):
lst = [[str(author) for author in book.aged_authors.all()] for book in qs]
qs = BookWithYear.objects.all()
lst2 = [[str(author) for author in book.aged_authors.all()] for book in qs]
self.assertEqual(lst, lst2)
def test_parent_link_prefetch(self):
with self.assertNumQueries(2):
[a.author for a in AuthorWithAge.objects.prefetch_related("author")]
@override_settings(DEBUG=True)
def test_child_link_prefetch(self):
with self.assertNumQueries(2):
authors = [
a.authorwithage
for a in Author.objects.prefetch_related("authorwithage")
]
# Regression for #18090: the prefetching query must include an IN clause.
# Note that on Oracle the table name is upper case in the generated SQL,
# thus the .lower() call.
self.assertIn("authorwithage", connection.queries[-1]["sql"].lower())
self.assertIn(" IN ", connection.queries[-1]["sql"])
self.assertEqual(authors, [a.authorwithage for a in Author.objects.all()])
class ForeignKeyToFieldTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.book = Book.objects.create(title="Poems")
cls.author1 = Author.objects.create(name="Jane", first_book=cls.book)
cls.author2 = Author.objects.create(name="Tom", first_book=cls.book)
cls.author3 = Author.objects.create(name="Robert", first_book=cls.book)
cls.author_address = AuthorAddress.objects.create(
author=cls.author1, address="SomeStreet 1"
)
FavoriteAuthors.objects.create(author=cls.author1, likes_author=cls.author2)
FavoriteAuthors.objects.create(author=cls.author2, likes_author=cls.author3)
FavoriteAuthors.objects.create(author=cls.author3, likes_author=cls.author1)
def test_foreignkey(self):
with self.assertNumQueries(2):
qs = Author.objects.prefetch_related("addresses")
addresses = [
[str(address) for address in obj.addresses.all()] for obj in qs
]
self.assertEqual(addresses, [[str(self.author_address)], [], []])
def test_m2m(self):
with self.assertNumQueries(3):
qs = Author.objects.prefetch_related("favorite_authors", "favors_me")
favorites = [
(
[str(i_like) for i_like in author.favorite_authors.all()],
[str(likes_me) for likes_me in author.favors_me.all()],
)
for author in qs
]
self.assertEqual(
favorites,
[
([str(self.author2)], [str(self.author3)]),
([str(self.author3)], [str(self.author1)]),
([str(self.author1)], [str(self.author2)]),
],
)
class LookupOrderingTest(TestCase):
"""
Test cases that demonstrate that ordering of lookups is important, and
ensure it is preserved.
"""
@classmethod
def setUpTestData(cls):
person1 = Person.objects.create(name="Joe")
person2 = Person.objects.create(name="Mary")
# Set main_room for each house before creating the next one for
# databases where supports_nullable_unique_constraints is False.
house1 = House.objects.create(address="123 Main St")
room1_1 = Room.objects.create(name="Dining room", house=house1)
Room.objects.create(name="Lounge", house=house1)
Room.objects.create(name="Kitchen", house=house1)
house1.main_room = room1_1
house1.save()
person1.houses.add(house1)
house2 = House.objects.create(address="45 Side St")
room2_1 = Room.objects.create(name="Dining room", house=house2)
Room.objects.create(name="Lounge", house=house2)
house2.main_room = room2_1
house2.save()
person1.houses.add(house2)
house3 = House.objects.create(address="6 Downing St")
room3_1 = Room.objects.create(name="Dining room", house=house3)
Room.objects.create(name="Lounge", house=house3)
Room.objects.create(name="Kitchen", house=house3)
house3.main_room = room3_1
house3.save()
person2.houses.add(house3)
house4 = House.objects.create(address="7 Regents St")
room4_1 = Room.objects.create(name="Dining room", house=house4)
Room.objects.create(name="Lounge", house=house4)
house4.main_room = room4_1
house4.save()
person2.houses.add(house4)
def test_order(self):
with self.assertNumQueries(4):
# The following two queries must be done in the same order as written,
# otherwise 'primary_house' will cause non-prefetched lookups
qs = Person.objects.prefetch_related(
"houses__rooms", "primary_house__occupants"
)
[list(p.primary_house.occupants.all()) for p in qs]
class NullableTest(TestCase):
@classmethod
def setUpTestData(cls):
boss = Employee.objects.create(name="Peter")
Employee.objects.create(name="Joe", boss=boss)
Employee.objects.create(name="Angela", boss=boss)
def test_traverse_nullable(self):
# Because we use select_related() for 'boss', it doesn't need to be
# prefetched, but we can still traverse it although it contains some nulls
with self.assertNumQueries(2):
qs = Employee.objects.select_related("boss").prefetch_related("boss__serfs")
co_serfs = [
list(e.boss.serfs.all()) if e.boss is not None else [] for e in qs
]
qs2 = Employee.objects.select_related("boss")
co_serfs2 = [
list(e.boss.serfs.all()) if e.boss is not None else [] for e in qs2
]
self.assertEqual(co_serfs, co_serfs2)
def test_prefetch_nullable(self):
# One for main employee, one for boss, one for serfs
with self.assertNumQueries(3):
qs = Employee.objects.prefetch_related("boss__serfs")
co_serfs = [
list(e.boss.serfs.all()) if e.boss is not None else [] for e in qs
]
qs2 = Employee.objects.all()
co_serfs2 = [
list(e.boss.serfs.all()) if e.boss is not None else [] for e in qs2
]
self.assertEqual(co_serfs, co_serfs2)
def test_in_bulk(self):
"""
In-bulk does correctly prefetch objects by not using .iterator()
directly.
"""
boss1 = Employee.objects.create(name="Peter")
boss2 = Employee.objects.create(name="Jack")
with self.assertNumQueries(2):
# Prefetch is done and it does not cause any errors.
bulk = Employee.objects.prefetch_related("serfs").in_bulk(
[boss1.pk, boss2.pk]
)
for b in bulk.values():
list(b.serfs.all())
class MultiDbTests(TestCase):
databases = {"default", "other"}
def test_using_is_honored_m2m(self):
B = Book.objects.using("other")
A = Author.objects.using("other")
book1 = B.create(title="Poems")
book2 = B.create(title="Jane Eyre")
book3 = B.create(title="Wuthering Heights")
book4 = B.create(title="Sense and Sensibility")
author1 = A.create(name="Charlotte", first_book=book1)
author2 = A.create(name="Anne", first_book=book1)
author3 = A.create(name="Emily", first_book=book1)
author4 = A.create(name="Jane", first_book=book4)
book1.authors.add(author1, author2, author3)
book2.authors.add(author1)
book3.authors.add(author3)
book4.authors.add(author4)
# Forward
qs1 = B.prefetch_related("authors")
with self.assertNumQueries(2, using="other"):
books = "".join(
"%s (%s)\n"
% (book.title, ", ".join(a.name for a in book.authors.all()))
for book in qs1
)
self.assertEqual(
books,
"Poems (Charlotte, Anne, Emily)\n"
"Jane Eyre (Charlotte)\n"
"Wuthering Heights (Emily)\n"
"Sense and Sensibility (Jane)\n",
)
# Reverse
qs2 = A.prefetch_related("books")
with self.assertNumQueries(2, using="other"):
authors = "".join(
"%s: %s\n"
% (author.name, ", ".join(b.title for b in author.books.all()))
for author in qs2
)
self.assertEqual(
authors,
"Charlotte: Poems, Jane Eyre\n"
"Anne: Poems\n"
"Emily: Poems, Wuthering Heights\n"
"Jane: Sense and Sensibility\n",
)
def test_using_is_honored_fkey(self):
B = Book.objects.using("other")
A = Author.objects.using("other")
book1 = B.create(title="Poems")
book2 = B.create(title="Sense and Sensibility")
A.create(name="Charlotte Bronte", first_book=book1)
A.create(name="Jane Austen", first_book=book2)
# Forward
with self.assertNumQueries(2, using="other"):
books = ", ".join(
a.first_book.title for a in A.prefetch_related("first_book")
)
self.assertEqual("Poems, Sense and Sensibility", books)
# Reverse
with self.assertNumQueries(2, using="other"):
books = "".join(
"%s (%s)\n"
% (b.title, ", ".join(a.name for a in b.first_time_authors.all()))
for b in B.prefetch_related("first_time_authors")
)
self.assertEqual(
books,
"Poems (Charlotte Bronte)\nSense and Sensibility (Jane Austen)\n",
)
def test_using_is_honored_inheritance(self):
B = BookWithYear.objects.using("other")
A = AuthorWithAge.objects.using("other")
book1 = B.create(title="Poems", published_year=2010)
B.create(title="More poems", published_year=2011)
A.create(name="Jane", first_book=book1, age=50)
A.create(name="Tom", first_book=book1, age=49)
# parent link
with self.assertNumQueries(2, using="other"):
authors = ", ".join(a.author.name for a in A.prefetch_related("author"))
self.assertEqual(authors, "Jane, Tom")
# child link
with self.assertNumQueries(2, using="other"):
ages = ", ".join(
str(a.authorwithage.age) for a in A.prefetch_related("authorwithage")
)
self.assertEqual(ages, "50, 49")
def test_using_is_honored_custom_qs(self):
B = Book.objects.using("other")
A = Author.objects.using("other")
book1 = B.create(title="Poems")
book2 = B.create(title="Sense and Sensibility")
A.create(name="Charlotte Bronte", first_book=book1)
A.create(name="Jane Austen", first_book=book2)
# Implicit hinting
with self.assertNumQueries(2, using="other"):
prefetch = Prefetch("first_time_authors", queryset=Author.objects.all())
books = "".join(
"%s (%s)\n"
% (b.title, ", ".join(a.name for a in b.first_time_authors.all()))
for b in B.prefetch_related(prefetch)
)
self.assertEqual(
books,
"Poems (Charlotte Bronte)\nSense and Sensibility (Jane Austen)\n",
)
# Explicit using on the same db.
with self.assertNumQueries(2, using="other"):
prefetch = Prefetch(
"first_time_authors", queryset=Author.objects.using("other")
)
books = "".join(
"%s (%s)\n"
% (b.title, ", ".join(a.name for a in b.first_time_authors.all()))
for b in B.prefetch_related(prefetch)
)
self.assertEqual(
books,
"Poems (Charlotte Bronte)\nSense and Sensibility (Jane Austen)\n",
)
# Explicit using on a different db.
with self.assertNumQueries(1, using="default"), self.assertNumQueries(
1, using="other"
):
prefetch = Prefetch(
"first_time_authors", queryset=Author.objects.using("default")
)
books = "".join(
"%s (%s)\n"
% (b.title, ", ".join(a.name for a in b.first_time_authors.all()))
for b in B.prefetch_related(prefetch)
)
self.assertEqual(books, "Poems ()\n" "Sense and Sensibility ()\n")
class Ticket19607Tests(TestCase):
@classmethod
def setUpTestData(cls):
LessonEntry.objects.bulk_create(
LessonEntry(id=id_, name1=name1, name2=name2)
for id_, name1, name2 in [
(1, "einfach", "simple"),
(2, "schwierig", "difficult"),
]
)
WordEntry.objects.bulk_create(
WordEntry(id=id_, lesson_entry_id=lesson_entry_id, name=name)
for id_, lesson_entry_id, name in [
(1, 1, "einfach"),
(2, 1, "simple"),
(3, 2, "schwierig"),
(4, 2, "difficult"),
]
)
def test_bug(self):
list(
WordEntry.objects.prefetch_related(
"lesson_entry", "lesson_entry__wordentry_set"
)
)
class Ticket21410Tests(TestCase):
@classmethod
def setUpTestData(cls):
book1 = Book.objects.create(title="Poems")
book2 = Book.objects.create(title="Jane Eyre")
book3 = Book.objects.create(title="Wuthering Heights")
book4 = Book.objects.create(title="Sense and Sensibility")
author1 = Author2.objects.create(name="Charlotte", first_book=book1)
author2 = Author2.objects.create(name="Anne", first_book=book1)
author3 = Author2.objects.create(name="Emily", first_book=book1)
author4 = Author2.objects.create(name="Jane", first_book=book4)
author1.favorite_books.add(book1, book2, book3)
author2.favorite_books.add(book1)
author3.favorite_books.add(book2)
author4.favorite_books.add(book3)
def test_bug(self):
list(Author2.objects.prefetch_related("first_book", "favorite_books"))
class Ticket21760Tests(TestCase):
@classmethod
def setUpTestData(cls):
cls.rooms = []
for _ in range(3):
house = House.objects.create()
for _ in range(3):
cls.rooms.append(Room.objects.create(house=house))
# Set main_room for each house before creating the next one for
# databases where supports_nullable_unique_constraints is False.
house.main_room = cls.rooms[-3]
house.save()
def test_bug(self):
prefetcher = get_prefetcher(self.rooms[0], "house", "house")[0]
queryset = prefetcher.get_prefetch_queryset(list(Room.objects.all()))[0]
self.assertNotIn(" JOIN ", str(queryset.query))
class DirectPrefetchedObjectCacheReuseTests(TestCase):
"""
prefetch_related() reuses objects fetched in _prefetched_objects_cache.
When objects are prefetched and not stored as an instance attribute (often
intermediary relationships), they are saved to the
_prefetched_objects_cache attribute. prefetch_related() takes
_prefetched_objects_cache into account when determining whether an object
has been fetched[1] and retrieves results from it when it is populated [2].
[1]: #25546 (duplicate queries on nested Prefetch)
[2]: #27554 (queryset evaluation fails with a mix of nested and flattened
prefetches)
"""
@classmethod
def setUpTestData(cls):
cls.book1, cls.book2 = [
Book.objects.create(title="book1"),
Book.objects.create(title="book2"),
]
cls.author11, cls.author12, cls.author21 = [
Author.objects.create(first_book=cls.book1, name="Author11"),
Author.objects.create(first_book=cls.book1, name="Author12"),
Author.objects.create(first_book=cls.book2, name="Author21"),
]
cls.author1_address1, cls.author1_address2, cls.author2_address1 = [
AuthorAddress.objects.create(author=cls.author11, address="Happy place"),
AuthorAddress.objects.create(author=cls.author12, address="Haunted house"),
AuthorAddress.objects.create(author=cls.author21, address="Happy place"),
]
cls.bookwithyear1 = BookWithYear.objects.create(
title="Poems", published_year=2010
)
cls.bookreview1 = BookReview.objects.create(book=cls.bookwithyear1)
def test_detect_is_fetched(self):
"""
Nested prefetch_related() shouldn't trigger duplicate queries for the same
lookup.
"""
with self.assertNumQueries(3):
books = Book.objects.filter(title__in=["book1", "book2"],).prefetch_related(
Prefetch(
"first_time_authors",
Author.objects.prefetch_related(
Prefetch(
"addresses",
AuthorAddress.objects.filter(address="Happy place"),
)
),
),
)
book1, book2 = list(books)
with self.assertNumQueries(0):
self.assertSequenceEqual(
book1.first_time_authors.all(), [self.author11, self.author12]
)
self.assertSequenceEqual(book2.first_time_authors.all(), [self.author21])
self.assertSequenceEqual(
book1.first_time_authors.all()[0].addresses.all(),
[self.author1_address1],
)
self.assertSequenceEqual(
book1.first_time_authors.all()[1].addresses.all(), []
)
self.assertSequenceEqual(
book2.first_time_authors.all()[0].addresses.all(),
[self.author2_address1],
)
self.assertEqual(
list(book1.first_time_authors.all()),
list(book1.first_time_authors.all().all()),
)
self.assertEqual(
list(book2.first_time_authors.all()),
list(book2.first_time_authors.all().all()),
)
self.assertEqual(
list(book1.first_time_authors.all()[0].addresses.all()),
list(book1.first_time_authors.all()[0].addresses.all().all()),
)
self.assertEqual(
list(book1.first_time_authors.all()[1].addresses.all()),
list(book1.first_time_authors.all()[1].addresses.all().all()),
)
self.assertEqual(
list(book2.first_time_authors.all()[0].addresses.all()),
list(book2.first_time_authors.all()[0].addresses.all().all()),
)
def test_detect_is_fetched_with_to_attr(self):
with self.assertNumQueries(3):
books = Book.objects.filter(title__in=["book1", "book2"],).prefetch_related(
Prefetch(
"first_time_authors",
Author.objects.prefetch_related(
Prefetch(
"addresses",
AuthorAddress.objects.filter(address="Happy place"),
to_attr="happy_place",
)
),
to_attr="first_authors",
),
)
book1, book2 = list(books)
with self.assertNumQueries(0):
self.assertEqual(book1.first_authors, [self.author11, self.author12])
self.assertEqual(book2.first_authors, [self.author21])
self.assertEqual(
book1.first_authors[0].happy_place, [self.author1_address1]
)
self.assertEqual(book1.first_authors[1].happy_place, [])
self.assertEqual(
book2.first_authors[0].happy_place, [self.author2_address1]
)
def test_prefetch_reverse_foreign_key(self):
with self.assertNumQueries(2):
(bookwithyear1,) = BookWithYear.objects.prefetch_related("bookreview_set")
with self.assertNumQueries(0):
self.assertCountEqual(
bookwithyear1.bookreview_set.all(), [self.bookreview1]
)
with self.assertNumQueries(0):
prefetch_related_objects([bookwithyear1], "bookreview_set")
def test_add_clears_prefetched_objects(self):
bookwithyear = BookWithYear.objects.get(pk=self.bookwithyear1.pk)
prefetch_related_objects([bookwithyear], "bookreview_set")
self.assertCountEqual(bookwithyear.bookreview_set.all(), [self.bookreview1])
new_review = BookReview.objects.create()
bookwithyear.bookreview_set.add(new_review)
self.assertCountEqual(
bookwithyear.bookreview_set.all(), [self.bookreview1, new_review]
)
def test_remove_clears_prefetched_objects(self):
bookwithyear = BookWithYear.objects.get(pk=self.bookwithyear1.pk)
prefetch_related_objects([bookwithyear], "bookreview_set")
self.assertCountEqual(bookwithyear.bookreview_set.all(), [self.bookreview1])
bookwithyear.bookreview_set.remove(self.bookreview1)
self.assertCountEqual(bookwithyear.bookreview_set.all(), [])
class ReadPrefetchedObjectsCacheTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.book1 = Book.objects.create(title="Les confessions Volume I")
cls.book2 = Book.objects.create(title="Candide")
cls.author1 = AuthorWithAge.objects.create(
name="Rousseau", first_book=cls.book1, age=70
)
cls.author2 = AuthorWithAge.objects.create(
name="Voltaire", first_book=cls.book2, age=65
)
cls.book1.authors.add(cls.author1)
cls.book2.authors.add(cls.author2)
FavoriteAuthors.objects.create(author=cls.author1, likes_author=cls.author2)
def test_retrieves_results_from_prefetched_objects_cache(self):
"""
When intermediary results are prefetched without a destination
attribute, they are saved in the RelatedManager's cache
(_prefetched_objects_cache). prefetch_related() uses this cache
(#27554).
"""
authors = AuthorWithAge.objects.prefetch_related(
Prefetch(
"author",
queryset=Author.objects.prefetch_related(
# Results are saved in the RelatedManager's cache
# (_prefetched_objects_cache) and do not replace the
# RelatedManager on Author instances (favorite_authors)
Prefetch("favorite_authors__first_book"),
),
),
)
with self.assertNumQueries(4):
# AuthorWithAge -> Author -> FavoriteAuthors, Book
self.assertSequenceEqual(authors, [self.author1, self.author2])
class NestedPrefetchTests(TestCase):
@classmethod
def setUpTestData(cls):
house = House.objects.create(name="Big house", address="123 Main St")
cls.room = Room.objects.create(name="Kitchen", house=house)
def test_nested_prefetch_is_not_overwritten_by_related_object(self):
"""
The prefetched relationship is used rather than populating the reverse
relationship from the parent, when prefetching a set of child objects
related to a set of parent objects and the child queryset itself
specifies a prefetch back to the parent.
"""
queryset = House.objects.only("name").prefetch_related(
Prefetch(
"rooms",
queryset=Room.objects.prefetch_related(
Prefetch("house", queryset=House.objects.only("address")),
),
),
)
with self.assertNumQueries(3):
house = queryset.first()
self.assertIs(Room.house.is_cached(self.room), True)
with self.assertNumQueries(0):
house.rooms.first().house.address
class PrefetchLimitTests(TestDataMixin, TestCase):
@skipUnlessDBFeature("supports_over_clause")
def test_m2m_forward(self):
authors = Author.objects.all() # Meta.ordering
with self.assertNumQueries(3):
books = list(
Book.objects.prefetch_related(
Prefetch("authors", authors),
Prefetch("authors", authors[1:], to_attr="authors_sliced"),
)
)
for book in books:
with self.subTest(book=book):
self.assertEqual(book.authors_sliced, list(book.authors.all())[1:])
@skipUnlessDBFeature("supports_over_clause")
def test_m2m_reverse(self):
books = Book.objects.order_by("title")
with self.assertNumQueries(3):
authors = list(
Author.objects.prefetch_related(
Prefetch("books", books),
Prefetch("books", books[1:2], to_attr="books_sliced"),
)
)
for author in authors:
with self.subTest(author=author):
self.assertEqual(author.books_sliced, list(author.books.all())[1:2])
@skipUnlessDBFeature("supports_over_clause")
def test_foreignkey_reverse(self):
authors = Author.objects.order_by("-name")
with self.assertNumQueries(3):
books = list(
Book.objects.prefetch_related(
Prefetch(
"first_time_authors",
authors,
),
Prefetch(
"first_time_authors",
authors[1:],
to_attr="first_time_authors_sliced",
),
)
)
for book in books:
with self.subTest(book=book):
self.assertEqual(
book.first_time_authors_sliced,
list(book.first_time_authors.all())[1:],
)
@skipUnlessDBFeature("supports_over_clause")
def test_reverse_ordering(self):
authors = Author.objects.reverse() # Reverse Meta.ordering
with self.assertNumQueries(3):
books = list(
Book.objects.prefetch_related(
Prefetch("authors", authors),
Prefetch("authors", authors[1:], to_attr="authors_sliced"),
)
)
for book in books:
with self.subTest(book=book):
self.assertEqual(book.authors_sliced, list(book.authors.all())[1:])
@skipIfDBFeature("supports_over_clause")
def test_window_not_supported(self):
authors = Author.objects.all()
msg = (
"Prefetching from a limited queryset is only supported on backends that "
"support window functions."
)
with self.assertRaisesMessage(NotSupportedError, msg):
list(Book.objects.prefetch_related(Prefetch("authors", authors[1:])))
|
60dd68f75812cc55b29ff453ed6c5dd44a569857d3b5663a95f8abcb54551fad | from django.db.models import CharField
from django.db.models import Value as V
from django.db.models.functions import Coalesce, Length, Upper
from django.test import TestCase
from django.test.utils import register_lookup
from .models import Author
class UpperBilateral(Upper):
bilateral = True
class FunctionTests(TestCase):
def test_nested_function_ordering(self):
Author.objects.create(name="John Smith")
Author.objects.create(name="Rhonda Simpson", alias="ronny")
authors = Author.objects.order_by(Length(Coalesce("alias", "name")))
self.assertQuerySetEqual(
authors,
[
"Rhonda Simpson",
"John Smith",
],
lambda a: a.name,
)
authors = Author.objects.order_by(Length(Coalesce("alias", "name")).desc())
self.assertQuerySetEqual(
authors,
[
"John Smith",
"Rhonda Simpson",
],
lambda a: a.name,
)
def test_func_transform_bilateral(self):
with register_lookup(CharField, UpperBilateral):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
authors = Author.objects.filter(name__upper__exact="john smith")
self.assertQuerySetEqual(
authors.order_by("name"),
[
"John Smith",
],
lambda a: a.name,
)
def test_func_transform_bilateral_multivalue(self):
with register_lookup(CharField, UpperBilateral):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
authors = Author.objects.filter(name__upper__in=["john smith", "rhonda"])
self.assertQuerySetEqual(
authors.order_by("name"),
[
"John Smith",
"Rhonda",
],
lambda a: a.name,
)
def test_function_as_filter(self):
Author.objects.create(name="John Smith", alias="SMITHJ")
Author.objects.create(name="Rhonda")
self.assertQuerySetEqual(
Author.objects.filter(alias=Upper(V("smithj"))),
["John Smith"],
lambda x: x.name,
)
self.assertQuerySetEqual(
Author.objects.exclude(alias=Upper(V("smithj"))),
["Rhonda"],
lambda x: x.name,
)
|
a5a721eb74b981894ea2e32c7f1b13fefdcfc82028f65d6007fa584166a83904 | import os
import re
import shutil
import tempfile
import time
import warnings
from io import StringIO
from pathlib import Path
from unittest import mock, skipIf, skipUnless
from admin_scripts.tests import AdminScriptTestCase
from django.core import management
from django.core.management import execute_from_command_line
from django.core.management.base import CommandError
from django.core.management.commands.makemessages import Command as MakeMessagesCommand
from django.core.management.commands.makemessages import write_pot_file
from django.core.management.utils import find_command
from django.test import SimpleTestCase, override_settings
from django.test.utils import captured_stderr, captured_stdout
from django.utils._os import symlinks_supported
from django.utils.translation import TranslatorCommentWarning
from .utils import POFileAssertionMixin, RunInTmpDirMixin, copytree
LOCALE = "de"
has_xgettext = find_command("xgettext")
gettext_version = MakeMessagesCommand().gettext_version if has_xgettext else None
requires_gettext_019 = skipIf(
has_xgettext and gettext_version < (0, 19), "gettext 0.19 required"
)
@skipUnless(has_xgettext, "xgettext is mandatory for extraction tests")
class ExtractorTests(POFileAssertionMixin, RunInTmpDirMixin, SimpleTestCase):
work_subdir = "commands"
PO_FILE = "locale/%s/LC_MESSAGES/django.po" % LOCALE
def _run_makemessages(self, **options):
out = StringIO()
management.call_command(
"makemessages", locale=[LOCALE], verbosity=2, stdout=out, **options
)
output = out.getvalue()
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
return output, po_contents
def assertMsgIdPlural(self, msgid, haystack, use_quotes=True):
return self._assertPoKeyword(
"msgid_plural", msgid, haystack, use_quotes=use_quotes
)
def assertMsgStr(self, msgstr, haystack, use_quotes=True):
return self._assertPoKeyword("msgstr", msgstr, haystack, use_quotes=use_quotes)
def assertNotMsgId(self, msgid, s, use_quotes=True):
if use_quotes:
msgid = '"%s"' % msgid
msgid = re.escape(msgid)
return self.assertTrue(not re.search("^msgid %s" % msgid, s, re.MULTILINE))
def _assertPoLocComment(
self, assert_presence, po_filename, line_number, *comment_parts
):
with open(po_filename) as fp:
po_contents = fp.read()
if os.name == "nt":
# #: .\path\to\file.html:123
cwd_prefix = "%s%s" % (os.curdir, os.sep)
else:
# #: path/to/file.html:123
cwd_prefix = ""
path = os.path.join(cwd_prefix, *comment_parts)
parts = [path]
if isinstance(line_number, str):
line_number = self._get_token_line_number(path, line_number)
if line_number is not None:
parts.append(":%d" % line_number)
needle = "".join(parts)
pattern = re.compile(r"^\#\:.*" + re.escape(needle), re.MULTILINE)
if assert_presence:
return self.assertRegex(
po_contents, pattern, '"%s" not found in final .po file.' % needle
)
else:
return self.assertNotRegex(
po_contents, pattern, '"%s" shouldn\'t be in final .po file.' % needle
)
def _get_token_line_number(self, path, token):
with open(path) as f:
for line, content in enumerate(f, 1):
if token in content:
return line
self.fail(
"The token '%s' could not be found in %s, please check the test config"
% (token, path)
)
def assertLocationCommentPresent(self, po_filename, line_number, *comment_parts):
r"""
self.assertLocationCommentPresent('django.po', 42, 'dirA', 'dirB', 'foo.py')
verifies that the django.po file has a gettext-style location comment
of the form
`#: dirA/dirB/foo.py:42`
(or `#: .\dirA\dirB\foo.py:42` on Windows)
None can be passed for the line_number argument to skip checking of
the :42 suffix part.
A string token can also be passed as line_number, in which case it
will be searched in the template, and its line number will be used.
A msgid is a suitable candidate.
"""
return self._assertPoLocComment(True, po_filename, line_number, *comment_parts)
def assertLocationCommentNotPresent(self, po_filename, line_number, *comment_parts):
"""Check the opposite of assertLocationComment()"""
return self._assertPoLocComment(False, po_filename, line_number, *comment_parts)
def assertRecentlyModified(self, path):
"""
Assert that file was recently modified (modification time was less than
10 seconds ago).
"""
delta = time.time() - os.stat(path).st_mtime
self.assertLess(delta, 10, "%s was recently modified" % path)
def assertNotRecentlyModified(self, path):
"""
Assert that file was not recently modified (modification time was more
than 10 seconds ago).
"""
delta = time.time() - os.stat(path).st_mtime
self.assertGreater(delta, 10, "%s wasn't recently modified" % path)
class BasicExtractorTests(ExtractorTests):
@override_settings(USE_I18N=False)
def test_use_i18n_false(self):
"""
makemessages also runs successfully when USE_I18N is False.
"""
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE, encoding="utf-8") as fp:
po_contents = fp.read()
# Check two random strings
self.assertIn("#. Translators: One-line translator comment #1", po_contents)
self.assertIn('msgctxt "Special trans context #1"', po_contents)
def test_no_option(self):
# One of either the --locale, --exclude, or --all options is required.
msg = "Type 'manage.py help makemessages' for usage information."
with mock.patch(
"django.core.management.commands.makemessages.sys.argv",
["manage.py", "makemessages"],
):
with self.assertRaisesRegex(CommandError, msg):
management.call_command("makemessages")
def test_valid_locale(self):
out = StringIO()
management.call_command("makemessages", locale=["de"], stdout=out, verbosity=1)
self.assertNotIn("invalid locale de", out.getvalue())
self.assertIn("processing locale de", out.getvalue())
self.assertIs(Path(self.PO_FILE).exists(), True)
def test_valid_locale_with_country(self):
out = StringIO()
management.call_command(
"makemessages", locale=["en_GB"], stdout=out, verbosity=1
)
self.assertNotIn("invalid locale en_GB", out.getvalue())
self.assertIn("processing locale en_GB", out.getvalue())
self.assertIs(Path("locale/en_GB/LC_MESSAGES/django.po").exists(), True)
def test_valid_locale_tachelhit_latin_morocco(self):
out = StringIO()
management.call_command(
"makemessages", locale=["shi_Latn_MA"], stdout=out, verbosity=1
)
self.assertNotIn("invalid locale shi_Latn_MA", out.getvalue())
self.assertIn("processing locale shi_Latn_MA", out.getvalue())
self.assertIs(Path("locale/shi_Latn_MA/LC_MESSAGES/django.po").exists(), True)
def test_valid_locale_private_subtag(self):
out = StringIO()
management.call_command(
"makemessages", locale=["nl_NL-x-informal"], stdout=out, verbosity=1
)
self.assertNotIn("invalid locale nl_NL-x-informal", out.getvalue())
self.assertIn("processing locale nl_NL-x-informal", out.getvalue())
self.assertIs(
Path("locale/nl_NL-x-informal/LC_MESSAGES/django.po").exists(), True
)
def test_invalid_locale_uppercase(self):
out = StringIO()
management.call_command("makemessages", locale=["PL"], stdout=out, verbosity=1)
self.assertIn("invalid locale PL, did you mean pl?", out.getvalue())
self.assertNotIn("processing locale pl", out.getvalue())
self.assertIs(Path("locale/pl/LC_MESSAGES/django.po").exists(), False)
def test_invalid_locale_hyphen(self):
out = StringIO()
management.call_command(
"makemessages", locale=["pl-PL"], stdout=out, verbosity=1
)
self.assertIn("invalid locale pl-PL, did you mean pl_PL?", out.getvalue())
self.assertNotIn("processing locale pl-PL", out.getvalue())
self.assertIs(Path("locale/pl-PL/LC_MESSAGES/django.po").exists(), False)
def test_invalid_locale_lower_country(self):
out = StringIO()
management.call_command(
"makemessages", locale=["pl_pl"], stdout=out, verbosity=1
)
self.assertIn("invalid locale pl_pl, did you mean pl_PL?", out.getvalue())
self.assertNotIn("processing locale pl_pl", out.getvalue())
self.assertIs(Path("locale/pl_pl/LC_MESSAGES/django.po").exists(), False)
def test_invalid_locale_private_subtag(self):
out = StringIO()
management.call_command(
"makemessages", locale=["nl-nl-x-informal"], stdout=out, verbosity=1
)
self.assertIn(
"invalid locale nl-nl-x-informal, did you mean nl_NL-x-informal?",
out.getvalue(),
)
self.assertNotIn("processing locale nl-nl-x-informal", out.getvalue())
self.assertIs(
Path("locale/nl-nl-x-informal/LC_MESSAGES/django.po").exists(), False
)
def test_invalid_locale_plus(self):
out = StringIO()
management.call_command(
"makemessages", locale=["en+GB"], stdout=out, verbosity=1
)
self.assertIn("invalid locale en+GB, did you mean en_GB?", out.getvalue())
self.assertNotIn("processing locale en+GB", out.getvalue())
self.assertIs(Path("locale/en+GB/LC_MESSAGES/django.po").exists(), False)
def test_invalid_locale_end_with_underscore(self):
out = StringIO()
management.call_command("makemessages", locale=["en_"], stdout=out, verbosity=1)
self.assertIn("invalid locale en_", out.getvalue())
self.assertNotIn("processing locale en_", out.getvalue())
self.assertIs(Path("locale/en_/LC_MESSAGES/django.po").exists(), False)
def test_invalid_locale_start_with_underscore(self):
out = StringIO()
management.call_command("makemessages", locale=["_en"], stdout=out, verbosity=1)
self.assertIn("invalid locale _en", out.getvalue())
self.assertNotIn("processing locale _en", out.getvalue())
self.assertIs(Path("locale/_en/LC_MESSAGES/django.po").exists(), False)
def test_comments_extractor(self):
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE, encoding="utf-8") as fp:
po_contents = fp.read()
self.assertNotIn("This comment should not be extracted", po_contents)
# Comments in templates
self.assertIn(
"#. Translators: This comment should be extracted", po_contents
)
self.assertIn(
"#. Translators: Django comment block for translators\n#. "
"string's meaning unveiled",
po_contents,
)
self.assertIn("#. Translators: One-line translator comment #1", po_contents)
self.assertIn(
"#. Translators: Two-line translator comment #1\n#. continued here.",
po_contents,
)
self.assertIn("#. Translators: One-line translator comment #2", po_contents)
self.assertIn(
"#. Translators: Two-line translator comment #2\n#. continued here.",
po_contents,
)
self.assertIn("#. Translators: One-line translator comment #3", po_contents)
self.assertIn(
"#. Translators: Two-line translator comment #3\n#. continued here.",
po_contents,
)
self.assertIn("#. Translators: One-line translator comment #4", po_contents)
self.assertIn(
"#. Translators: Two-line translator comment #4\n#. continued here.",
po_contents,
)
self.assertIn(
"#. Translators: One-line translator comment #5 -- with "
"non ASCII characters: áéíóúö",
po_contents,
)
self.assertIn(
"#. Translators: Two-line translator comment #5 -- with "
"non ASCII characters: áéíóúö\n#. continued here.",
po_contents,
)
def test_special_char_extracted(self):
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE, encoding="utf-8") as fp:
po_contents = fp.read()
self.assertMsgId("Non-breaking space\u00a0:", po_contents)
def test_blocktranslate_trimmed(self):
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
# should not be trimmed
self.assertNotMsgId("Text with a few line breaks.", po_contents)
# should be trimmed
self.assertMsgId(
"Again some text with a few line breaks, this time should be trimmed.",
po_contents,
)
# #21406 -- Should adjust for eaten line numbers
self.assertMsgId("Get my line number", po_contents)
self.assertLocationCommentPresent(
self.PO_FILE, "Get my line number", "templates", "test.html"
)
def test_extraction_error(self):
msg = (
"Translation blocks must not include other block tags: blocktranslate "
"(file %s, line 3)" % os.path.join("templates", "template_with_error.tpl")
)
with self.assertRaisesMessage(SyntaxError, msg):
management.call_command(
"makemessages", locale=[LOCALE], extensions=["tpl"], verbosity=0
)
# The temporary files were cleaned up.
self.assertFalse(os.path.exists("./templates/template_with_error.tpl.py"))
self.assertFalse(os.path.exists("./templates/template_0_with_no_error.tpl.py"))
def test_unicode_decode_error(self):
shutil.copyfile("./not_utf8.sample", "./not_utf8.txt")
out = StringIO()
management.call_command("makemessages", locale=[LOCALE], stdout=out)
self.assertIn(
"UnicodeDecodeError: skipped file not_utf8.txt in .", out.getvalue()
)
def test_unicode_file_name(self):
open(os.path.join(self.test_dir, "vidéo.txt"), "a").close()
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
def test_extraction_warning(self):
"""test xgettext warning about multiple bare interpolation placeholders"""
shutil.copyfile("./code.sample", "./code_sample.py")
out = StringIO()
management.call_command("makemessages", locale=[LOCALE], stdout=out)
self.assertIn("code_sample.py:4", out.getvalue())
def test_template_message_context_extractor(self):
"""
Message contexts are correctly extracted for the {% translate %} and
{% blocktranslate %} template tags (#14806).
"""
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
# {% translate %}
self.assertIn('msgctxt "Special trans context #1"', po_contents)
self.assertMsgId("Translatable literal #7a", po_contents)
self.assertIn('msgctxt "Special trans context #2"', po_contents)
self.assertMsgId("Translatable literal #7b", po_contents)
self.assertIn('msgctxt "Special trans context #3"', po_contents)
self.assertMsgId("Translatable literal #7c", po_contents)
# {% translate %} with a filter
for (
minor_part
) in "abcdefgh": # Iterate from #7.1a to #7.1h template markers
self.assertIn(
'msgctxt "context #7.1{}"'.format(minor_part), po_contents
)
self.assertMsgId(
"Translatable literal #7.1{}".format(minor_part), po_contents
)
# {% blocktranslate %}
self.assertIn('msgctxt "Special blocktranslate context #1"', po_contents)
self.assertMsgId("Translatable literal #8a", po_contents)
self.assertIn('msgctxt "Special blocktranslate context #2"', po_contents)
self.assertMsgId("Translatable literal #8b-singular", po_contents)
self.assertIn("Translatable literal #8b-plural", po_contents)
self.assertIn('msgctxt "Special blocktranslate context #3"', po_contents)
self.assertMsgId("Translatable literal #8c-singular", po_contents)
self.assertIn("Translatable literal #8c-plural", po_contents)
self.assertIn('msgctxt "Special blocktranslate context #4"', po_contents)
self.assertMsgId("Translatable literal #8d %(a)s", po_contents)
# {% trans %} and {% blocktrans %}
self.assertMsgId("trans text", po_contents)
self.assertMsgId("blocktrans text", po_contents)
def test_context_in_single_quotes(self):
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
# {% translate %}
self.assertIn('msgctxt "Context wrapped in double quotes"', po_contents)
self.assertIn('msgctxt "Context wrapped in single quotes"', po_contents)
# {% blocktranslate %}
self.assertIn(
'msgctxt "Special blocktranslate context wrapped in double quotes"',
po_contents,
)
self.assertIn(
'msgctxt "Special blocktranslate context wrapped in single quotes"',
po_contents,
)
def test_template_comments(self):
"""Template comment tags on the same line of other constructs (#19552)"""
# Test detection/end user reporting of old, incorrect templates
# translator comments syntax
with warnings.catch_warnings(record=True) as ws:
warnings.simplefilter("always")
management.call_command(
"makemessages", locale=[LOCALE], extensions=["thtml"], verbosity=0
)
self.assertEqual(len(ws), 3)
for w in ws:
self.assertTrue(issubclass(w.category, TranslatorCommentWarning))
self.assertRegex(
str(ws[0].message),
r"The translator-targeted comment 'Translators: ignored i18n "
r"comment #1' \(file templates[/\\]comments.thtml, line 4\) "
r"was ignored, because it wasn't the last item on the line\.",
)
self.assertRegex(
str(ws[1].message),
r"The translator-targeted comment 'Translators: ignored i18n "
r"comment #3' \(file templates[/\\]comments.thtml, line 6\) "
r"was ignored, because it wasn't the last item on the line\.",
)
self.assertRegex(
str(ws[2].message),
r"The translator-targeted comment 'Translators: ignored i18n "
r"comment #4' \(file templates[/\\]comments.thtml, line 8\) "
r"was ignored, because it wasn't the last item on the line\.",
)
# Now test .po file contents
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
self.assertMsgId("Translatable literal #9a", po_contents)
self.assertNotIn("ignored comment #1", po_contents)
self.assertNotIn("Translators: ignored i18n comment #1", po_contents)
self.assertMsgId("Translatable literal #9b", po_contents)
self.assertNotIn("ignored i18n comment #2", po_contents)
self.assertNotIn("ignored comment #2", po_contents)
self.assertMsgId("Translatable literal #9c", po_contents)
self.assertNotIn("ignored comment #3", po_contents)
self.assertNotIn("ignored i18n comment #3", po_contents)
self.assertMsgId("Translatable literal #9d", po_contents)
self.assertNotIn("ignored comment #4", po_contents)
self.assertMsgId("Translatable literal #9e", po_contents)
self.assertNotIn("ignored comment #5", po_contents)
self.assertNotIn("ignored i18n comment #4", po_contents)
self.assertMsgId("Translatable literal #9f", po_contents)
self.assertIn("#. Translators: valid i18n comment #5", po_contents)
self.assertMsgId("Translatable literal #9g", po_contents)
self.assertIn("#. Translators: valid i18n comment #6", po_contents)
self.assertMsgId("Translatable literal #9h", po_contents)
self.assertIn("#. Translators: valid i18n comment #7", po_contents)
self.assertMsgId("Translatable literal #9i", po_contents)
self.assertRegex(po_contents, r"#\..+Translators: valid i18n comment #8")
self.assertRegex(po_contents, r"#\..+Translators: valid i18n comment #9")
self.assertMsgId("Translatable literal #9j", po_contents)
def test_makemessages_find_files(self):
"""
find_files only discover files having the proper extensions.
"""
cmd = MakeMessagesCommand()
cmd.ignore_patterns = ["CVS", ".*", "*~", "*.pyc"]
cmd.symlinks = False
cmd.domain = "django"
cmd.extensions = [".html", ".txt", ".py"]
cmd.verbosity = 0
cmd.locale_paths = []
cmd.default_locale_path = os.path.join(self.test_dir, "locale")
found_files = cmd.find_files(self.test_dir)
self.assertGreater(len(found_files), 1)
found_exts = {os.path.splitext(tfile.file)[1] for tfile in found_files}
self.assertEqual(found_exts.difference({".py", ".html", ".txt"}), set())
cmd.extensions = [".js"]
cmd.domain = "djangojs"
found_files = cmd.find_files(self.test_dir)
self.assertGreater(len(found_files), 1)
found_exts = {os.path.splitext(tfile.file)[1] for tfile in found_files}
self.assertEqual(found_exts.difference({".js"}), set())
@mock.patch("django.core.management.commands.makemessages.popen_wrapper")
def test_makemessages_gettext_version(self, mocked_popen_wrapper):
# "Normal" output:
mocked_popen_wrapper.return_value = (
"xgettext (GNU gettext-tools) 0.18.1\n"
"Copyright (C) 1995-1998, 2000-2010 Free Software Foundation, Inc.\n"
"License GPLv3+: GNU GPL version 3 or later "
"<http://gnu.org/licenses/gpl.html>\n"
"This is free software: you are free to change and redistribute it.\n"
"There is NO WARRANTY, to the extent permitted by law.\n"
"Written by Ulrich Drepper.\n",
"",
0,
)
cmd = MakeMessagesCommand()
self.assertEqual(cmd.gettext_version, (0, 18, 1))
# Version number with only 2 parts (#23788)
mocked_popen_wrapper.return_value = (
"xgettext (GNU gettext-tools) 0.17\n",
"",
0,
)
cmd = MakeMessagesCommand()
self.assertEqual(cmd.gettext_version, (0, 17))
# Bad version output
mocked_popen_wrapper.return_value = ("any other return value\n", "", 0)
cmd = MakeMessagesCommand()
with self.assertRaisesMessage(
CommandError, "Unable to get gettext version. Is it installed?"
):
cmd.gettext_version
def test_po_file_encoding_when_updating(self):
"""
Update of PO file doesn't corrupt it with non-UTF-8 encoding on Windows
(#23271).
"""
BR_PO_BASE = "locale/pt_BR/LC_MESSAGES/django"
shutil.copyfile(BR_PO_BASE + ".pristine", BR_PO_BASE + ".po")
management.call_command("makemessages", locale=["pt_BR"], verbosity=0)
self.assertTrue(os.path.exists(BR_PO_BASE + ".po"))
with open(BR_PO_BASE + ".po", encoding="utf-8") as fp:
po_contents = fp.read()
self.assertMsgStr("Größe", po_contents)
def test_pot_charset_header_is_utf8(self):
"""Content-Type: ... charset=CHARSET is replaced with charset=UTF-8"""
msgs = (
"# SOME DESCRIPTIVE TITLE.\n"
"# (some lines truncated as they are not relevant)\n"
'"Content-Type: text/plain; charset=CHARSET\\n"\n'
'"Content-Transfer-Encoding: 8bit\\n"\n'
"\n"
"#: somefile.py:8\n"
'msgid "mañana; charset=CHARSET"\n'
'msgstr ""\n'
)
with tempfile.NamedTemporaryFile() as pot_file:
pot_filename = pot_file.name
write_pot_file(pot_filename, msgs)
with open(pot_filename, encoding="utf-8") as fp:
pot_contents = fp.read()
self.assertIn("Content-Type: text/plain; charset=UTF-8", pot_contents)
self.assertIn("mañana; charset=CHARSET", pot_contents)
class JavaScriptExtractorTests(ExtractorTests):
PO_FILE = "locale/%s/LC_MESSAGES/djangojs.po" % LOCALE
def test_javascript_literals(self):
_, po_contents = self._run_makemessages(domain="djangojs")
self.assertMsgId("This literal should be included.", po_contents)
self.assertMsgId("gettext_noop should, too.", po_contents)
self.assertMsgId("This one as well.", po_contents)
self.assertMsgId(r"He said, \"hello\".", po_contents)
self.assertMsgId("okkkk", po_contents)
self.assertMsgId("TEXT", po_contents)
self.assertMsgId("It's at http://example.com", po_contents)
self.assertMsgId("String", po_contents)
self.assertMsgId(
"/* but this one will be too */ 'cause there is no way of telling...",
po_contents,
)
self.assertMsgId("foo", po_contents)
self.assertMsgId("bar", po_contents)
self.assertMsgId("baz", po_contents)
self.assertMsgId("quz", po_contents)
self.assertMsgId("foobar", po_contents)
def test_media_static_dirs_ignored(self):
"""
Regression test for #23583.
"""
with override_settings(
STATIC_ROOT=os.path.join(self.test_dir, "static/"),
MEDIA_ROOT=os.path.join(self.test_dir, "media_root/"),
):
_, po_contents = self._run_makemessages(domain="djangojs")
self.assertMsgId(
"Static content inside app should be included.", po_contents
)
self.assertNotMsgId(
"Content from STATIC_ROOT should not be included", po_contents
)
@override_settings(STATIC_ROOT=None, MEDIA_ROOT="")
def test_default_root_settings(self):
"""
Regression test for #23717.
"""
_, po_contents = self._run_makemessages(domain="djangojs")
self.assertMsgId("Static content inside app should be included.", po_contents)
class IgnoredExtractorTests(ExtractorTests):
def test_ignore_directory(self):
out, po_contents = self._run_makemessages(
ignore_patterns=[
os.path.join("ignore_dir", "*"),
]
)
self.assertIn("ignoring directory ignore_dir", out)
self.assertMsgId("This literal should be included.", po_contents)
self.assertNotMsgId("This should be ignored.", po_contents)
def test_ignore_subdirectory(self):
out, po_contents = self._run_makemessages(
ignore_patterns=[
"templates/*/ignore.html",
"templates/subdir/*",
]
)
self.assertIn("ignoring directory subdir", out)
self.assertNotMsgId("This subdir should be ignored too.", po_contents)
def test_ignore_file_patterns(self):
out, po_contents = self._run_makemessages(
ignore_patterns=[
"xxx_*",
]
)
self.assertIn("ignoring file xxx_ignored.html", out)
self.assertNotMsgId("This should be ignored too.", po_contents)
def test_media_static_dirs_ignored(self):
with override_settings(
STATIC_ROOT=os.path.join(self.test_dir, "static/"),
MEDIA_ROOT=os.path.join(self.test_dir, "media_root/"),
):
out, _ = self._run_makemessages()
self.assertIn("ignoring directory static", out)
self.assertIn("ignoring directory media_root", out)
class SymlinkExtractorTests(ExtractorTests):
def setUp(self):
super().setUp()
self.symlinked_dir = os.path.join(self.test_dir, "templates_symlinked")
def test_symlink(self):
if symlinks_supported():
os.symlink(os.path.join(self.test_dir, "templates"), self.symlinked_dir)
else:
self.skipTest(
"os.symlink() not available on this OS + Python version combination."
)
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, symlinks=True
)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
self.assertMsgId("This literal should be included.", po_contents)
self.assertLocationCommentPresent(
self.PO_FILE, None, "templates_symlinked", "test.html"
)
class CopyPluralFormsExtractorTests(ExtractorTests):
PO_FILE_ES = "locale/es/LC_MESSAGES/django.po"
def test_copy_plural_forms(self):
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
self.assertIn("Plural-Forms: nplurals=2; plural=(n != 1)", po_contents)
def test_override_plural_forms(self):
"""Ticket #20311."""
management.call_command(
"makemessages", locale=["es"], extensions=["djtpl"], verbosity=0
)
self.assertTrue(os.path.exists(self.PO_FILE_ES))
with open(self.PO_FILE_ES, encoding="utf-8") as fp:
po_contents = fp.read()
found = re.findall(
r'^(?P<value>"Plural-Forms.+?\\n")\s*$',
po_contents,
re.MULTILINE | re.DOTALL,
)
self.assertEqual(1, len(found))
def test_translate_and_plural_blocktranslate_collision(self):
"""
Ensures a correct workaround for the gettext bug when handling a literal
found inside a {% translate %} tag and also in another file inside a
{% blocktranslate %} with a plural (#17375).
"""
management.call_command(
"makemessages", locale=[LOCALE], extensions=["html", "djtpl"], verbosity=0
)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
self.assertNotIn(
"#-#-#-#-# django.pot (PACKAGE VERSION) #-#-#-#-#\\n", po_contents
)
self.assertMsgId(
"First `translate`, then `blocktranslate` with a plural", po_contents
)
self.assertMsgIdPlural(
"Plural for a `translate` and `blocktranslate` collision case",
po_contents,
)
class NoWrapExtractorTests(ExtractorTests):
def test_no_wrap_enabled(self):
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, no_wrap=True
)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
self.assertMsgId(
"This literal should also be included wrapped or not wrapped "
"depending on the use of the --no-wrap option.",
po_contents,
)
def test_no_wrap_disabled(self):
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, no_wrap=False
)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
self.assertMsgId(
'""\n"This literal should also be included wrapped or not '
'wrapped depending on the "\n"use of the --no-wrap option."',
po_contents,
use_quotes=False,
)
class LocationCommentsTests(ExtractorTests):
def test_no_location_enabled(self):
"""Behavior is correct if --no-location switch is specified. See #16903."""
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, no_location=True
)
self.assertTrue(os.path.exists(self.PO_FILE))
self.assertLocationCommentNotPresent(self.PO_FILE, None, "test.html")
def test_no_location_disabled(self):
"""Behavior is correct if --no-location switch isn't specified."""
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, no_location=False
)
self.assertTrue(os.path.exists(self.PO_FILE))
# #16903 -- Standard comment with source file relative path should be present
self.assertLocationCommentPresent(
self.PO_FILE, "Translatable literal #6b", "templates", "test.html"
)
def test_location_comments_for_templatized_files(self):
"""
Ensure no leaky paths in comments, e.g. #: path\to\file.html.py:123
Refs #21209/#26341.
"""
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
self.assertMsgId("#: templates/test.html.py", po_contents)
self.assertLocationCommentNotPresent(self.PO_FILE, None, ".html.py")
self.assertLocationCommentPresent(self.PO_FILE, 5, "templates", "test.html")
@requires_gettext_019
def test_add_location_full(self):
"""makemessages --add-location=full"""
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, add_location="full"
)
self.assertTrue(os.path.exists(self.PO_FILE))
# Comment with source file relative path and line number is present.
self.assertLocationCommentPresent(
self.PO_FILE, "Translatable literal #6b", "templates", "test.html"
)
@requires_gettext_019
def test_add_location_file(self):
"""makemessages --add-location=file"""
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, add_location="file"
)
self.assertTrue(os.path.exists(self.PO_FILE))
# Comment with source file relative path is present.
self.assertLocationCommentPresent(self.PO_FILE, None, "templates", "test.html")
# But it should not contain the line number.
self.assertLocationCommentNotPresent(
self.PO_FILE, "Translatable literal #6b", "templates", "test.html"
)
@requires_gettext_019
def test_add_location_never(self):
"""makemessages --add-location=never"""
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, add_location="never"
)
self.assertTrue(os.path.exists(self.PO_FILE))
self.assertLocationCommentNotPresent(self.PO_FILE, None, "test.html")
@mock.patch(
"django.core.management.commands.makemessages.Command.gettext_version",
new=(0, 18, 99),
)
def test_add_location_gettext_version_check(self):
"""
CommandError is raised when using makemessages --add-location with
gettext < 0.19.
"""
msg = (
"The --add-location option requires gettext 0.19 or later. You have "
"0.18.99."
)
with self.assertRaisesMessage(CommandError, msg):
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, add_location="full"
)
class KeepPotFileExtractorTests(ExtractorTests):
POT_FILE = "locale/django.pot"
def test_keep_pot_disabled_by_default(self):
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertFalse(os.path.exists(self.POT_FILE))
def test_keep_pot_explicitly_disabled(self):
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, keep_pot=False
)
self.assertFalse(os.path.exists(self.POT_FILE))
def test_keep_pot_enabled(self):
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, keep_pot=True
)
self.assertTrue(os.path.exists(self.POT_FILE))
class MultipleLocaleExtractionTests(ExtractorTests):
PO_FILE_PT = "locale/pt/LC_MESSAGES/django.po"
PO_FILE_DE = "locale/de/LC_MESSAGES/django.po"
PO_FILE_KO = "locale/ko/LC_MESSAGES/django.po"
LOCALES = ["pt", "de", "ch"]
def test_multiple_locales(self):
management.call_command("makemessages", locale=["pt", "de"], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE_PT))
self.assertTrue(os.path.exists(self.PO_FILE_DE))
def test_all_locales(self):
"""
When the `locale` flag is absent, all dirs from the parent locale dir
are considered as language directories, except if the directory doesn't
start with two letters (which excludes __pycache__, .gitignore, etc.).
"""
os.mkdir(os.path.join("locale", "_do_not_pick"))
# Excluding locales that do not compile
management.call_command("makemessages", exclude=["ja", "es_AR"], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE_KO))
self.assertFalse(os.path.exists("locale/_do_not_pick/LC_MESSAGES/django.po"))
class ExcludedLocaleExtractionTests(ExtractorTests):
work_subdir = "exclude"
LOCALES = ["en", "fr", "it"]
PO_FILE = "locale/%s/LC_MESSAGES/django.po"
def _set_times_for_all_po_files(self):
"""
Set access and modification times to the Unix epoch time for all the .po files.
"""
for locale in self.LOCALES:
os.utime(self.PO_FILE % locale, (0, 0))
def setUp(self):
super().setUp()
copytree("canned_locale", "locale")
self._set_times_for_all_po_files()
def test_command_help(self):
with captured_stdout(), captured_stderr():
# `call_command` bypasses the parser; by calling
# `execute_from_command_line` with the help subcommand we
# ensure that there are no issues with the parser itself.
execute_from_command_line(["django-admin", "help", "makemessages"])
def test_one_locale_excluded(self):
management.call_command("makemessages", exclude=["it"], verbosity=0)
self.assertRecentlyModified(self.PO_FILE % "en")
self.assertRecentlyModified(self.PO_FILE % "fr")
self.assertNotRecentlyModified(self.PO_FILE % "it")
def test_multiple_locales_excluded(self):
management.call_command("makemessages", exclude=["it", "fr"], verbosity=0)
self.assertRecentlyModified(self.PO_FILE % "en")
self.assertNotRecentlyModified(self.PO_FILE % "fr")
self.assertNotRecentlyModified(self.PO_FILE % "it")
def test_one_locale_excluded_with_locale(self):
management.call_command(
"makemessages", locale=["en", "fr"], exclude=["fr"], verbosity=0
)
self.assertRecentlyModified(self.PO_FILE % "en")
self.assertNotRecentlyModified(self.PO_FILE % "fr")
self.assertNotRecentlyModified(self.PO_FILE % "it")
def test_multiple_locales_excluded_with_locale(self):
management.call_command(
"makemessages", locale=["en", "fr", "it"], exclude=["fr", "it"], verbosity=0
)
self.assertRecentlyModified(self.PO_FILE % "en")
self.assertNotRecentlyModified(self.PO_FILE % "fr")
self.assertNotRecentlyModified(self.PO_FILE % "it")
class CustomLayoutExtractionTests(ExtractorTests):
work_subdir = "project_dir"
def test_no_locale_raises(self):
msg = (
"Unable to find a locale path to store translations for file "
"__init__.py. Make sure the 'locale' directory exists in an app "
"or LOCALE_PATHS setting is set."
)
with self.assertRaisesMessage(management.CommandError, msg):
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
# Working files are cleaned up on an error.
self.assertFalse(os.path.exists("./app_no_locale/test.html.py"))
def test_project_locale_paths(self):
self._test_project_locale_paths(os.path.join(self.test_dir, "project_locale"))
def test_project_locale_paths_pathlib(self):
self._test_project_locale_paths(Path(self.test_dir) / "project_locale")
def _test_project_locale_paths(self, locale_path):
"""
* translations for an app containing a locale folder are stored in that folder
* translations outside of that app are in LOCALE_PATHS[0]
"""
with override_settings(LOCALE_PATHS=[locale_path]):
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
project_de_locale = os.path.join(
self.test_dir, "project_locale", "de", "LC_MESSAGES", "django.po"
)
app_de_locale = os.path.join(
self.test_dir,
"app_with_locale",
"locale",
"de",
"LC_MESSAGES",
"django.po",
)
self.assertTrue(os.path.exists(project_de_locale))
self.assertTrue(os.path.exists(app_de_locale))
with open(project_de_locale) as fp:
po_contents = fp.read()
self.assertMsgId("This app has no locale directory", po_contents)
self.assertMsgId("This is a project-level string", po_contents)
with open(app_de_locale) as fp:
po_contents = fp.read()
self.assertMsgId("This app has a locale directory", po_contents)
@skipUnless(has_xgettext, "xgettext is mandatory for extraction tests")
class NoSettingsExtractionTests(AdminScriptTestCase):
def test_makemessages_no_settings(self):
out, err = self.run_django_admin(["makemessages", "-l", "en", "-v", "0"])
self.assertNoOutput(err)
self.assertNoOutput(out)
class UnchangedPoExtractionTests(ExtractorTests):
work_subdir = "unchanged"
def setUp(self):
super().setUp()
po_file = Path(self.PO_FILE)
po_file_tmp = Path(self.PO_FILE + ".tmp")
if os.name == "nt":
# msgmerge outputs Windows style paths on Windows.
po_contents = po_file_tmp.read_text().replace(
"#: __init__.py",
"#: .\\__init__.py",
)
po_file.write_text(po_contents)
else:
po_file_tmp.rename(po_file)
self.original_po_contents = po_file.read_text()
def test_po_remains_unchanged(self):
"""PO files are unchanged unless there are new changes."""
_, po_contents = self._run_makemessages()
self.assertEqual(po_contents, self.original_po_contents)
def test_po_changed_with_new_strings(self):
"""PO files are updated when new changes are detected."""
Path("models.py.tmp").rename("models.py")
_, po_contents = self._run_makemessages()
self.assertNotEqual(po_contents, self.original_po_contents)
self.assertMsgId(
"This is a hitherto undiscovered translatable string.",
po_contents,
)
|
8edc7659eb30c532676928846e3d75b126923e5e27eecfcf64e76d22bc6dc2a7 | import datetime
import decimal
import gettext as gettext_module
import os
import pickle
import re
import tempfile
from contextlib import contextmanager
from importlib import import_module
from pathlib import Path
from unittest import mock
from asgiref.local import Local
from django import forms
from django.apps import AppConfig
from django.conf import settings
from django.conf.locale import LANG_INFO
from django.conf.urls.i18n import i18n_patterns
from django.template import Context, Template
from django.test import (
RequestFactory,
SimpleTestCase,
TestCase,
ignore_warnings,
override_settings,
)
from django.utils import translation
from django.utils.deprecation import RemovedInDjango50Warning
from django.utils.formats import (
date_format,
get_format,
iter_format_modules,
localize,
localize_input,
reset_format_cache,
sanitize_separators,
sanitize_strftime_format,
time_format,
)
from django.utils.numberformat import format as nformat
from django.utils.safestring import SafeString, mark_safe
from django.utils.translation import (
activate,
check_for_language,
deactivate,
get_language,
get_language_bidi,
get_language_from_request,
get_language_info,
gettext,
gettext_lazy,
ngettext,
ngettext_lazy,
npgettext,
npgettext_lazy,
pgettext,
round_away_from_one,
to_language,
to_locale,
trans_null,
trans_real,
)
from django.utils.translation.reloader import (
translation_file_changed,
watch_for_translation_changes,
)
from .forms import CompanyForm, I18nForm, SelectDateForm
from .models import Company, TestModel
here = os.path.dirname(os.path.abspath(__file__))
extended_locale_paths = settings.LOCALE_PATHS + [
os.path.join(here, "other", "locale"),
]
class AppModuleStub:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
@contextmanager
def patch_formats(lang, **settings):
from django.utils.formats import _format_cache
# Populate _format_cache with temporary values
for key, value in settings.items():
_format_cache[(key, lang)] = value
try:
yield
finally:
reset_format_cache()
class TranslationTests(SimpleTestCase):
@translation.override("fr")
def test_plural(self):
"""
Test plurals with ngettext. French differs from English in that 0 is singular.
"""
self.assertEqual(
ngettext("%(num)d year", "%(num)d years", 0) % {"num": 0},
"0 année",
)
self.assertEqual(
ngettext("%(num)d year", "%(num)d years", 2) % {"num": 2},
"2 années",
)
self.assertEqual(
ngettext("%(size)d byte", "%(size)d bytes", 0) % {"size": 0}, "0 octet"
)
self.assertEqual(
ngettext("%(size)d byte", "%(size)d bytes", 2) % {"size": 2}, "2 octets"
)
def test_plural_null(self):
g = trans_null.ngettext
self.assertEqual(g("%(num)d year", "%(num)d years", 0) % {"num": 0}, "0 years")
self.assertEqual(g("%(num)d year", "%(num)d years", 1) % {"num": 1}, "1 year")
self.assertEqual(g("%(num)d year", "%(num)d years", 2) % {"num": 2}, "2 years")
@override_settings(LOCALE_PATHS=extended_locale_paths)
@translation.override("fr")
def test_multiple_plurals_per_language(self):
"""
Normally, French has 2 plurals. As other/locale/fr/LC_MESSAGES/django.po
has a different plural equation with 3 plurals, this tests if those
plural are honored.
"""
self.assertEqual(ngettext("%d singular", "%d plural", 0) % 0, "0 pluriel1")
self.assertEqual(ngettext("%d singular", "%d plural", 1) % 1, "1 singulier")
self.assertEqual(ngettext("%d singular", "%d plural", 2) % 2, "2 pluriel2")
french = trans_real.catalog()
# Internal _catalog can query subcatalogs (from different po files).
self.assertEqual(french._catalog[("%d singular", 0)], "%d singulier")
self.assertEqual(french._catalog[("%(num)d hour", 0)], "%(num)d heure")
def test_override(self):
activate("de")
try:
with translation.override("pl"):
self.assertEqual(get_language(), "pl")
self.assertEqual(get_language(), "de")
with translation.override(None):
self.assertIsNone(get_language())
with translation.override("pl"):
pass
self.assertIsNone(get_language())
self.assertEqual(get_language(), "de")
finally:
deactivate()
def test_override_decorator(self):
@translation.override("pl")
def func_pl():
self.assertEqual(get_language(), "pl")
@translation.override(None)
def func_none():
self.assertIsNone(get_language())
try:
activate("de")
func_pl()
self.assertEqual(get_language(), "de")
func_none()
self.assertEqual(get_language(), "de")
finally:
deactivate()
def test_override_exit(self):
"""
The language restored is the one used when the function was
called, not the one used when the decorator was initialized (#23381).
"""
activate("fr")
@translation.override("pl")
def func_pl():
pass
deactivate()
try:
activate("en")
func_pl()
self.assertEqual(get_language(), "en")
finally:
deactivate()
def test_lazy_objects(self):
"""
Format string interpolation should work with *_lazy objects.
"""
s = gettext_lazy("Add %(name)s")
d = {"name": "Ringo"}
self.assertEqual("Add Ringo", s % d)
with translation.override("de", deactivate=True):
self.assertEqual("Ringo hinzuf\xfcgen", s % d)
with translation.override("pl"):
self.assertEqual("Dodaj Ringo", s % d)
# It should be possible to compare *_lazy objects.
s1 = gettext_lazy("Add %(name)s")
self.assertEqual(s, s1)
s2 = gettext_lazy("Add %(name)s")
s3 = gettext_lazy("Add %(name)s")
self.assertEqual(s2, s3)
self.assertEqual(s, s2)
s4 = gettext_lazy("Some other string")
self.assertNotEqual(s, s4)
def test_lazy_pickle(self):
s1 = gettext_lazy("test")
self.assertEqual(str(s1), "test")
s2 = pickle.loads(pickle.dumps(s1))
self.assertEqual(str(s2), "test")
@override_settings(LOCALE_PATHS=extended_locale_paths)
def test_ngettext_lazy(self):
simple_with_format = ngettext_lazy("%d good result", "%d good results")
simple_context_with_format = npgettext_lazy(
"Exclamation", "%d good result", "%d good results"
)
simple_without_format = ngettext_lazy("good result", "good results")
with translation.override("de"):
self.assertEqual(simple_with_format % 1, "1 gutes Resultat")
self.assertEqual(simple_with_format % 4, "4 guten Resultate")
self.assertEqual(simple_context_with_format % 1, "1 gutes Resultat!")
self.assertEqual(simple_context_with_format % 4, "4 guten Resultate!")
self.assertEqual(simple_without_format % 1, "gutes Resultat")
self.assertEqual(simple_without_format % 4, "guten Resultate")
complex_nonlazy = ngettext_lazy(
"Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", 4
)
complex_deferred = ngettext_lazy(
"Hi %(name)s, %(num)d good result",
"Hi %(name)s, %(num)d good results",
"num",
)
complex_context_nonlazy = npgettext_lazy(
"Greeting",
"Hi %(name)s, %(num)d good result",
"Hi %(name)s, %(num)d good results",
4,
)
complex_context_deferred = npgettext_lazy(
"Greeting",
"Hi %(name)s, %(num)d good result",
"Hi %(name)s, %(num)d good results",
"num",
)
with translation.override("de"):
self.assertEqual(
complex_nonlazy % {"num": 4, "name": "Jim"},
"Hallo Jim, 4 guten Resultate",
)
self.assertEqual(
complex_deferred % {"name": "Jim", "num": 1},
"Hallo Jim, 1 gutes Resultat",
)
self.assertEqual(
complex_deferred % {"name": "Jim", "num": 5},
"Hallo Jim, 5 guten Resultate",
)
with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"):
complex_deferred % {"name": "Jim"}
self.assertEqual(
complex_context_nonlazy % {"num": 4, "name": "Jim"},
"Willkommen Jim, 4 guten Resultate",
)
self.assertEqual(
complex_context_deferred % {"name": "Jim", "num": 1},
"Willkommen Jim, 1 gutes Resultat",
)
self.assertEqual(
complex_context_deferred % {"name": "Jim", "num": 5},
"Willkommen Jim, 5 guten Resultate",
)
with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"):
complex_context_deferred % {"name": "Jim"}
@override_settings(LOCALE_PATHS=extended_locale_paths)
def test_ngettext_lazy_format_style(self):
simple_with_format = ngettext_lazy("{} good result", "{} good results")
simple_context_with_format = npgettext_lazy(
"Exclamation", "{} good result", "{} good results"
)
with translation.override("de"):
self.assertEqual(simple_with_format.format(1), "1 gutes Resultat")
self.assertEqual(simple_with_format.format(4), "4 guten Resultate")
self.assertEqual(simple_context_with_format.format(1), "1 gutes Resultat!")
self.assertEqual(simple_context_with_format.format(4), "4 guten Resultate!")
complex_nonlazy = ngettext_lazy(
"Hi {name}, {num} good result", "Hi {name}, {num} good results", 4
)
complex_deferred = ngettext_lazy(
"Hi {name}, {num} good result", "Hi {name}, {num} good results", "num"
)
complex_context_nonlazy = npgettext_lazy(
"Greeting",
"Hi {name}, {num} good result",
"Hi {name}, {num} good results",
4,
)
complex_context_deferred = npgettext_lazy(
"Greeting",
"Hi {name}, {num} good result",
"Hi {name}, {num} good results",
"num",
)
with translation.override("de"):
self.assertEqual(
complex_nonlazy.format(num=4, name="Jim"),
"Hallo Jim, 4 guten Resultate",
)
self.assertEqual(
complex_deferred.format(name="Jim", num=1),
"Hallo Jim, 1 gutes Resultat",
)
self.assertEqual(
complex_deferred.format(name="Jim", num=5),
"Hallo Jim, 5 guten Resultate",
)
with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"):
complex_deferred.format(name="Jim")
self.assertEqual(
complex_context_nonlazy.format(num=4, name="Jim"),
"Willkommen Jim, 4 guten Resultate",
)
self.assertEqual(
complex_context_deferred.format(name="Jim", num=1),
"Willkommen Jim, 1 gutes Resultat",
)
self.assertEqual(
complex_context_deferred.format(name="Jim", num=5),
"Willkommen Jim, 5 guten Resultate",
)
with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"):
complex_context_deferred.format(name="Jim")
def test_ngettext_lazy_bool(self):
self.assertTrue(ngettext_lazy("%d good result", "%d good results"))
self.assertFalse(ngettext_lazy("", ""))
def test_ngettext_lazy_pickle(self):
s1 = ngettext_lazy("%d good result", "%d good results")
self.assertEqual(s1 % 1, "1 good result")
self.assertEqual(s1 % 8, "8 good results")
s2 = pickle.loads(pickle.dumps(s1))
self.assertEqual(s2 % 1, "1 good result")
self.assertEqual(s2 % 8, "8 good results")
@override_settings(LOCALE_PATHS=extended_locale_paths)
def test_pgettext(self):
trans_real._active = Local()
trans_real._translations = {}
with translation.override("de"):
self.assertEqual(pgettext("unexisting", "May"), "May")
self.assertEqual(pgettext("month name", "May"), "Mai")
self.assertEqual(pgettext("verb", "May"), "Kann")
self.assertEqual(
npgettext("search", "%d result", "%d results", 4) % 4, "4 Resultate"
)
def test_empty_value(self):
"""Empty value must stay empty after being translated (#23196)."""
with translation.override("de"):
self.assertEqual("", gettext(""))
s = mark_safe("")
self.assertEqual(s, gettext(s))
@override_settings(LOCALE_PATHS=extended_locale_paths)
def test_safe_status(self):
"""
Translating a string requiring no auto-escaping with gettext or pgettext
shouldn't change the "safe" status.
"""
trans_real._active = Local()
trans_real._translations = {}
s1 = mark_safe("Password")
s2 = mark_safe("May")
with translation.override("de", deactivate=True):
self.assertIs(type(gettext(s1)), SafeString)
self.assertIs(type(pgettext("month name", s2)), SafeString)
self.assertEqual("aPassword", SafeString("a") + s1)
self.assertEqual("Passworda", s1 + SafeString("a"))
self.assertEqual("Passworda", s1 + mark_safe("a"))
self.assertEqual("aPassword", mark_safe("a") + s1)
self.assertEqual("as", mark_safe("a") + mark_safe("s"))
def test_maclines(self):
"""
Translations on files with Mac or DOS end of lines will be converted
to unix EOF in .po catalogs.
"""
ca_translation = trans_real.translation("ca")
ca_translation._catalog["Mac\nEOF\n"] = "Catalan Mac\nEOF\n"
ca_translation._catalog["Win\nEOF\n"] = "Catalan Win\nEOF\n"
with translation.override("ca", deactivate=True):
self.assertEqual("Catalan Mac\nEOF\n", gettext("Mac\rEOF\r"))
self.assertEqual("Catalan Win\nEOF\n", gettext("Win\r\nEOF\r\n"))
def test_to_locale(self):
tests = (
("en", "en"),
("EN", "en"),
("en-us", "en_US"),
("EN-US", "en_US"),
("en_US", "en_US"),
# With > 2 characters after the dash.
("sr-latn", "sr_Latn"),
("sr-LATN", "sr_Latn"),
("sr_Latn", "sr_Latn"),
# 3-char language codes.
("ber-MA", "ber_MA"),
("BER-MA", "ber_MA"),
("BER_MA", "ber_MA"),
("ber_MA", "ber_MA"),
# With private use subtag (x-informal).
("nl-nl-x-informal", "nl_NL-x-informal"),
("NL-NL-X-INFORMAL", "nl_NL-x-informal"),
("sr-latn-x-informal", "sr_Latn-x-informal"),
("SR-LATN-X-INFORMAL", "sr_Latn-x-informal"),
)
for lang, locale in tests:
with self.subTest(lang=lang):
self.assertEqual(to_locale(lang), locale)
def test_to_language(self):
self.assertEqual(to_language("en_US"), "en-us")
self.assertEqual(to_language("sr_Lat"), "sr-lat")
def test_language_bidi(self):
self.assertIs(get_language_bidi(), False)
with translation.override(None):
self.assertIs(get_language_bidi(), False)
def test_language_bidi_null(self):
self.assertIs(trans_null.get_language_bidi(), False)
with override_settings(LANGUAGE_CODE="he"):
self.assertIs(get_language_bidi(), True)
class TranslationLoadingTests(SimpleTestCase):
def setUp(self):
"""Clear translation state."""
self._old_language = get_language()
self._old_translations = trans_real._translations
deactivate()
trans_real._translations = {}
def tearDown(self):
trans_real._translations = self._old_translations
activate(self._old_language)
@override_settings(
USE_I18N=True,
LANGUAGE_CODE="en",
LANGUAGES=[
("en", "English"),
("en-ca", "English (Canada)"),
("en-nz", "English (New Zealand)"),
("en-au", "English (Australia)"),
],
LOCALE_PATHS=[os.path.join(here, "loading")],
INSTALLED_APPS=["i18n.loading_app"],
)
def test_translation_loading(self):
"""
"loading_app" does not have translations for all languages provided by
"loading". Catalogs are merged correctly.
"""
tests = [
("en", "local country person"),
("en_AU", "aussie"),
("en_NZ", "kiwi"),
("en_CA", "canuck"),
]
# Load all relevant translations.
for language, _ in tests:
activate(language)
# Catalogs are merged correctly.
for language, nickname in tests:
with self.subTest(language=language):
activate(language)
self.assertEqual(gettext("local country person"), nickname)
class TranslationThreadSafetyTests(SimpleTestCase):
def setUp(self):
self._old_language = get_language()
self._translations = trans_real._translations
# here we rely on .split() being called inside the _fetch()
# in trans_real.translation()
class sideeffect_str(str):
def split(self, *args, **kwargs):
res = str.split(self, *args, **kwargs)
trans_real._translations["en-YY"] = None
return res
trans_real._translations = {sideeffect_str("en-XX"): None}
def tearDown(self):
trans_real._translations = self._translations
activate(self._old_language)
def test_bug14894_translation_activate_thread_safety(self):
translation_count = len(trans_real._translations)
# May raise RuntimeError if translation.activate() isn't thread-safe.
translation.activate("pl")
# make sure sideeffect_str actually added a new translation
self.assertLess(translation_count, len(trans_real._translations))
class FormattingTests(SimpleTestCase):
def setUp(self):
super().setUp()
self.n = decimal.Decimal("66666.666")
self.f = 99999.999
self.d = datetime.date(2009, 12, 31)
self.dt = datetime.datetime(2009, 12, 31, 20, 50)
self.t = datetime.time(10, 15, 48)
self.long = 10000
self.ctxt = Context(
{
"n": self.n,
"t": self.t,
"d": self.d,
"dt": self.dt,
"f": self.f,
"l": self.long,
}
)
def test_all_format_strings(self):
all_locales = LANG_INFO.keys()
some_date = datetime.date(2017, 10, 14)
some_datetime = datetime.datetime(2017, 10, 14, 10, 23)
for locale in all_locales:
with self.subTest(locale=locale), translation.override(locale):
self.assertIn(
"2017", date_format(some_date)
) # Uses DATE_FORMAT by default
self.assertIn(
"23", time_format(some_datetime)
) # Uses TIME_FORMAT by default
self.assertIn(
"2017",
date_format(some_datetime, format=get_format("DATETIME_FORMAT")),
)
self.assertIn(
"2017",
date_format(some_date, format=get_format("YEAR_MONTH_FORMAT")),
)
self.assertIn(
"14", date_format(some_date, format=get_format("MONTH_DAY_FORMAT"))
)
self.assertIn(
"2017",
date_format(some_date, format=get_format("SHORT_DATE_FORMAT")),
)
self.assertIn(
"2017",
date_format(
some_datetime, format=get_format("SHORT_DATETIME_FORMAT")
),
)
def test_locale_independent(self):
"""
Localization of numbers
"""
with self.settings(USE_THOUSAND_SEPARATOR=False):
self.assertEqual(
"66666.66",
nformat(
self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep=","
),
)
self.assertEqual(
"66666A6",
nformat(
self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B"
),
)
self.assertEqual(
"66666",
nformat(
self.n, decimal_sep="X", decimal_pos=0, grouping=1, thousand_sep="Y"
),
)
with self.settings(USE_THOUSAND_SEPARATOR=True):
self.assertEqual(
"66,666.66",
nformat(
self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep=","
),
)
self.assertEqual(
"6B6B6B6B6A6",
nformat(
self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B"
),
)
self.assertEqual(
"-66666.6", nformat(-66666.666, decimal_sep=".", decimal_pos=1)
)
self.assertEqual(
"-66666.0", nformat(int("-66666"), decimal_sep=".", decimal_pos=1)
)
self.assertEqual(
"10000.0", nformat(self.long, decimal_sep=".", decimal_pos=1)
)
self.assertEqual(
"10,00,00,000.00",
nformat(
100000000.00,
decimal_sep=".",
decimal_pos=2,
grouping=(3, 2, 0),
thousand_sep=",",
),
)
self.assertEqual(
"1,0,00,000,0000.00",
nformat(
10000000000.00,
decimal_sep=".",
decimal_pos=2,
grouping=(4, 3, 2, 1, 0),
thousand_sep=",",
),
)
self.assertEqual(
"10000,00,000.00",
nformat(
1000000000.00,
decimal_sep=".",
decimal_pos=2,
grouping=(3, 2, -1),
thousand_sep=",",
),
)
# This unusual grouping/force_grouping combination may be triggered
# by the intcomma filter.
self.assertEqual(
"10000",
nformat(
self.long,
decimal_sep=".",
decimal_pos=0,
grouping=0,
force_grouping=True,
),
)
# date filter
self.assertEqual(
"31.12.2009 в 20:50",
Template('{{ dt|date:"d.m.Y в H:i" }}').render(self.ctxt),
)
self.assertEqual(
"⌚ 10:15", Template('{{ t|time:"⌚ H:i" }}').render(self.ctxt)
)
@ignore_warnings(category=RemovedInDjango50Warning)
@override_settings(USE_L10N=False)
def test_l10n_disabled(self):
"""
Catalan locale with format i18n disabled translations will be used,
but not formats
"""
with translation.override("ca", deactivate=True):
self.maxDiff = 3000
self.assertEqual("N j, Y", get_format("DATE_FORMAT"))
self.assertEqual(0, get_format("FIRST_DAY_OF_WEEK"))
self.assertEqual(".", get_format("DECIMAL_SEPARATOR"))
self.assertEqual("10:15 a.m.", time_format(self.t))
self.assertEqual("Des. 31, 2009", date_format(self.d))
self.assertEqual("desembre 2009", date_format(self.d, "YEAR_MONTH_FORMAT"))
self.assertEqual(
"12/31/2009 8:50 p.m.", date_format(self.dt, "SHORT_DATETIME_FORMAT")
)
self.assertEqual("No localizable", localize("No localizable"))
self.assertEqual("66666.666", localize(self.n))
self.assertEqual("99999.999", localize(self.f))
self.assertEqual("10000", localize(self.long))
self.assertEqual("Des. 31, 2009", localize(self.d))
self.assertEqual("Des. 31, 2009, 8:50 p.m.", localize(self.dt))
self.assertEqual("66666.666", Template("{{ n }}").render(self.ctxt))
self.assertEqual("99999.999", Template("{{ f }}").render(self.ctxt))
self.assertEqual("Des. 31, 2009", Template("{{ d }}").render(self.ctxt))
self.assertEqual(
"Des. 31, 2009, 8:50 p.m.", Template("{{ dt }}").render(self.ctxt)
)
self.assertEqual(
"66666.67", Template('{{ n|floatformat:"2u" }}').render(self.ctxt)
)
self.assertEqual(
"100000.0", Template('{{ f|floatformat:"u" }}').render(self.ctxt)
)
self.assertEqual(
"66666.67",
Template('{{ n|floatformat:"2gu" }}').render(self.ctxt),
)
self.assertEqual(
"100000.0",
Template('{{ f|floatformat:"ug" }}').render(self.ctxt),
)
self.assertEqual(
"10:15 a.m.", Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt)
)
self.assertEqual(
"12/31/2009",
Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt),
)
self.assertEqual(
"12/31/2009 8:50 p.m.",
Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt),
)
form = I18nForm(
{
"decimal_field": "66666,666",
"float_field": "99999,999",
"date_field": "31/12/2009",
"datetime_field": "31/12/2009 20:50",
"time_field": "20:50",
"integer_field": "1.234",
}
)
self.assertFalse(form.is_valid())
self.assertEqual(["Introdu\xefu un n\xfamero."], form.errors["float_field"])
self.assertEqual(
["Introdu\xefu un n\xfamero."], form.errors["decimal_field"]
)
self.assertEqual(
["Introdu\xefu una data v\xe0lida."], form.errors["date_field"]
)
self.assertEqual(
["Introdu\xefu una data/hora v\xe0lides."],
form.errors["datetime_field"],
)
self.assertEqual(
["Introdu\xefu un n\xfamero enter."], form.errors["integer_field"]
)
form2 = SelectDateForm(
{
"date_field_month": "12",
"date_field_day": "31",
"date_field_year": "2009",
}
)
self.assertTrue(form2.is_valid())
self.assertEqual(
datetime.date(2009, 12, 31), form2.cleaned_data["date_field"]
)
self.assertHTMLEqual(
'<select name="mydate_month" id="id_mydate_month">'
'<option value="">---</option>'
'<option value="1">gener</option>'
'<option value="2">febrer</option>'
'<option value="3">mar\xe7</option>'
'<option value="4">abril</option>'
'<option value="5">maig</option>'
'<option value="6">juny</option>'
'<option value="7">juliol</option>'
'<option value="8">agost</option>'
'<option value="9">setembre</option>'
'<option value="10">octubre</option>'
'<option value="11">novembre</option>'
'<option value="12" selected>desembre</option>'
"</select>"
'<select name="mydate_day" id="id_mydate_day">'
'<option value="">---</option>'
'<option value="1">1</option>'
'<option value="2">2</option>'
'<option value="3">3</option>'
'<option value="4">4</option>'
'<option value="5">5</option>'
'<option value="6">6</option>'
'<option value="7">7</option>'
'<option value="8">8</option>'
'<option value="9">9</option>'
'<option value="10">10</option>'
'<option value="11">11</option>'
'<option value="12">12</option>'
'<option value="13">13</option>'
'<option value="14">14</option>'
'<option value="15">15</option>'
'<option value="16">16</option>'
'<option value="17">17</option>'
'<option value="18">18</option>'
'<option value="19">19</option>'
'<option value="20">20</option>'
'<option value="21">21</option>'
'<option value="22">22</option>'
'<option value="23">23</option>'
'<option value="24">24</option>'
'<option value="25">25</option>'
'<option value="26">26</option>'
'<option value="27">27</option>'
'<option value="28">28</option>'
'<option value="29">29</option>'
'<option value="30">30</option>'
'<option value="31" selected>31</option>'
"</select>"
'<select name="mydate_year" id="id_mydate_year">'
'<option value="">---</option>'
'<option value="2009" selected>2009</option>'
'<option value="2010">2010</option>'
'<option value="2011">2011</option>'
'<option value="2012">2012</option>'
'<option value="2013">2013</option>'
'<option value="2014">2014</option>'
'<option value="2015">2015</option>'
'<option value="2016">2016</option>'
'<option value="2017">2017</option>'
'<option value="2018">2018</option>'
"</select>",
forms.SelectDateWidget(years=range(2009, 2019)).render(
"mydate", datetime.date(2009, 12, 31)
),
)
# We shouldn't change the behavior of the floatformat filter re:
# thousand separator and grouping when localization is disabled
# even if the USE_THOUSAND_SEPARATOR, NUMBER_GROUPING and
# THOUSAND_SEPARATOR settings are specified.
with self.settings(
USE_THOUSAND_SEPARATOR=True, NUMBER_GROUPING=1, THOUSAND_SEPARATOR="!"
):
self.assertEqual(
"66666.67", Template('{{ n|floatformat:"2u" }}').render(self.ctxt)
)
self.assertEqual(
"100000.0", Template('{{ f|floatformat:"u" }}').render(self.ctxt)
)
def test_false_like_locale_formats(self):
"""
The active locale's formats take precedence over the default settings
even if they would be interpreted as False in a conditional test
(e.g. 0 or empty string) (#16938).
"""
with translation.override("fr"):
with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="!"):
self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR"))
# Even a second time (after the format has been cached)...
self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR"))
with self.settings(FIRST_DAY_OF_WEEK=0):
self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK"))
# Even a second time (after the format has been cached)...
self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK"))
def test_l10n_enabled(self):
self.maxDiff = 3000
# Catalan locale
with translation.override("ca", deactivate=True):
self.assertEqual(r"j E \d\e Y", get_format("DATE_FORMAT"))
self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK"))
self.assertEqual(",", get_format("DECIMAL_SEPARATOR"))
self.assertEqual("10:15", time_format(self.t))
self.assertEqual("31 desembre de 2009", date_format(self.d))
self.assertEqual("1 abril de 2009", date_format(datetime.date(2009, 4, 1)))
self.assertEqual(
"desembre del 2009", date_format(self.d, "YEAR_MONTH_FORMAT")
)
self.assertEqual(
"31/12/2009 20:50", date_format(self.dt, "SHORT_DATETIME_FORMAT")
)
self.assertEqual("No localizable", localize("No localizable"))
with self.settings(USE_THOUSAND_SEPARATOR=True):
self.assertEqual("66.666,666", localize(self.n))
self.assertEqual("99.999,999", localize(self.f))
self.assertEqual("10.000", localize(self.long))
self.assertEqual("True", localize(True))
with self.settings(USE_THOUSAND_SEPARATOR=False):
self.assertEqual("66666,666", localize(self.n))
self.assertEqual("99999,999", localize(self.f))
self.assertEqual("10000", localize(self.long))
self.assertEqual("31 desembre de 2009", localize(self.d))
self.assertEqual("31 desembre de 2009 a les 20:50", localize(self.dt))
with self.settings(USE_THOUSAND_SEPARATOR=True):
self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt))
self.assertEqual("99.999,999", Template("{{ f }}").render(self.ctxt))
self.assertEqual("10.000", Template("{{ l }}").render(self.ctxt))
with self.settings(USE_THOUSAND_SEPARATOR=True):
form3 = I18nForm(
{
"decimal_field": "66.666,666",
"float_field": "99.999,999",
"date_field": "31/12/2009",
"datetime_field": "31/12/2009 20:50",
"time_field": "20:50",
"integer_field": "1.234",
}
)
self.assertTrue(form3.is_valid())
self.assertEqual(
decimal.Decimal("66666.666"), form3.cleaned_data["decimal_field"]
)
self.assertEqual(99999.999, form3.cleaned_data["float_field"])
self.assertEqual(
datetime.date(2009, 12, 31), form3.cleaned_data["date_field"]
)
self.assertEqual(
datetime.datetime(2009, 12, 31, 20, 50),
form3.cleaned_data["datetime_field"],
)
self.assertEqual(
datetime.time(20, 50), form3.cleaned_data["time_field"]
)
self.assertEqual(1234, form3.cleaned_data["integer_field"])
with self.settings(USE_THOUSAND_SEPARATOR=False):
self.assertEqual("66666,666", Template("{{ n }}").render(self.ctxt))
self.assertEqual("99999,999", Template("{{ f }}").render(self.ctxt))
self.assertEqual(
"31 desembre de 2009", Template("{{ d }}").render(self.ctxt)
)
self.assertEqual(
"31 desembre de 2009 a les 20:50",
Template("{{ dt }}").render(self.ctxt),
)
self.assertEqual(
"66666,67", Template("{{ n|floatformat:2 }}").render(self.ctxt)
)
self.assertEqual(
"100000,0", Template("{{ f|floatformat }}").render(self.ctxt)
)
self.assertEqual(
"66.666,67",
Template('{{ n|floatformat:"2g" }}').render(self.ctxt),
)
self.assertEqual(
"100.000,0",
Template('{{ f|floatformat:"g" }}').render(self.ctxt),
)
self.assertEqual(
"10:15", Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt)
)
self.assertEqual(
"31/12/2009",
Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt),
)
self.assertEqual(
"31/12/2009 20:50",
Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt),
)
self.assertEqual(
date_format(datetime.datetime.now(), "DATE_FORMAT"),
Template('{% now "DATE_FORMAT" %}').render(self.ctxt),
)
with self.settings(USE_THOUSAND_SEPARATOR=False):
form4 = I18nForm(
{
"decimal_field": "66666,666",
"float_field": "99999,999",
"date_field": "31/12/2009",
"datetime_field": "31/12/2009 20:50",
"time_field": "20:50",
"integer_field": "1234",
}
)
self.assertTrue(form4.is_valid())
self.assertEqual(
decimal.Decimal("66666.666"), form4.cleaned_data["decimal_field"]
)
self.assertEqual(99999.999, form4.cleaned_data["float_field"])
self.assertEqual(
datetime.date(2009, 12, 31), form4.cleaned_data["date_field"]
)
self.assertEqual(
datetime.datetime(2009, 12, 31, 20, 50),
form4.cleaned_data["datetime_field"],
)
self.assertEqual(
datetime.time(20, 50), form4.cleaned_data["time_field"]
)
self.assertEqual(1234, form4.cleaned_data["integer_field"])
form5 = SelectDateForm(
{
"date_field_month": "12",
"date_field_day": "31",
"date_field_year": "2009",
}
)
self.assertTrue(form5.is_valid())
self.assertEqual(
datetime.date(2009, 12, 31), form5.cleaned_data["date_field"]
)
self.assertHTMLEqual(
'<select name="mydate_day" id="id_mydate_day">'
'<option value="">---</option>'
'<option value="1">1</option>'
'<option value="2">2</option>'
'<option value="3">3</option>'
'<option value="4">4</option>'
'<option value="5">5</option>'
'<option value="6">6</option>'
'<option value="7">7</option>'
'<option value="8">8</option>'
'<option value="9">9</option>'
'<option value="10">10</option>'
'<option value="11">11</option>'
'<option value="12">12</option>'
'<option value="13">13</option>'
'<option value="14">14</option>'
'<option value="15">15</option>'
'<option value="16">16</option>'
'<option value="17">17</option>'
'<option value="18">18</option>'
'<option value="19">19</option>'
'<option value="20">20</option>'
'<option value="21">21</option>'
'<option value="22">22</option>'
'<option value="23">23</option>'
'<option value="24">24</option>'
'<option value="25">25</option>'
'<option value="26">26</option>'
'<option value="27">27</option>'
'<option value="28">28</option>'
'<option value="29">29</option>'
'<option value="30">30</option>'
'<option value="31" selected>31</option>'
"</select>"
'<select name="mydate_month" id="id_mydate_month">'
'<option value="">---</option>'
'<option value="1">gener</option>'
'<option value="2">febrer</option>'
'<option value="3">mar\xe7</option>'
'<option value="4">abril</option>'
'<option value="5">maig</option>'
'<option value="6">juny</option>'
'<option value="7">juliol</option>'
'<option value="8">agost</option>'
'<option value="9">setembre</option>'
'<option value="10">octubre</option>'
'<option value="11">novembre</option>'
'<option value="12" selected>desembre</option>'
"</select>"
'<select name="mydate_year" id="id_mydate_year">'
'<option value="">---</option>'
'<option value="2009" selected>2009</option>'
'<option value="2010">2010</option>'
'<option value="2011">2011</option>'
'<option value="2012">2012</option>'
'<option value="2013">2013</option>'
'<option value="2014">2014</option>'
'<option value="2015">2015</option>'
'<option value="2016">2016</option>'
'<option value="2017">2017</option>'
'<option value="2018">2018</option>'
"</select>",
forms.SelectDateWidget(years=range(2009, 2019)).render(
"mydate", datetime.date(2009, 12, 31)
),
)
# Russian locale (with E as month)
with translation.override("ru", deactivate=True):
self.assertHTMLEqual(
'<select name="mydate_day" id="id_mydate_day">'
'<option value="">---</option>'
'<option value="1">1</option>'
'<option value="2">2</option>'
'<option value="3">3</option>'
'<option value="4">4</option>'
'<option value="5">5</option>'
'<option value="6">6</option>'
'<option value="7">7</option>'
'<option value="8">8</option>'
'<option value="9">9</option>'
'<option value="10">10</option>'
'<option value="11">11</option>'
'<option value="12">12</option>'
'<option value="13">13</option>'
'<option value="14">14</option>'
'<option value="15">15</option>'
'<option value="16">16</option>'
'<option value="17">17</option>'
'<option value="18">18</option>'
'<option value="19">19</option>'
'<option value="20">20</option>'
'<option value="21">21</option>'
'<option value="22">22</option>'
'<option value="23">23</option>'
'<option value="24">24</option>'
'<option value="25">25</option>'
'<option value="26">26</option>'
'<option value="27">27</option>'
'<option value="28">28</option>'
'<option value="29">29</option>'
'<option value="30">30</option>'
'<option value="31" selected>31</option>'
"</select>"
'<select name="mydate_month" id="id_mydate_month">'
'<option value="">---</option>'
'<option value="1">\u042f\u043d\u0432\u0430\u0440\u044c</option>'
'<option value="2">\u0424\u0435\u0432\u0440\u0430\u043b\u044c</option>'
'<option value="3">\u041c\u0430\u0440\u0442</option>'
'<option value="4">\u0410\u043f\u0440\u0435\u043b\u044c</option>'
'<option value="5">\u041c\u0430\u0439</option>'
'<option value="6">\u0418\u044e\u043d\u044c</option>'
'<option value="7">\u0418\u044e\u043b\u044c</option>'
'<option value="8">\u0410\u0432\u0433\u0443\u0441\u0442</option>'
'<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c'
"</option>"
'<option value="10">\u041e\u043a\u0442\u044f\u0431\u0440\u044c</option>'
'<option value="11">\u041d\u043e\u044f\u0431\u0440\u044c</option>'
'<option value="12" selected>\u0414\u0435\u043a\u0430\u0431\u0440\u044c'
"</option>"
"</select>"
'<select name="mydate_year" id="id_mydate_year">'
'<option value="">---</option>'
'<option value="2009" selected>2009</option>'
'<option value="2010">2010</option>'
'<option value="2011">2011</option>'
'<option value="2012">2012</option>'
'<option value="2013">2013</option>'
'<option value="2014">2014</option>'
'<option value="2015">2015</option>'
'<option value="2016">2016</option>'
'<option value="2017">2017</option>'
'<option value="2018">2018</option>'
"</select>",
forms.SelectDateWidget(years=range(2009, 2019)).render(
"mydate", datetime.date(2009, 12, 31)
),
)
# English locale
with translation.override("en", deactivate=True):
self.assertEqual("N j, Y", get_format("DATE_FORMAT"))
self.assertEqual(0, get_format("FIRST_DAY_OF_WEEK"))
self.assertEqual(".", get_format("DECIMAL_SEPARATOR"))
self.assertEqual("Dec. 31, 2009", date_format(self.d))
self.assertEqual("December 2009", date_format(self.d, "YEAR_MONTH_FORMAT"))
self.assertEqual(
"12/31/2009 8:50 p.m.", date_format(self.dt, "SHORT_DATETIME_FORMAT")
)
self.assertEqual("No localizable", localize("No localizable"))
with self.settings(USE_THOUSAND_SEPARATOR=True):
self.assertEqual("66,666.666", localize(self.n))
self.assertEqual("99,999.999", localize(self.f))
self.assertEqual("10,000", localize(self.long))
with self.settings(USE_THOUSAND_SEPARATOR=False):
self.assertEqual("66666.666", localize(self.n))
self.assertEqual("99999.999", localize(self.f))
self.assertEqual("10000", localize(self.long))
self.assertEqual("Dec. 31, 2009", localize(self.d))
self.assertEqual("Dec. 31, 2009, 8:50 p.m.", localize(self.dt))
with self.settings(USE_THOUSAND_SEPARATOR=True):
self.assertEqual("66,666.666", Template("{{ n }}").render(self.ctxt))
self.assertEqual("99,999.999", Template("{{ f }}").render(self.ctxt))
self.assertEqual("10,000", Template("{{ l }}").render(self.ctxt))
with self.settings(USE_THOUSAND_SEPARATOR=False):
self.assertEqual("66666.666", Template("{{ n }}").render(self.ctxt))
self.assertEqual("99999.999", Template("{{ f }}").render(self.ctxt))
self.assertEqual("Dec. 31, 2009", Template("{{ d }}").render(self.ctxt))
self.assertEqual(
"Dec. 31, 2009, 8:50 p.m.", Template("{{ dt }}").render(self.ctxt)
)
self.assertEqual(
"66666.67", Template("{{ n|floatformat:2 }}").render(self.ctxt)
)
self.assertEqual(
"100000.0", Template("{{ f|floatformat }}").render(self.ctxt)
)
self.assertEqual(
"66,666.67",
Template('{{ n|floatformat:"2g" }}').render(self.ctxt),
)
self.assertEqual(
"100,000.0",
Template('{{ f|floatformat:"g" }}').render(self.ctxt),
)
self.assertEqual(
"12/31/2009",
Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt),
)
self.assertEqual(
"12/31/2009 8:50 p.m.",
Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt),
)
form5 = I18nForm(
{
"decimal_field": "66666.666",
"float_field": "99999.999",
"date_field": "12/31/2009",
"datetime_field": "12/31/2009 20:50",
"time_field": "20:50",
"integer_field": "1234",
}
)
self.assertTrue(form5.is_valid())
self.assertEqual(
decimal.Decimal("66666.666"), form5.cleaned_data["decimal_field"]
)
self.assertEqual(99999.999, form5.cleaned_data["float_field"])
self.assertEqual(
datetime.date(2009, 12, 31), form5.cleaned_data["date_field"]
)
self.assertEqual(
datetime.datetime(2009, 12, 31, 20, 50),
form5.cleaned_data["datetime_field"],
)
self.assertEqual(datetime.time(20, 50), form5.cleaned_data["time_field"])
self.assertEqual(1234, form5.cleaned_data["integer_field"])
form6 = SelectDateForm(
{
"date_field_month": "12",
"date_field_day": "31",
"date_field_year": "2009",
}
)
self.assertTrue(form6.is_valid())
self.assertEqual(
datetime.date(2009, 12, 31), form6.cleaned_data["date_field"]
)
self.assertHTMLEqual(
'<select name="mydate_month" id="id_mydate_month">'
'<option value="">---</option>'
'<option value="1">January</option>'
'<option value="2">February</option>'
'<option value="3">March</option>'
'<option value="4">April</option>'
'<option value="5">May</option>'
'<option value="6">June</option>'
'<option value="7">July</option>'
'<option value="8">August</option>'
'<option value="9">September</option>'
'<option value="10">October</option>'
'<option value="11">November</option>'
'<option value="12" selected>December</option>'
"</select>"
'<select name="mydate_day" id="id_mydate_day">'
'<option value="">---</option>'
'<option value="1">1</option>'
'<option value="2">2</option>'
'<option value="3">3</option>'
'<option value="4">4</option>'
'<option value="5">5</option>'
'<option value="6">6</option>'
'<option value="7">7</option>'
'<option value="8">8</option>'
'<option value="9">9</option>'
'<option value="10">10</option>'
'<option value="11">11</option>'
'<option value="12">12</option>'
'<option value="13">13</option>'
'<option value="14">14</option>'
'<option value="15">15</option>'
'<option value="16">16</option>'
'<option value="17">17</option>'
'<option value="18">18</option>'
'<option value="19">19</option>'
'<option value="20">20</option>'
'<option value="21">21</option>'
'<option value="22">22</option>'
'<option value="23">23</option>'
'<option value="24">24</option>'
'<option value="25">25</option>'
'<option value="26">26</option>'
'<option value="27">27</option>'
'<option value="28">28</option>'
'<option value="29">29</option>'
'<option value="30">30</option>'
'<option value="31" selected>31</option>'
"</select>"
'<select name="mydate_year" id="id_mydate_year">'
'<option value="">---</option>'
'<option value="2009" selected>2009</option>'
'<option value="2010">2010</option>'
'<option value="2011">2011</option>'
'<option value="2012">2012</option>'
'<option value="2013">2013</option>'
'<option value="2014">2014</option>'
'<option value="2015">2015</option>'
'<option value="2016">2016</option>'
'<option value="2017">2017</option>'
'<option value="2018">2018</option>'
"</select>",
forms.SelectDateWidget(years=range(2009, 2019)).render(
"mydate", datetime.date(2009, 12, 31)
),
)
def test_sub_locales(self):
"""
Check if sublocales fall back to the main locale
"""
with self.settings(USE_THOUSAND_SEPARATOR=True):
with translation.override("de-at", deactivate=True):
self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt))
with translation.override("es-us", deactivate=True):
self.assertEqual("31 de diciembre de 2009", date_format(self.d))
def test_localized_input(self):
"""
Tests if form input is correctly localized
"""
self.maxDiff = 1200
with translation.override("de-at", deactivate=True):
form6 = CompanyForm(
{
"name": "acme",
"date_added": datetime.datetime(2009, 12, 31, 6, 0, 0),
"cents_paid": decimal.Decimal("59.47"),
"products_delivered": 12000,
}
)
self.assertTrue(form6.is_valid())
self.assertHTMLEqual(
form6.as_ul(),
'<li><label for="id_name">Name:</label>'
'<input id="id_name" type="text" name="name" value="acme" '
' maxlength="50" required></li>'
'<li><label for="id_date_added">Date added:</label>'
'<input type="text" name="date_added" value="31.12.2009 06:00:00" '
' id="id_date_added" required></li>'
'<li><label for="id_cents_paid">Cents paid:</label>'
'<input type="text" name="cents_paid" value="59,47" id="id_cents_paid" '
" required></li>"
'<li><label for="id_products_delivered">Products delivered:</label>'
'<input type="text" name="products_delivered" value="12000" '
' id="id_products_delivered" required>'
"</li>",
)
self.assertEqual(
localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)),
"31.12.2009 06:00:00",
)
self.assertEqual(
datetime.datetime(2009, 12, 31, 6, 0, 0),
form6.cleaned_data["date_added"],
)
with self.settings(USE_THOUSAND_SEPARATOR=True):
# Checking for the localized "products_delivered" field
self.assertInHTML(
'<input type="text" name="products_delivered" '
'value="12.000" id="id_products_delivered" required>',
form6.as_ul(),
)
def test_localized_input_func(self):
tests = (
(True, "True"),
(datetime.date(1, 1, 1), "0001-01-01"),
(datetime.datetime(1, 1, 1), "0001-01-01 00:00:00"),
)
with self.settings(USE_THOUSAND_SEPARATOR=True):
for value, expected in tests:
with self.subTest(value=value):
self.assertEqual(localize_input(value), expected)
def test_sanitize_strftime_format(self):
for year in (1, 99, 999, 1000):
dt = datetime.date(year, 1, 1)
for fmt, expected in [
("%C", "%02d" % (year // 100)),
("%F", "%04d-01-01" % year),
("%G", "%04d" % year),
("%Y", "%04d" % year),
]:
with self.subTest(year=year, fmt=fmt):
fmt = sanitize_strftime_format(fmt)
self.assertEqual(dt.strftime(fmt), expected)
def test_sanitize_strftime_format_with_escaped_percent(self):
dt = datetime.date(1, 1, 1)
for fmt, expected in [
("%%C", "%C"),
("%%F", "%F"),
("%%G", "%G"),
("%%Y", "%Y"),
("%%%%C", "%%C"),
("%%%%F", "%%F"),
("%%%%G", "%%G"),
("%%%%Y", "%%Y"),
]:
with self.subTest(fmt=fmt):
fmt = sanitize_strftime_format(fmt)
self.assertEqual(dt.strftime(fmt), expected)
for year in (1, 99, 999, 1000):
dt = datetime.date(year, 1, 1)
for fmt, expected in [
("%%%C", "%%%02d" % (year // 100)),
("%%%F", "%%%04d-01-01" % year),
("%%%G", "%%%04d" % year),
("%%%Y", "%%%04d" % year),
("%%%%%C", "%%%%%02d" % (year // 100)),
("%%%%%F", "%%%%%04d-01-01" % year),
("%%%%%G", "%%%%%04d" % year),
("%%%%%Y", "%%%%%04d" % year),
]:
with self.subTest(year=year, fmt=fmt):
fmt = sanitize_strftime_format(fmt)
self.assertEqual(dt.strftime(fmt), expected)
def test_sanitize_separators(self):
"""
Tests django.utils.formats.sanitize_separators.
"""
# Non-strings are untouched
self.assertEqual(sanitize_separators(123), 123)
with translation.override("ru", deactivate=True):
# Russian locale has non-breaking space (\xa0) as thousand separator
# Usual space is accepted too when sanitizing inputs
with self.settings(USE_THOUSAND_SEPARATOR=True):
self.assertEqual(sanitize_separators("1\xa0234\xa0567"), "1234567")
self.assertEqual(sanitize_separators("77\xa0777,777"), "77777.777")
self.assertEqual(sanitize_separators("12 345"), "12345")
self.assertEqual(sanitize_separators("77 777,777"), "77777.777")
with translation.override(None): # RemovedInDjango50Warning
with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="."):
self.assertEqual(sanitize_separators("12\xa0345"), "12\xa0345")
with self.settings(USE_THOUSAND_SEPARATOR=True):
with patch_formats(
get_language(), THOUSAND_SEPARATOR=".", DECIMAL_SEPARATOR=","
):
self.assertEqual(sanitize_separators("10.234"), "10234")
# Suspicion that user entered dot as decimal separator (#22171)
self.assertEqual(sanitize_separators("10.10"), "10.10")
# RemovedInDjango50Warning: When the deprecation ends, remove
# @ignore_warnings and USE_L10N=False. The assertions should remain
# because format-related settings will take precedence over
# locale-dictated formats.
with ignore_warnings(category=RemovedInDjango50Warning):
with self.settings(USE_L10N=False):
with self.settings(DECIMAL_SEPARATOR=","):
self.assertEqual(sanitize_separators("1001,10"), "1001.10")
self.assertEqual(sanitize_separators("1001.10"), "1001.10")
with self.settings(
DECIMAL_SEPARATOR=",",
THOUSAND_SEPARATOR=".",
USE_THOUSAND_SEPARATOR=True,
):
self.assertEqual(sanitize_separators("1.001,10"), "1001.10")
self.assertEqual(sanitize_separators("1001,10"), "1001.10")
self.assertEqual(sanitize_separators("1001.10"), "1001.10")
# Invalid output.
self.assertEqual(sanitize_separators("1,001.10"), "1.001.10")
def test_iter_format_modules(self):
"""
Tests the iter_format_modules function.
"""
# Importing some format modules so that we can compare the returned
# modules with these expected modules
default_mod = import_module("django.conf.locale.de.formats")
test_mod = import_module("i18n.other.locale.de.formats")
test_mod2 = import_module("i18n.other2.locale.de.formats")
with translation.override("de-at", deactivate=True):
# Should return the correct default module when no setting is set
self.assertEqual(list(iter_format_modules("de")), [default_mod])
# When the setting is a string, should return the given module and
# the default module
self.assertEqual(
list(iter_format_modules("de", "i18n.other.locale")),
[test_mod, default_mod],
)
# When setting is a list of strings, should return the given
# modules and the default module
self.assertEqual(
list(
iter_format_modules(
"de", ["i18n.other.locale", "i18n.other2.locale"]
)
),
[test_mod, test_mod2, default_mod],
)
def test_iter_format_modules_stability(self):
"""
Tests the iter_format_modules function always yields format modules in
a stable and correct order in presence of both base ll and ll_CC formats.
"""
en_format_mod = import_module("django.conf.locale.en.formats")
en_gb_format_mod = import_module("django.conf.locale.en_GB.formats")
self.assertEqual(
list(iter_format_modules("en-gb")), [en_gb_format_mod, en_format_mod]
)
def test_get_format_modules_lang(self):
with translation.override("de", deactivate=True):
self.assertEqual(".", get_format("DECIMAL_SEPARATOR", lang="en"))
def test_get_format_lazy_format(self):
self.assertEqual(get_format(gettext_lazy("DATE_FORMAT")), "N j, Y")
def test_localize_templatetag_and_filter(self):
"""
Test the {% localize %} templatetag and the localize/unlocalize filters.
"""
context = Context(
{"int": 1455, "float": 3.14, "date": datetime.date(2016, 12, 31)}
)
template1 = Template(
"{% load l10n %}{% localize %}"
"{{ int }}/{{ float }}/{{ date }}{% endlocalize %}; "
"{% localize on %}{{ int }}/{{ float }}/{{ date }}{% endlocalize %}"
)
template2 = Template(
"{% load l10n %}{{ int }}/{{ float }}/{{ date }}; "
"{% localize off %}{{ int }}/{{ float }}/{{ date }};{% endlocalize %} "
"{{ int }}/{{ float }}/{{ date }}"
)
template3 = Template(
"{% load l10n %}{{ int }}/{{ float }}/{{ date }}; "
"{{ int|unlocalize }}/{{ float|unlocalize }}/{{ date|unlocalize }}"
)
template4 = Template(
"{% load l10n %}{{ int }}/{{ float }}/{{ date }}; "
"{{ int|localize }}/{{ float|localize }}/{{ date|localize }}"
)
expected_localized = "1.455/3,14/31. Dezember 2016"
expected_unlocalized = "1455/3.14/Dez. 31, 2016"
output1 = "; ".join([expected_localized, expected_localized])
output2 = "; ".join(
[expected_localized, expected_unlocalized, expected_localized]
)
output3 = "; ".join([expected_localized, expected_unlocalized])
output4 = "; ".join([expected_unlocalized, expected_localized])
with translation.override("de", deactivate=True):
# RemovedInDjango50Warning: When the deprecation ends, remove
# @ignore_warnings and USE_L10N=False. The assertions should remain
# because format-related settings will take precedence over
# locale-dictated formats.
with ignore_warnings(category=RemovedInDjango50Warning):
with self.settings(
USE_L10N=False,
DATE_FORMAT="N j, Y",
DECIMAL_SEPARATOR=".",
NUMBER_GROUPING=0,
USE_THOUSAND_SEPARATOR=True,
):
self.assertEqual(template1.render(context), output1)
self.assertEqual(template4.render(context), output4)
with self.settings(USE_THOUSAND_SEPARATOR=True):
self.assertEqual(template1.render(context), output1)
self.assertEqual(template2.render(context), output2)
self.assertEqual(template3.render(context), output3)
def test_localized_off_numbers(self):
"""A string representation is returned for unlocalized numbers."""
template = Template(
"{% load l10n %}{% localize off %}"
"{{ int }}/{{ float }}/{{ decimal }}{% endlocalize %}"
)
context = Context(
{"int": 1455, "float": 3.14, "decimal": decimal.Decimal("24.1567")}
)
with self.settings(
DECIMAL_SEPARATOR=",",
USE_THOUSAND_SEPARATOR=True,
THOUSAND_SEPARATOR="°",
NUMBER_GROUPING=2,
):
self.assertEqual(template.render(context), "1455/3.14/24.1567")
# RemovedInDjango50Warning.
with ignore_warnings(category=RemovedInDjango50Warning):
with self.settings(
USE_L10N=False,
DECIMAL_SEPARATOR=",",
USE_THOUSAND_SEPARATOR=True,
THOUSAND_SEPARATOR="°",
NUMBER_GROUPING=2,
):
self.assertEqual(template.render(context), "1455/3.14/24.1567")
def test_localized_as_text_as_hidden_input(self):
"""
Form input with 'as_hidden' or 'as_text' is correctly localized.
"""
self.maxDiff = 1200
with translation.override("de-at", deactivate=True):
template = Template(
"{% load l10n %}{{ form.date_added }}; {{ form.cents_paid }}"
)
template_as_text = Template(
"{% load l10n %}"
"{{ form.date_added.as_text }}; {{ form.cents_paid.as_text }}"
)
template_as_hidden = Template(
"{% load l10n %}"
"{{ form.date_added.as_hidden }}; {{ form.cents_paid.as_hidden }}"
)
form = CompanyForm(
{
"name": "acme",
"date_added": datetime.datetime(2009, 12, 31, 6, 0, 0),
"cents_paid": decimal.Decimal("59.47"),
"products_delivered": 12000,
}
)
context = Context({"form": form})
self.assertTrue(form.is_valid())
self.assertHTMLEqual(
template.render(context),
'<input id="id_date_added" name="date_added" type="text" '
'value="31.12.2009 06:00:00" required>;'
'<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" '
"required>",
)
self.assertHTMLEqual(
template_as_text.render(context),
'<input id="id_date_added" name="date_added" type="text" '
'value="31.12.2009 06:00:00" required>;'
'<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" '
"required>",
)
self.assertHTMLEqual(
template_as_hidden.render(context),
'<input id="id_date_added" name="date_added" type="hidden" '
'value="31.12.2009 06:00:00">;'
'<input id="id_cents_paid" name="cents_paid" type="hidden" '
'value="59,47">',
)
def test_format_arbitrary_settings(self):
self.assertEqual(get_format("DEBUG"), "DEBUG")
def test_get_custom_format(self):
reset_format_cache()
with self.settings(FORMAT_MODULE_PATH="i18n.other.locale"):
with translation.override("fr", deactivate=True):
self.assertEqual("d/m/Y CUSTOM", get_format("CUSTOM_DAY_FORMAT"))
def test_admin_javascript_supported_input_formats(self):
"""
The first input format for DATE_INPUT_FORMATS, TIME_INPUT_FORMATS, and
DATETIME_INPUT_FORMATS must not contain %f since that's unsupported by
the admin's time picker widget.
"""
regex = re.compile("%([^BcdHImMpSwxXyY%])")
for language_code, language_name in settings.LANGUAGES:
for format_name in (
"DATE_INPUT_FORMATS",
"TIME_INPUT_FORMATS",
"DATETIME_INPUT_FORMATS",
):
with self.subTest(language=language_code, format=format_name):
formatter = get_format(format_name, lang=language_code)[0]
self.assertEqual(
regex.findall(formatter),
[],
"%s locale's %s uses an unsupported format code."
% (language_code, format_name),
)
class MiscTests(SimpleTestCase):
rf = RequestFactory()
@override_settings(LANGUAGE_CODE="de")
def test_english_fallback(self):
"""
With a non-English LANGUAGE_CODE and if the active language is English
or one of its variants, the untranslated string should be returned
(instead of falling back to LANGUAGE_CODE) (See #24413).
"""
self.assertEqual(gettext("Image"), "Bild")
with translation.override("en"):
self.assertEqual(gettext("Image"), "Image")
with translation.override("en-us"):
self.assertEqual(gettext("Image"), "Image")
with translation.override("en-ca"):
self.assertEqual(gettext("Image"), "Image")
def test_parse_spec_http_header(self):
"""
Testing HTTP header parsing. First, we test that we can parse the
values according to the spec (and that we extract all the pieces in
the right order).
"""
tests = [
# Good headers
("de", [("de", 1.0)]),
("en-AU", [("en-au", 1.0)]),
("es-419", [("es-419", 1.0)]),
("*;q=1.00", [("*", 1.0)]),
("en-AU;q=0.123", [("en-au", 0.123)]),
("en-au;q=0.5", [("en-au", 0.5)]),
("en-au;q=1.0", [("en-au", 1.0)]),
("da, en-gb;q=0.25, en;q=0.5", [("da", 1.0), ("en", 0.5), ("en-gb", 0.25)]),
("en-au-xx", [("en-au-xx", 1.0)]),
(
"de,en-au;q=0.75,en-us;q=0.5,en;q=0.25,es;q=0.125,fa;q=0.125",
[
("de", 1.0),
("en-au", 0.75),
("en-us", 0.5),
("en", 0.25),
("es", 0.125),
("fa", 0.125),
],
),
("*", [("*", 1.0)]),
("de;q=0.", [("de", 0.0)]),
("en; q=1,", [("en", 1.0)]),
("en; q=1.0, * ; q=0.5", [("en", 1.0), ("*", 0.5)]),
# Bad headers
("en-gb;q=1.0000", []),
("en;q=0.1234", []),
("en;q=.2", []),
("abcdefghi-au", []),
("**", []),
("en,,gb", []),
("en-au;q=0.1.0", []),
(("X" * 97) + "Z,en", []),
("da, en-gb;q=0.8, en;q=0.7,#", []),
("de;q=2.0", []),
("de;q=0.a", []),
("12-345", []),
("", []),
("en;q=1e0", []),
("en-au;q=1.0", []),
]
for value, expected in tests:
with self.subTest(value=value):
self.assertEqual(
trans_real.parse_accept_lang_header(value), tuple(expected)
)
def test_parse_literal_http_header(self):
tests = [
("pt-br", "pt-br"),
("pt", "pt"),
("es,de", "es"),
("es-a,de", "es"),
# There isn't a Django translation to a US variation of the Spanish
# language, a safe assumption. When the user sets it as the
# preferred language, the main 'es' translation should be selected
# instead.
("es-us", "es"),
# There isn't a main language (zh) translation of Django but there
# is a translation to variation (zh-hans) the user sets zh-hans as
# the preferred language, it should be selected without falling
# back nor ignoring it.
("zh-hans,de", "zh-hans"),
("NL", "nl"),
("fy", "fy"),
("ia", "ia"),
("sr-latn", "sr-latn"),
("zh-hans", "zh-hans"),
("zh-hant", "zh-hant"),
]
for header, expected in tests:
with self.subTest(header=header):
request = self.rf.get("/", HTTP_ACCEPT_LANGUAGE=header)
self.assertEqual(get_language_from_request(request), expected)
@override_settings(
LANGUAGES=[
("en", "English"),
("zh-hans", "Simplified Chinese"),
("zh-hant", "Traditional Chinese"),
]
)
def test_support_for_deprecated_chinese_language_codes(self):
"""
Some browsers (Firefox, IE, etc.) use deprecated language codes. As these
language codes will be removed in Django 1.9, these will be incorrectly
matched. For example zh-tw (traditional) will be interpreted as zh-hans
(simplified), which is wrong. So we should also accept these deprecated
language codes.
refs #18419 -- this is explicitly for browser compatibility
"""
g = get_language_from_request
request = self.rf.get("/", HTTP_ACCEPT_LANGUAGE="zh-cn,en")
self.assertEqual(g(request), "zh-hans")
request = self.rf.get("/", HTTP_ACCEPT_LANGUAGE="zh-tw,en")
self.assertEqual(g(request), "zh-hant")
def test_special_fallback_language(self):
"""
Some languages may have special fallbacks that don't follow the simple
'fr-ca' -> 'fr' logic (notably Chinese codes).
"""
request = self.rf.get("/", HTTP_ACCEPT_LANGUAGE="zh-my,en")
self.assertEqual(get_language_from_request(request), "zh-hans")
def test_subsequent_code_fallback_language(self):
"""
Subsequent language codes should be used when the language code is not
supported.
"""
tests = [
("zh-Hans-CN", "zh-hans"),
("zh-hans-mo", "zh-hans"),
("zh-hans-HK", "zh-hans"),
("zh-Hant-HK", "zh-hant"),
("zh-hant-tw", "zh-hant"),
("zh-hant-SG", "zh-hant"),
]
for value, expected in tests:
with self.subTest(value=value):
request = self.rf.get("/", HTTP_ACCEPT_LANGUAGE=f"{value},en")
self.assertEqual(get_language_from_request(request), expected)
def test_parse_language_cookie(self):
g = get_language_from_request
request = self.rf.get("/")
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "pt-br"
self.assertEqual("pt-br", g(request))
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "pt"
self.assertEqual("pt", g(request))
request = self.rf.get("/", HTTP_ACCEPT_LANGUAGE="de")
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "es"
self.assertEqual("es", g(request))
# There isn't a Django translation to a US variation of the Spanish
# language, a safe assumption. When the user sets it as the preferred
# language, the main 'es' translation should be selected instead.
request = self.rf.get("/")
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "es-us"
self.assertEqual(g(request), "es")
# There isn't a main language (zh) translation of Django but there is a
# translation to variation (zh-hans) the user sets zh-hans as the
# preferred language, it should be selected without falling back nor
# ignoring it.
request = self.rf.get("/", HTTP_ACCEPT_LANGUAGE="de")
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "zh-hans"
self.assertEqual(g(request), "zh-hans")
@override_settings(
USE_I18N=True,
LANGUAGES=[
("en", "English"),
("ar-dz", "Algerian Arabic"),
("de", "German"),
("de-at", "Austrian German"),
("pt-BR", "Portuguese (Brazil)"),
],
)
def test_get_supported_language_variant_real(self):
g = trans_real.get_supported_language_variant
self.assertEqual(g("en"), "en")
self.assertEqual(g("en-gb"), "en")
self.assertEqual(g("de"), "de")
self.assertEqual(g("de-at"), "de-at")
self.assertEqual(g("de-ch"), "de")
self.assertEqual(g("pt-br"), "pt-br")
self.assertEqual(g("pt-BR"), "pt-BR")
self.assertEqual(g("pt"), "pt-br")
self.assertEqual(g("pt-pt"), "pt-br")
self.assertEqual(g("ar-dz"), "ar-dz")
self.assertEqual(g("ar-DZ"), "ar-DZ")
with self.assertRaises(LookupError):
g("pt", strict=True)
with self.assertRaises(LookupError):
g("pt-pt", strict=True)
with self.assertRaises(LookupError):
g("xyz")
with self.assertRaises(LookupError):
g("xy-zz")
def test_get_supported_language_variant_null(self):
g = trans_null.get_supported_language_variant
self.assertEqual(g(settings.LANGUAGE_CODE), settings.LANGUAGE_CODE)
with self.assertRaises(LookupError):
g("pt")
with self.assertRaises(LookupError):
g("de")
with self.assertRaises(LookupError):
g("de-at")
with self.assertRaises(LookupError):
g("de", strict=True)
with self.assertRaises(LookupError):
g("de-at", strict=True)
with self.assertRaises(LookupError):
g("xyz")
@override_settings(
LANGUAGES=[
("en", "English"),
("en-latn-us", "Latin English"),
("de", "German"),
("de-1996", "German, orthography of 1996"),
("de-at", "Austrian German"),
("de-ch-1901", "German, Swiss variant, traditional orthography"),
("i-mingo", "Mingo"),
("kl-tunumiit", "Tunumiisiut"),
("nan-hani-tw", "Hanji"),
("pl", "Polish"),
],
)
def test_get_language_from_path_real(self):
g = trans_real.get_language_from_path
tests = [
("/pl/", "pl"),
("/pl", "pl"),
("/xyz/", None),
("/en/", "en"),
("/en-gb/", "en"),
("/en-latn-us/", "en-latn-us"),
("/en-Latn-US/", "en-Latn-US"),
("/de/", "de"),
("/de-1996/", "de-1996"),
("/de-at/", "de-at"),
("/de-AT/", "de-AT"),
("/de-ch/", "de"),
("/de-ch-1901/", "de-ch-1901"),
("/de-simple-page-test/", None),
("/i-mingo/", "i-mingo"),
("/kl-tunumiit/", "kl-tunumiit"),
("/nan-hani-tw/", "nan-hani-tw"),
]
for path, language in tests:
with self.subTest(path=path):
self.assertEqual(g(path), language)
def test_get_language_from_path_null(self):
g = trans_null.get_language_from_path
self.assertIsNone(g("/pl/"))
self.assertIsNone(g("/pl"))
self.assertIsNone(g("/xyz/"))
def test_cache_resetting(self):
"""
After setting LANGUAGE, the cache should be cleared and languages
previously valid should not be used (#14170).
"""
g = get_language_from_request
request = self.rf.get("/", HTTP_ACCEPT_LANGUAGE="pt-br")
self.assertEqual("pt-br", g(request))
with self.settings(LANGUAGES=[("en", "English")]):
self.assertNotEqual("pt-br", g(request))
def test_i18n_patterns_returns_list(self):
with override_settings(USE_I18N=False):
self.assertIsInstance(i18n_patterns([]), list)
with override_settings(USE_I18N=True):
self.assertIsInstance(i18n_patterns([]), list)
class ResolutionOrderI18NTests(SimpleTestCase):
def setUp(self):
super().setUp()
activate("de")
def tearDown(self):
deactivate()
super().tearDown()
def assertGettext(self, msgid, msgstr):
result = gettext(msgid)
self.assertIn(
msgstr,
result,
"The string '%s' isn't in the translation of '%s'; the actual result is "
"'%s'." % (msgstr, msgid, result),
)
class AppResolutionOrderI18NTests(ResolutionOrderI18NTests):
@override_settings(LANGUAGE_CODE="de")
def test_app_translation(self):
# Original translation.
self.assertGettext("Date/time", "Datum/Zeit")
# Different translation.
with self.modify_settings(INSTALLED_APPS={"append": "i18n.resolution"}):
# Force refreshing translations.
activate("de")
# Doesn't work because it's added later in the list.
self.assertGettext("Date/time", "Datum/Zeit")
with self.modify_settings(
INSTALLED_APPS={"remove": "django.contrib.admin.apps.SimpleAdminConfig"}
):
# Force refreshing translations.
activate("de")
# Unless the original is removed from the list.
self.assertGettext("Date/time", "Datum/Zeit (APP)")
@override_settings(LOCALE_PATHS=extended_locale_paths)
class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests):
def test_locale_paths_translation(self):
self.assertGettext("Time", "LOCALE_PATHS")
def test_locale_paths_override_app_translation(self):
with self.settings(INSTALLED_APPS=["i18n.resolution"]):
self.assertGettext("Time", "LOCALE_PATHS")
class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests):
def test_django_fallback(self):
self.assertEqual(gettext("Date/time"), "Datum/Zeit")
@override_settings(INSTALLED_APPS=["i18n.territorial_fallback"])
class TranslationFallbackI18NTests(ResolutionOrderI18NTests):
def test_sparse_territory_catalog(self):
"""
Untranslated strings for territorial language variants use the
translations of the generic language. In this case, the de-de
translation falls back to de.
"""
with translation.override("de-de"):
self.assertGettext("Test 1 (en)", "(de-de)")
self.assertGettext("Test 2 (en)", "(de)")
class TestModels(TestCase):
def test_lazy(self):
tm = TestModel()
tm.save()
def test_safestr(self):
c = Company(cents_paid=12, products_delivered=1)
c.name = SafeString("Iñtërnâtiônàlizætiøn1")
c.save()
class TestLanguageInfo(SimpleTestCase):
def test_localized_language_info(self):
li = get_language_info("de")
self.assertEqual(li["code"], "de")
self.assertEqual(li["name_local"], "Deutsch")
self.assertEqual(li["name"], "German")
self.assertIs(li["bidi"], False)
def test_unknown_language_code(self):
with self.assertRaisesMessage(KeyError, "Unknown language code xx"):
get_language_info("xx")
with translation.override("xx"):
# A language with no translation catalogs should fallback to the
# untranslated string.
self.assertEqual(gettext("Title"), "Title")
def test_unknown_only_country_code(self):
li = get_language_info("de-xx")
self.assertEqual(li["code"], "de")
self.assertEqual(li["name_local"], "Deutsch")
self.assertEqual(li["name"], "German")
self.assertIs(li["bidi"], False)
def test_unknown_language_code_and_country_code(self):
with self.assertRaisesMessage(KeyError, "Unknown language code xx-xx and xx"):
get_language_info("xx-xx")
def test_fallback_language_code(self):
"""
get_language_info return the first fallback language info if the lang_info
struct does not contain the 'name' key.
"""
li = get_language_info("zh-my")
self.assertEqual(li["code"], "zh-hans")
li = get_language_info("zh-hans")
self.assertEqual(li["code"], "zh-hans")
@override_settings(
USE_I18N=True,
LANGUAGES=[
("en", "English"),
("fr", "French"),
],
MIDDLEWARE=[
"django.middleware.locale.LocaleMiddleware",
"django.middleware.common.CommonMiddleware",
],
ROOT_URLCONF="i18n.urls",
)
class LocaleMiddlewareTests(TestCase):
def test_streaming_response(self):
# Regression test for #5241
response = self.client.get("/fr/streaming/")
self.assertContains(response, "Oui/Non")
response = self.client.get("/en/streaming/")
self.assertContains(response, "Yes/No")
@override_settings(
USE_I18N=True,
LANGUAGES=[
("en", "English"),
("de", "German"),
("fr", "French"),
],
MIDDLEWARE=[
"django.middleware.locale.LocaleMiddleware",
"django.middleware.common.CommonMiddleware",
],
ROOT_URLCONF="i18n.urls_default_unprefixed",
LANGUAGE_CODE="en",
)
class UnprefixedDefaultLanguageTests(SimpleTestCase):
def test_default_lang_without_prefix(self):
"""
With i18n_patterns(..., prefix_default_language=False), the default
language (settings.LANGUAGE_CODE) should be accessible without a prefix.
"""
response = self.client.get("/simple/")
self.assertEqual(response.content, b"Yes")
def test_other_lang_with_prefix(self):
response = self.client.get("/fr/simple/")
self.assertEqual(response.content, b"Oui")
def test_unprefixed_language_with_accept_language(self):
"""'Accept-Language' is respected."""
response = self.client.get("/simple/", HTTP_ACCEPT_LANGUAGE="fr")
self.assertRedirects(response, "/fr/simple/")
def test_unprefixed_language_with_cookie_language(self):
"""A language set in the cookies is respected."""
self.client.cookies.load({settings.LANGUAGE_COOKIE_NAME: "fr"})
response = self.client.get("/simple/")
self.assertRedirects(response, "/fr/simple/")
def test_unprefixed_language_with_non_valid_language(self):
response = self.client.get("/simple/", HTTP_ACCEPT_LANGUAGE="fi")
self.assertEqual(response.content, b"Yes")
self.client.cookies.load({settings.LANGUAGE_COOKIE_NAME: "fi"})
response = self.client.get("/simple/")
self.assertEqual(response.content, b"Yes")
def test_page_with_dash(self):
# A page starting with /de* shouldn't match the 'de' language code.
response = self.client.get("/de-simple-page-test/")
self.assertEqual(response.content, b"Yes")
def test_no_redirect_on_404(self):
"""
A request for a nonexistent URL shouldn't cause a redirect to
/<default_language>/<request_url> when prefix_default_language=False and
/<default_language>/<request_url> has a URL match (#27402).
"""
# A match for /group1/group2/ must exist for this to act as a
# regression test.
response = self.client.get("/group1/group2/")
self.assertEqual(response.status_code, 200)
response = self.client.get("/nonexistent/")
self.assertEqual(response.status_code, 404)
@override_settings(
USE_I18N=True,
LANGUAGES=[
("bg", "Bulgarian"),
("en-us", "English"),
("pt-br", "Portuguese (Brazil)"),
],
MIDDLEWARE=[
"django.middleware.locale.LocaleMiddleware",
"django.middleware.common.CommonMiddleware",
],
ROOT_URLCONF="i18n.urls",
)
class CountrySpecificLanguageTests(SimpleTestCase):
rf = RequestFactory()
def test_check_for_language(self):
self.assertTrue(check_for_language("en"))
self.assertTrue(check_for_language("en-us"))
self.assertTrue(check_for_language("en-US"))
self.assertFalse(check_for_language("en_US"))
self.assertTrue(check_for_language("be"))
self.assertTrue(check_for_language("be@latin"))
self.assertTrue(check_for_language("sr-RS@latin"))
self.assertTrue(check_for_language("sr-RS@12345"))
self.assertFalse(check_for_language("en-ü"))
self.assertFalse(check_for_language("en\x00"))
self.assertFalse(check_for_language(None))
self.assertFalse(check_for_language("be@ "))
# Specifying encoding is not supported (Django enforces UTF-8)
self.assertFalse(check_for_language("tr-TR.UTF-8"))
self.assertFalse(check_for_language("tr-TR.UTF8"))
self.assertFalse(check_for_language("de-DE.utf-8"))
def test_check_for_language_null(self):
self.assertIs(trans_null.check_for_language("en"), True)
def test_get_language_from_request(self):
# issue 19919
request = self.rf.get(
"/", HTTP_ACCEPT_LANGUAGE="en-US,en;q=0.8,bg;q=0.6,ru;q=0.4"
)
lang = get_language_from_request(request)
self.assertEqual("en-us", lang)
request = self.rf.get(
"/", HTTP_ACCEPT_LANGUAGE="bg-bg,en-US;q=0.8,en;q=0.6,ru;q=0.4"
)
lang = get_language_from_request(request)
self.assertEqual("bg", lang)
def test_get_language_from_request_null(self):
lang = trans_null.get_language_from_request(None)
self.assertEqual(lang, None)
def test_specific_language_codes(self):
# issue 11915
request = self.rf.get(
"/", HTTP_ACCEPT_LANGUAGE="pt,en-US;q=0.8,en;q=0.6,ru;q=0.4"
)
lang = get_language_from_request(request)
self.assertEqual("pt-br", lang)
request = self.rf.get(
"/", HTTP_ACCEPT_LANGUAGE="pt-pt,en-US;q=0.8,en;q=0.6,ru;q=0.4"
)
lang = get_language_from_request(request)
self.assertEqual("pt-br", lang)
class TranslationFilesMissing(SimpleTestCase):
def setUp(self):
super().setUp()
self.gettext_find_builtin = gettext_module.find
def tearDown(self):
gettext_module.find = self.gettext_find_builtin
super().tearDown()
def patchGettextFind(self):
gettext_module.find = lambda *args, **kw: None
def test_failure_finding_default_mo_files(self):
"""OSError is raised if the default language is unparseable."""
self.patchGettextFind()
trans_real._translations = {}
with self.assertRaises(OSError):
activate("en")
class NonDjangoLanguageTests(SimpleTestCase):
"""
A language non present in default Django languages can still be
installed/used by a Django project.
"""
@override_settings(
USE_I18N=True,
LANGUAGES=[
("en-us", "English"),
("xxx", "Somelanguage"),
],
LANGUAGE_CODE="xxx",
LOCALE_PATHS=[os.path.join(here, "commands", "locale")],
)
def test_non_django_language(self):
self.assertEqual(get_language(), "xxx")
self.assertEqual(gettext("year"), "reay")
@override_settings(USE_I18N=True)
def test_check_for_language(self):
with tempfile.TemporaryDirectory() as app_dir:
os.makedirs(os.path.join(app_dir, "locale", "dummy_Lang", "LC_MESSAGES"))
open(
os.path.join(
app_dir, "locale", "dummy_Lang", "LC_MESSAGES", "django.mo"
),
"w",
).close()
app_config = AppConfig("dummy_app", AppModuleStub(__path__=[app_dir]))
with mock.patch(
"django.apps.apps.get_app_configs", return_value=[app_config]
):
self.assertIs(check_for_language("dummy-lang"), True)
@override_settings(
USE_I18N=True,
LANGUAGES=[
("en-us", "English"),
# xyz language has no locale files
("xyz", "XYZ"),
],
)
@translation.override("xyz")
def test_plural_non_django_language(self):
self.assertEqual(get_language(), "xyz")
self.assertEqual(ngettext("year", "years", 2), "years")
@override_settings(USE_I18N=True)
class WatchForTranslationChangesTests(SimpleTestCase):
@override_settings(USE_I18N=False)
def test_i18n_disabled(self):
mocked_sender = mock.MagicMock()
watch_for_translation_changes(mocked_sender)
mocked_sender.watch_dir.assert_not_called()
def test_i18n_enabled(self):
mocked_sender = mock.MagicMock()
watch_for_translation_changes(mocked_sender)
self.assertGreater(mocked_sender.watch_dir.call_count, 1)
def test_i18n_locale_paths(self):
mocked_sender = mock.MagicMock()
with tempfile.TemporaryDirectory() as app_dir:
with self.settings(LOCALE_PATHS=[app_dir]):
watch_for_translation_changes(mocked_sender)
mocked_sender.watch_dir.assert_any_call(Path(app_dir), "**/*.mo")
def test_i18n_app_dirs(self):
mocked_sender = mock.MagicMock()
with self.settings(INSTALLED_APPS=["i18n.sampleproject"]):
watch_for_translation_changes(mocked_sender)
project_dir = Path(__file__).parent / "sampleproject" / "locale"
mocked_sender.watch_dir.assert_any_call(project_dir, "**/*.mo")
def test_i18n_app_dirs_ignore_django_apps(self):
mocked_sender = mock.MagicMock()
with self.settings(INSTALLED_APPS=["django.contrib.admin"]):
watch_for_translation_changes(mocked_sender)
mocked_sender.watch_dir.assert_called_once_with(Path("locale"), "**/*.mo")
def test_i18n_local_locale(self):
mocked_sender = mock.MagicMock()
watch_for_translation_changes(mocked_sender)
locale_dir = Path(__file__).parent / "locale"
mocked_sender.watch_dir.assert_any_call(locale_dir, "**/*.mo")
class TranslationFileChangedTests(SimpleTestCase):
def setUp(self):
self.gettext_translations = gettext_module._translations.copy()
self.trans_real_translations = trans_real._translations.copy()
def tearDown(self):
gettext._translations = self.gettext_translations
trans_real._translations = self.trans_real_translations
def test_ignores_non_mo_files(self):
gettext_module._translations = {"foo": "bar"}
path = Path("test.py")
self.assertIsNone(translation_file_changed(None, path))
self.assertEqual(gettext_module._translations, {"foo": "bar"})
def test_resets_cache_with_mo_files(self):
gettext_module._translations = {"foo": "bar"}
trans_real._translations = {"foo": "bar"}
trans_real._default = 1
trans_real._active = False
path = Path("test.mo")
self.assertIs(translation_file_changed(None, path), True)
self.assertEqual(gettext_module._translations, {})
self.assertEqual(trans_real._translations, {})
self.assertIsNone(trans_real._default)
self.assertIsInstance(trans_real._active, Local)
class UtilsTests(SimpleTestCase):
def test_round_away_from_one(self):
tests = [
(0, 0),
(0.0, 0),
(0.25, 0),
(0.5, 0),
(0.75, 0),
(1, 1),
(1.0, 1),
(1.25, 2),
(1.5, 2),
(1.75, 2),
(-0.0, 0),
(-0.25, -1),
(-0.5, -1),
(-0.75, -1),
(-1, -1),
(-1.0, -1),
(-1.25, -2),
(-1.5, -2),
(-1.75, -2),
]
for value, expected in tests:
with self.subTest(value=value):
self.assertEqual(round_away_from_one(value), expected)
|
de255e79b9033021746d6b4e6a1b4d21aba4533a1f7fdf2c04e6f825635801ce | from operator import attrgetter
from django.contrib.contenttypes.models import ContentType
from django.contrib.sessions.backends.db import SessionStore
from django.db import models
from django.db.models import Count
from django.test import TestCase, ignore_warnings, override_settings
from django.utils.deprecation import RemovedInDjango50Warning
from .models import (
Base,
Child,
Derived,
Feature,
Item,
ItemAndSimpleItem,
Leaf,
Location,
OneToOneItem,
Proxy,
ProxyRelated,
RelatedItem,
Request,
ResolveThis,
SimpleItem,
SpecialFeature,
)
class DeferRegressionTest(TestCase):
def test_basic(self):
# Deferred fields should really be deferred and not accidentally use
# the field's default value just because they aren't passed to __init__
Item.objects.create(name="first", value=42)
obj = Item.objects.only("name", "other_value").get(name="first")
# Accessing "name" doesn't trigger a new database query. Accessing
# "value" or "text" should.
with self.assertNumQueries(0):
self.assertEqual(obj.name, "first")
self.assertEqual(obj.other_value, 0)
with self.assertNumQueries(1):
self.assertEqual(obj.value, 42)
with self.assertNumQueries(1):
self.assertEqual(obj.text, "xyzzy")
with self.assertNumQueries(0):
self.assertEqual(obj.text, "xyzzy")
# Regression test for #10695. Make sure different instances don't
# inadvertently share data in the deferred descriptor objects.
i = Item.objects.create(name="no I'm first", value=37)
items = Item.objects.only("value").order_by("-value")
self.assertEqual(items[0].name, "first")
self.assertEqual(items[1].name, "no I'm first")
RelatedItem.objects.create(item=i)
r = RelatedItem.objects.defer("item").get()
self.assertEqual(r.item_id, i.id)
self.assertEqual(r.item, i)
# Some further checks for select_related() and inherited model
# behavior (regression for #10710).
c1 = Child.objects.create(name="c1", value=42)
c2 = Child.objects.create(name="c2", value=37)
Leaf.objects.create(name="l1", child=c1, second_child=c2)
obj = Leaf.objects.only("name", "child").select_related()[0]
self.assertEqual(obj.child.name, "c1")
self.assertQuerySetEqual(
Leaf.objects.select_related().only("child__name", "second_child__name"),
[
"l1",
],
attrgetter("name"),
)
# Models instances with deferred fields should still return the same
# content types as their non-deferred versions (bug #10738).
ctype = ContentType.objects.get_for_model
c1 = ctype(Item.objects.all()[0])
c2 = ctype(Item.objects.defer("name")[0])
c3 = ctype(Item.objects.only("name")[0])
self.assertTrue(c1 is c2 is c3)
# Regression for #10733 - only() can be used on a model with two
# foreign keys.
results = Leaf.objects.only("name", "child", "second_child").select_related()
self.assertEqual(results[0].child.name, "c1")
self.assertEqual(results[0].second_child.name, "c2")
results = Leaf.objects.only(
"name", "child", "second_child", "child__name", "second_child__name"
).select_related()
self.assertEqual(results[0].child.name, "c1")
self.assertEqual(results[0].second_child.name, "c2")
# Regression for #16409 - make sure defer() and only() work with annotate()
self.assertIsInstance(
list(SimpleItem.objects.annotate(Count("feature")).defer("name")), list
)
self.assertIsInstance(
list(SimpleItem.objects.annotate(Count("feature")).only("name")), list
)
@ignore_warnings(category=RemovedInDjango50Warning)
@override_settings(
SESSION_SERIALIZER="django.contrib.sessions.serializers.PickleSerializer"
)
def test_ticket_12163(self):
# Test for #12163 - Pickling error saving session with unsaved model
# instances.
SESSION_KEY = "2b1189a188b44ad18c35e1baac6ceead"
item = Item()
item._deferred = False
s = SessionStore(SESSION_KEY)
s.clear()
s["item"] = item
s.save(must_create=True)
s = SessionStore(SESSION_KEY)
s.modified = True
s.save()
i2 = s["item"]
self.assertFalse(i2._deferred)
def test_ticket_16409(self):
# Regression for #16409 - make sure defer() and only() work with annotate()
self.assertIsInstance(
list(SimpleItem.objects.annotate(Count("feature")).defer("name")), list
)
self.assertIsInstance(
list(SimpleItem.objects.annotate(Count("feature")).only("name")), list
)
def test_ticket_23270(self):
d = Derived.objects.create(text="foo", other_text="bar")
with self.assertNumQueries(1):
obj = Base.objects.select_related("derived").defer("text")[0]
self.assertIsInstance(obj.derived, Derived)
self.assertEqual("bar", obj.derived.other_text)
self.assertNotIn("text", obj.__dict__)
self.assertEqual(d.pk, obj.derived.base_ptr_id)
def test_only_and_defer_usage_on_proxy_models(self):
# Regression for #15790 - only() broken for proxy models
proxy = Proxy.objects.create(name="proxy", value=42)
msg = "QuerySet.only() return bogus results with proxy models"
dp = Proxy.objects.only("other_value").get(pk=proxy.pk)
self.assertEqual(dp.name, proxy.name, msg=msg)
self.assertEqual(dp.value, proxy.value, msg=msg)
# also test things with .defer()
msg = "QuerySet.defer() return bogus results with proxy models"
dp = Proxy.objects.defer("name", "text", "value").get(pk=proxy.pk)
self.assertEqual(dp.name, proxy.name, msg=msg)
self.assertEqual(dp.value, proxy.value, msg=msg)
def test_resolve_columns(self):
ResolveThis.objects.create(num=5.0, name="Foobar")
qs = ResolveThis.objects.defer("num")
self.assertEqual(1, qs.count())
self.assertEqual("Foobar", qs[0].name)
def test_reverse_one_to_one_relations(self):
# Refs #14694. Test reverse relations which are known unique (reverse
# side has o2ofield or unique FK) - the o2o case
item = Item.objects.create(name="first", value=42)
o2o = OneToOneItem.objects.create(item=item, name="second")
self.assertEqual(len(Item.objects.defer("one_to_one_item__name")), 1)
self.assertEqual(len(Item.objects.select_related("one_to_one_item")), 1)
self.assertEqual(
len(
Item.objects.select_related("one_to_one_item").defer(
"one_to_one_item__name"
)
),
1,
)
self.assertEqual(
len(Item.objects.select_related("one_to_one_item").defer("value")), 1
)
# Make sure that `only()` doesn't break when we pass in a unique relation,
# rather than a field on the relation.
self.assertEqual(len(Item.objects.only("one_to_one_item")), 1)
with self.assertNumQueries(1):
i = Item.objects.select_related("one_to_one_item")[0]
self.assertEqual(i.one_to_one_item.pk, o2o.pk)
self.assertEqual(i.one_to_one_item.name, "second")
with self.assertNumQueries(1):
i = Item.objects.select_related("one_to_one_item").defer(
"value", "one_to_one_item__name"
)[0]
self.assertEqual(i.one_to_one_item.pk, o2o.pk)
self.assertEqual(i.name, "first")
with self.assertNumQueries(1):
self.assertEqual(i.one_to_one_item.name, "second")
with self.assertNumQueries(1):
self.assertEqual(i.value, 42)
def test_defer_with_select_related(self):
item1 = Item.objects.create(name="first", value=47)
item2 = Item.objects.create(name="second", value=42)
simple = SimpleItem.objects.create(name="simple", value="23")
ItemAndSimpleItem.objects.create(item=item1, simple=simple)
obj = ItemAndSimpleItem.objects.defer("item").select_related("simple").get()
self.assertEqual(obj.item, item1)
self.assertEqual(obj.item_id, item1.id)
obj.item = item2
obj.save()
obj = ItemAndSimpleItem.objects.defer("item").select_related("simple").get()
self.assertEqual(obj.item, item2)
self.assertEqual(obj.item_id, item2.id)
def test_proxy_model_defer_with_select_related(self):
# Regression for #22050
item = Item.objects.create(name="first", value=47)
RelatedItem.objects.create(item=item)
# Defer fields with only()
obj = ProxyRelated.objects.select_related().only("item__name")[0]
with self.assertNumQueries(0):
self.assertEqual(obj.item.name, "first")
with self.assertNumQueries(1):
self.assertEqual(obj.item.value, 47)
def test_only_with_select_related(self):
# Test for #17485.
item = SimpleItem.objects.create(name="first", value=47)
feature = Feature.objects.create(item=item)
SpecialFeature.objects.create(feature=feature)
qs = Feature.objects.only("item__name").select_related("item")
self.assertEqual(len(qs), 1)
qs = SpecialFeature.objects.only("feature__item__name").select_related(
"feature__item"
)
self.assertEqual(len(qs), 1)
def test_defer_annotate_select_related(self):
location = Location.objects.create()
Request.objects.create(location=location)
self.assertIsInstance(
list(
Request.objects.annotate(Count("items"))
.select_related("profile", "location")
.only("profile", "location")
),
list,
)
self.assertIsInstance(
list(
Request.objects.annotate(Count("items"))
.select_related("profile", "location")
.only("profile__profile1", "location__location1")
),
list,
)
self.assertIsInstance(
list(
Request.objects.annotate(Count("items"))
.select_related("profile", "location")
.defer("request1", "request2", "request3", "request4")
),
list,
)
def test_common_model_different_mask(self):
child = Child.objects.create(name="Child", value=42)
second_child = Child.objects.create(name="Second", value=64)
Leaf.objects.create(child=child, second_child=second_child)
with self.assertNumQueries(1):
leaf = (
Leaf.objects.select_related("child", "second_child")
.defer("child__name", "second_child__value")
.get()
)
self.assertEqual(leaf.child, child)
self.assertEqual(leaf.second_child, second_child)
self.assertEqual(leaf.child.get_deferred_fields(), {"name"})
self.assertEqual(leaf.second_child.get_deferred_fields(), {"value"})
with self.assertNumQueries(0):
self.assertEqual(leaf.child.value, 42)
self.assertEqual(leaf.second_child.name, "Second")
with self.assertNumQueries(1):
self.assertEqual(leaf.child.name, "Child")
with self.assertNumQueries(1):
self.assertEqual(leaf.second_child.value, 64)
class DeferDeletionSignalsTests(TestCase):
senders = [Item, Proxy]
@classmethod
def setUpTestData(cls):
cls.item_pk = Item.objects.create(value=1).pk
def setUp(self):
self.pre_delete_senders = []
self.post_delete_senders = []
for sender in self.senders:
models.signals.pre_delete.connect(self.pre_delete_receiver, sender)
models.signals.post_delete.connect(self.post_delete_receiver, sender)
def tearDown(self):
for sender in self.senders:
models.signals.pre_delete.disconnect(self.pre_delete_receiver, sender)
models.signals.post_delete.disconnect(self.post_delete_receiver, sender)
def pre_delete_receiver(self, sender, **kwargs):
self.pre_delete_senders.append(sender)
def post_delete_receiver(self, sender, **kwargs):
self.post_delete_senders.append(sender)
def test_delete_defered_model(self):
Item.objects.only("value").get(pk=self.item_pk).delete()
self.assertEqual(self.pre_delete_senders, [Item])
self.assertEqual(self.post_delete_senders, [Item])
def test_delete_defered_proxy_model(self):
Proxy.objects.only("value").get(pk=self.item_pk).delete()
self.assertEqual(self.pre_delete_senders, [Proxy])
self.assertEqual(self.post_delete_senders, [Proxy])
|
01500f015134b8bf622f661bcda0f0e8b951493c0b2a155023494f03077da436 | import time
import unittest
from datetime import date, datetime
from django.core.exceptions import FieldError
from django.db import connection, models
from django.db.models.fields.related_lookups import RelatedGreaterThan
from django.db.models.lookups import EndsWith, StartsWith
from django.test import SimpleTestCase, TestCase, override_settings
from django.test.utils import register_lookup
from django.utils import timezone
from .models import Article, Author, MySQLUnixTimestamp
class Div3Lookup(models.Lookup):
lookup_name = "div3"
def as_sql(self, compiler, connection):
lhs, params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
params.extend(rhs_params)
return "(%s) %%%% 3 = %s" % (lhs, rhs), params
def as_oracle(self, compiler, connection):
lhs, params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
params.extend(rhs_params)
return "mod(%s, 3) = %s" % (lhs, rhs), params
class Div3Transform(models.Transform):
lookup_name = "div3"
def as_sql(self, compiler, connection):
lhs, lhs_params = compiler.compile(self.lhs)
return "(%s) %%%% 3" % lhs, lhs_params
def as_oracle(self, compiler, connection, **extra_context):
lhs, lhs_params = compiler.compile(self.lhs)
return "mod(%s, 3)" % lhs, lhs_params
class Div3BilateralTransform(Div3Transform):
bilateral = True
class Mult3BilateralTransform(models.Transform):
bilateral = True
lookup_name = "mult3"
def as_sql(self, compiler, connection):
lhs, lhs_params = compiler.compile(self.lhs)
return "3 * (%s)" % lhs, lhs_params
class LastDigitTransform(models.Transform):
lookup_name = "lastdigit"
def as_sql(self, compiler, connection):
lhs, lhs_params = compiler.compile(self.lhs)
return "SUBSTR(CAST(%s AS CHAR(2)), 2, 1)" % lhs, lhs_params
class UpperBilateralTransform(models.Transform):
bilateral = True
lookup_name = "upper"
def as_sql(self, compiler, connection):
lhs, lhs_params = compiler.compile(self.lhs)
return "UPPER(%s)" % lhs, lhs_params
class YearTransform(models.Transform):
# Use a name that avoids collision with the built-in year lookup.
lookup_name = "testyear"
def as_sql(self, compiler, connection):
lhs_sql, params = compiler.compile(self.lhs)
return connection.ops.date_extract_sql("year", lhs_sql, params)
@property
def output_field(self):
return models.IntegerField()
@YearTransform.register_lookup
class YearExact(models.lookups.Lookup):
lookup_name = "exact"
def as_sql(self, compiler, connection):
# We will need to skip the extract part, and instead go
# directly with the originating field, that is self.lhs.lhs
lhs_sql, lhs_params = self.process_lhs(compiler, connection, self.lhs.lhs)
rhs_sql, rhs_params = self.process_rhs(compiler, connection)
# Note that we must be careful so that we have params in the
# same order as we have the parts in the SQL.
params = lhs_params + rhs_params + lhs_params + rhs_params
# We use PostgreSQL specific SQL here. Note that we must do the
# conversions in SQL instead of in Python to support F() references.
return (
"%(lhs)s >= (%(rhs)s || '-01-01')::date "
"AND %(lhs)s <= (%(rhs)s || '-12-31')::date"
% {"lhs": lhs_sql, "rhs": rhs_sql},
params,
)
@YearTransform.register_lookup
class YearLte(models.lookups.LessThanOrEqual):
"""
The purpose of this lookup is to efficiently compare the year of the field.
"""
def as_sql(self, compiler, connection):
# Skip the YearTransform above us (no possibility for efficient
# lookup otherwise).
real_lhs = self.lhs.lhs
lhs_sql, params = self.process_lhs(compiler, connection, real_lhs)
rhs_sql, rhs_params = self.process_rhs(compiler, connection)
params.extend(rhs_params)
# Build SQL where the integer year is concatenated with last month
# and day, then convert that to date. (We try to have SQL like:
# WHERE somecol <= '2013-12-31')
# but also make it work if the rhs_sql is field reference.
return "%s <= (%s || '-12-31')::date" % (lhs_sql, rhs_sql), params
class Exactly(models.lookups.Exact):
"""
This lookup is used to test lookup registration.
"""
lookup_name = "exactly"
def get_rhs_op(self, connection, rhs):
return connection.operators["exact"] % rhs
class SQLFuncMixin:
def as_sql(self, compiler, connection):
return "%s()" % self.name, []
@property
def output_field(self):
return CustomField()
class SQLFuncLookup(SQLFuncMixin, models.Lookup):
def __init__(self, name, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = name
class SQLFuncTransform(SQLFuncMixin, models.Transform):
def __init__(self, name, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = name
class SQLFuncFactory:
def __init__(self, key, name):
self.key = key
self.name = name
def __call__(self, *args, **kwargs):
if self.key == "lookupfunc":
return SQLFuncLookup(self.name, *args, **kwargs)
return SQLFuncTransform(self.name, *args, **kwargs)
class CustomField(models.TextField):
def get_lookup(self, lookup_name):
if lookup_name.startswith("lookupfunc_"):
key, name = lookup_name.split("_", 1)
return SQLFuncFactory(key, name)
return super().get_lookup(lookup_name)
def get_transform(self, lookup_name):
if lookup_name.startswith("transformfunc_"):
key, name = lookup_name.split("_", 1)
return SQLFuncFactory(key, name)
return super().get_transform(lookup_name)
class CustomModel(models.Model):
field = CustomField()
# We will register this class temporarily in the test method.
class InMonth(models.lookups.Lookup):
"""
InMonth matches if the column's month is the same as value's month.
"""
lookup_name = "inmonth"
def as_sql(self, compiler, connection):
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
# We need to be careful so that we get the params in right
# places.
params = lhs_params + rhs_params + lhs_params + rhs_params
return (
"%s >= date_trunc('month', %s) and "
"%s < date_trunc('month', %s) + interval '1 months'" % (lhs, rhs, lhs, rhs),
params,
)
class DateTimeTransform(models.Transform):
lookup_name = "as_datetime"
@property
def output_field(self):
return models.DateTimeField()
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
return "from_unixtime({})".format(lhs), params
class CustomStartsWith(StartsWith):
lookup_name = "sw"
class CustomEndsWith(EndsWith):
lookup_name = "ew"
class RelatedMoreThan(RelatedGreaterThan):
lookup_name = "rmt"
class LookupTests(TestCase):
def test_custom_name_lookup(self):
a1 = Author.objects.create(name="a1", birthdate=date(1981, 2, 16))
Author.objects.create(name="a2", birthdate=date(2012, 2, 29))
with register_lookup(models.DateField, YearTransform), register_lookup(
models.DateField, YearTransform, lookup_name="justtheyear"
), register_lookup(YearTransform, Exactly), register_lookup(
YearTransform, Exactly, lookup_name="isactually"
):
qs1 = Author.objects.filter(birthdate__testyear__exactly=1981)
qs2 = Author.objects.filter(birthdate__justtheyear__isactually=1981)
self.assertSequenceEqual(qs1, [a1])
self.assertSequenceEqual(qs2, [a1])
def test_custom_exact_lookup_none_rhs(self):
"""
__exact=None is transformed to __isnull=True if a custom lookup class
with lookup_name != 'exact' is registered as the `exact` lookup.
"""
field = Author._meta.get_field("birthdate")
OldExactLookup = field.get_lookup("exact")
author = Author.objects.create(name="author", birthdate=None)
try:
field.register_lookup(Exactly, "exact")
self.assertEqual(Author.objects.get(birthdate__exact=None), author)
finally:
field.register_lookup(OldExactLookup, "exact")
def test_basic_lookup(self):
a1 = Author.objects.create(name="a1", age=1)
a2 = Author.objects.create(name="a2", age=2)
a3 = Author.objects.create(name="a3", age=3)
a4 = Author.objects.create(name="a4", age=4)
with register_lookup(models.IntegerField, Div3Lookup):
self.assertSequenceEqual(Author.objects.filter(age__div3=0), [a3])
self.assertSequenceEqual(
Author.objects.filter(age__div3=1).order_by("age"), [a1, a4]
)
self.assertSequenceEqual(Author.objects.filter(age__div3=2), [a2])
self.assertSequenceEqual(Author.objects.filter(age__div3=3), [])
@unittest.skipUnless(
connection.vendor == "postgresql", "PostgreSQL specific SQL used"
)
def test_birthdate_month(self):
a1 = Author.objects.create(name="a1", birthdate=date(1981, 2, 16))
a2 = Author.objects.create(name="a2", birthdate=date(2012, 2, 29))
a3 = Author.objects.create(name="a3", birthdate=date(2012, 1, 31))
a4 = Author.objects.create(name="a4", birthdate=date(2012, 3, 1))
with register_lookup(models.DateField, InMonth):
self.assertSequenceEqual(
Author.objects.filter(birthdate__inmonth=date(2012, 1, 15)), [a3]
)
self.assertSequenceEqual(
Author.objects.filter(birthdate__inmonth=date(2012, 2, 1)), [a2]
)
self.assertSequenceEqual(
Author.objects.filter(birthdate__inmonth=date(1981, 2, 28)), [a1]
)
self.assertSequenceEqual(
Author.objects.filter(birthdate__inmonth=date(2012, 3, 12)), [a4]
)
self.assertSequenceEqual(
Author.objects.filter(birthdate__inmonth=date(2012, 4, 1)), []
)
def test_div3_extract(self):
with register_lookup(models.IntegerField, Div3Transform):
a1 = Author.objects.create(name="a1", age=1)
a2 = Author.objects.create(name="a2", age=2)
a3 = Author.objects.create(name="a3", age=3)
a4 = Author.objects.create(name="a4", age=4)
baseqs = Author.objects.order_by("name")
self.assertSequenceEqual(baseqs.filter(age__div3=2), [a2])
self.assertSequenceEqual(baseqs.filter(age__div3__lte=3), [a1, a2, a3, a4])
self.assertSequenceEqual(baseqs.filter(age__div3__in=[0, 2]), [a2, a3])
self.assertSequenceEqual(baseqs.filter(age__div3__in=[2, 4]), [a2])
self.assertSequenceEqual(baseqs.filter(age__div3__gte=3), [])
self.assertSequenceEqual(
baseqs.filter(age__div3__range=(1, 2)), [a1, a2, a4]
)
def test_foreignobject_lookup_registration(self):
field = Article._meta.get_field("author")
with register_lookup(models.ForeignObject, Exactly):
self.assertIs(field.get_lookup("exactly"), Exactly)
# ForeignObject should ignore regular Field lookups
with register_lookup(models.Field, Exactly):
self.assertIsNone(field.get_lookup("exactly"))
def test_lookups_caching(self):
field = Article._meta.get_field("author")
# clear and re-cache
field.get_class_lookups.cache_clear()
self.assertNotIn("exactly", field.get_lookups())
# registration should bust the cache
with register_lookup(models.ForeignObject, Exactly):
# getting the lookups again should re-cache
self.assertIn("exactly", field.get_lookups())
# Unregistration should bust the cache.
self.assertNotIn("exactly", field.get_lookups())
class BilateralTransformTests(TestCase):
def test_bilateral_upper(self):
with register_lookup(models.CharField, UpperBilateralTransform):
author1 = Author.objects.create(name="Doe")
author2 = Author.objects.create(name="doe")
author3 = Author.objects.create(name="Foo")
self.assertCountEqual(
Author.objects.filter(name__upper="doe"),
[author1, author2],
)
self.assertSequenceEqual(
Author.objects.filter(name__upper__contains="f"),
[author3],
)
def test_bilateral_inner_qs(self):
with register_lookup(models.CharField, UpperBilateralTransform):
msg = "Bilateral transformations on nested querysets are not implemented."
with self.assertRaisesMessage(NotImplementedError, msg):
Author.objects.filter(
name__upper__in=Author.objects.values_list("name")
)
def test_bilateral_multi_value(self):
with register_lookup(models.CharField, UpperBilateralTransform):
Author.objects.bulk_create(
[
Author(name="Foo"),
Author(name="Bar"),
Author(name="Ray"),
]
)
self.assertQuerySetEqual(
Author.objects.filter(name__upper__in=["foo", "bar", "doe"]).order_by(
"name"
),
["Bar", "Foo"],
lambda a: a.name,
)
def test_div3_bilateral_extract(self):
with register_lookup(models.IntegerField, Div3BilateralTransform):
a1 = Author.objects.create(name="a1", age=1)
a2 = Author.objects.create(name="a2", age=2)
a3 = Author.objects.create(name="a3", age=3)
a4 = Author.objects.create(name="a4", age=4)
baseqs = Author.objects.order_by("name")
self.assertSequenceEqual(baseqs.filter(age__div3=2), [a2])
self.assertSequenceEqual(baseqs.filter(age__div3__lte=3), [a3])
self.assertSequenceEqual(baseqs.filter(age__div3__in=[0, 2]), [a2, a3])
self.assertSequenceEqual(baseqs.filter(age__div3__in=[2, 4]), [a1, a2, a4])
self.assertSequenceEqual(baseqs.filter(age__div3__gte=3), [a1, a2, a3, a4])
self.assertSequenceEqual(
baseqs.filter(age__div3__range=(1, 2)), [a1, a2, a4]
)
def test_bilateral_order(self):
with register_lookup(
models.IntegerField, Mult3BilateralTransform, Div3BilateralTransform
):
a1 = Author.objects.create(name="a1", age=1)
a2 = Author.objects.create(name="a2", age=2)
a3 = Author.objects.create(name="a3", age=3)
a4 = Author.objects.create(name="a4", age=4)
baseqs = Author.objects.order_by("name")
# mult3__div3 always leads to 0
self.assertSequenceEqual(
baseqs.filter(age__mult3__div3=42), [a1, a2, a3, a4]
)
self.assertSequenceEqual(baseqs.filter(age__div3__mult3=42), [a3])
def test_transform_order_by(self):
with register_lookup(models.IntegerField, LastDigitTransform):
a1 = Author.objects.create(name="a1", age=11)
a2 = Author.objects.create(name="a2", age=23)
a3 = Author.objects.create(name="a3", age=32)
a4 = Author.objects.create(name="a4", age=40)
qs = Author.objects.order_by("age__lastdigit")
self.assertSequenceEqual(qs, [a4, a1, a3, a2])
def test_bilateral_fexpr(self):
with register_lookup(models.IntegerField, Mult3BilateralTransform):
a1 = Author.objects.create(name="a1", age=1, average_rating=3.2)
a2 = Author.objects.create(name="a2", age=2, average_rating=0.5)
a3 = Author.objects.create(name="a3", age=3, average_rating=1.5)
a4 = Author.objects.create(name="a4", age=4)
baseqs = Author.objects.order_by("name")
self.assertSequenceEqual(
baseqs.filter(age__mult3=models.F("age")), [a1, a2, a3, a4]
)
# Same as age >= average_rating
self.assertSequenceEqual(
baseqs.filter(age__mult3__gte=models.F("average_rating")), [a2, a3]
)
@override_settings(USE_TZ=True)
class DateTimeLookupTests(TestCase):
@unittest.skipUnless(connection.vendor == "mysql", "MySQL specific SQL used")
def test_datetime_output_field(self):
with register_lookup(models.PositiveIntegerField, DateTimeTransform):
ut = MySQLUnixTimestamp.objects.create(timestamp=time.time())
y2k = timezone.make_aware(datetime(2000, 1, 1))
self.assertSequenceEqual(
MySQLUnixTimestamp.objects.filter(timestamp__as_datetime__gt=y2k), [ut]
)
class YearLteTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.a1 = Author.objects.create(name="a1", birthdate=date(1981, 2, 16))
cls.a2 = Author.objects.create(name="a2", birthdate=date(2012, 2, 29))
cls.a3 = Author.objects.create(name="a3", birthdate=date(2012, 1, 31))
cls.a4 = Author.objects.create(name="a4", birthdate=date(2012, 3, 1))
def setUp(self):
models.DateField.register_lookup(YearTransform)
def tearDown(self):
models.DateField._unregister_lookup(YearTransform)
@unittest.skipUnless(
connection.vendor == "postgresql", "PostgreSQL specific SQL used"
)
def test_year_lte(self):
baseqs = Author.objects.order_by("name")
self.assertSequenceEqual(
baseqs.filter(birthdate__testyear__lte=2012),
[self.a1, self.a2, self.a3, self.a4],
)
self.assertSequenceEqual(
baseqs.filter(birthdate__testyear=2012), [self.a2, self.a3, self.a4]
)
self.assertNotIn("BETWEEN", str(baseqs.filter(birthdate__testyear=2012).query))
self.assertSequenceEqual(
baseqs.filter(birthdate__testyear__lte=2011), [self.a1]
)
# The non-optimized version works, too.
self.assertSequenceEqual(baseqs.filter(birthdate__testyear__lt=2012), [self.a1])
@unittest.skipUnless(
connection.vendor == "postgresql", "PostgreSQL specific SQL used"
)
def test_year_lte_fexpr(self):
self.a2.age = 2011
self.a2.save()
self.a3.age = 2012
self.a3.save()
self.a4.age = 2013
self.a4.save()
baseqs = Author.objects.order_by("name")
self.assertSequenceEqual(
baseqs.filter(birthdate__testyear__lte=models.F("age")), [self.a3, self.a4]
)
self.assertSequenceEqual(
baseqs.filter(birthdate__testyear__lt=models.F("age")), [self.a4]
)
def test_year_lte_sql(self):
# This test will just check the generated SQL for __lte. This
# doesn't require running on PostgreSQL and spots the most likely
# error - not running YearLte SQL at all.
baseqs = Author.objects.order_by("name")
self.assertIn(
"<= (2011 || ", str(baseqs.filter(birthdate__testyear__lte=2011).query)
)
self.assertIn("-12-31", str(baseqs.filter(birthdate__testyear__lte=2011).query))
def test_postgres_year_exact(self):
baseqs = Author.objects.order_by("name")
self.assertIn("= (2011 || ", str(baseqs.filter(birthdate__testyear=2011).query))
self.assertIn("-12-31", str(baseqs.filter(birthdate__testyear=2011).query))
def test_custom_implementation_year_exact(self):
try:
# Two ways to add a customized implementation for different backends:
# First is MonkeyPatch of the class.
def as_custom_sql(self, compiler, connection):
lhs_sql, lhs_params = self.process_lhs(
compiler, connection, self.lhs.lhs
)
rhs_sql, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + rhs_params + lhs_params + rhs_params
return (
"%(lhs)s >= "
"str_to_date(concat(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') "
"AND %(lhs)s <= "
"str_to_date(concat(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')"
% {"lhs": lhs_sql, "rhs": rhs_sql},
params,
)
setattr(YearExact, "as_" + connection.vendor, as_custom_sql)
self.assertIn(
"concat(", str(Author.objects.filter(birthdate__testyear=2012).query)
)
finally:
delattr(YearExact, "as_" + connection.vendor)
try:
# The other way is to subclass the original lookup and register the
# subclassed lookup instead of the original.
class CustomYearExact(YearExact):
# This method should be named "as_mysql" for MySQL,
# "as_postgresql" for postgres and so on, but as we don't know
# which DB we are running on, we need to use setattr.
def as_custom_sql(self, compiler, connection):
lhs_sql, lhs_params = self.process_lhs(
compiler, connection, self.lhs.lhs
)
rhs_sql, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + rhs_params + lhs_params + rhs_params
return (
"%(lhs)s >= "
"str_to_date(CONCAT(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') "
"AND %(lhs)s <= "
"str_to_date(CONCAT(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')"
% {"lhs": lhs_sql, "rhs": rhs_sql},
params,
)
setattr(
CustomYearExact,
"as_" + connection.vendor,
CustomYearExact.as_custom_sql,
)
YearTransform.register_lookup(CustomYearExact)
self.assertIn(
"CONCAT(", str(Author.objects.filter(birthdate__testyear=2012).query)
)
finally:
YearTransform._unregister_lookup(CustomYearExact)
YearTransform.register_lookup(YearExact)
class TrackCallsYearTransform(YearTransform):
# Use a name that avoids collision with the built-in year lookup.
lookup_name = "testyear"
call_order = []
def as_sql(self, compiler, connection):
lhs_sql, params = compiler.compile(self.lhs)
return connection.ops.date_extract_sql("year", lhs_sql), params
@property
def output_field(self):
return models.IntegerField()
def get_lookup(self, lookup_name):
self.call_order.append("lookup")
return super().get_lookup(lookup_name)
def get_transform(self, lookup_name):
self.call_order.append("transform")
return super().get_transform(lookup_name)
class LookupTransformCallOrderTests(SimpleTestCase):
def test_call_order(self):
with register_lookup(models.DateField, TrackCallsYearTransform):
# junk lookup - tries lookup, then transform, then fails
msg = (
"Unsupported lookup 'junk' for IntegerField or join on the field not "
"permitted."
)
with self.assertRaisesMessage(FieldError, msg):
Author.objects.filter(birthdate__testyear__junk=2012)
self.assertEqual(
TrackCallsYearTransform.call_order, ["lookup", "transform"]
)
TrackCallsYearTransform.call_order = []
# junk transform - tries transform only, then fails
with self.assertRaisesMessage(FieldError, msg):
Author.objects.filter(birthdate__testyear__junk__more_junk=2012)
self.assertEqual(TrackCallsYearTransform.call_order, ["transform"])
TrackCallsYearTransform.call_order = []
# Just getting the year (implied __exact) - lookup only
Author.objects.filter(birthdate__testyear=2012)
self.assertEqual(TrackCallsYearTransform.call_order, ["lookup"])
TrackCallsYearTransform.call_order = []
# Just getting the year (explicit __exact) - lookup only
Author.objects.filter(birthdate__testyear__exact=2012)
self.assertEqual(TrackCallsYearTransform.call_order, ["lookup"])
class CustomisedMethodsTests(SimpleTestCase):
def test_overridden_get_lookup(self):
q = CustomModel.objects.filter(field__lookupfunc_monkeys=3)
self.assertIn("monkeys()", str(q.query))
def test_overridden_get_transform(self):
q = CustomModel.objects.filter(field__transformfunc_banana=3)
self.assertIn("banana()", str(q.query))
def test_overridden_get_lookup_chain(self):
q = CustomModel.objects.filter(
field__transformfunc_banana__lookupfunc_elephants=3
)
self.assertIn("elephants()", str(q.query))
def test_overridden_get_transform_chain(self):
q = CustomModel.objects.filter(
field__transformfunc_banana__transformfunc_pear=3
)
self.assertIn("pear()", str(q.query))
class SubqueryTransformTests(TestCase):
def test_subquery_usage(self):
with register_lookup(models.IntegerField, Div3Transform):
Author.objects.create(name="a1", age=1)
a2 = Author.objects.create(name="a2", age=2)
Author.objects.create(name="a3", age=3)
Author.objects.create(name="a4", age=4)
qs = Author.objects.order_by("name").filter(
id__in=Author.objects.filter(age__div3=2)
)
self.assertSequenceEqual(qs, [a2])
class RegisterLookupTests(SimpleTestCase):
def test_class_lookup(self):
author_name = Author._meta.get_field("name")
with register_lookup(models.CharField, CustomStartsWith):
self.assertEqual(author_name.get_lookup("sw"), CustomStartsWith)
self.assertIsNone(author_name.get_lookup("sw"))
def test_instance_lookup(self):
author_name = Author._meta.get_field("name")
author_alias = Author._meta.get_field("alias")
with register_lookup(author_name, CustomStartsWith):
self.assertEqual(author_name.instance_lookups, {"sw": CustomStartsWith})
self.assertEqual(author_name.get_lookup("sw"), CustomStartsWith)
self.assertIsNone(author_alias.get_lookup("sw"))
self.assertIsNone(author_name.get_lookup("sw"))
self.assertEqual(author_name.instance_lookups, {})
self.assertIsNone(author_alias.get_lookup("sw"))
def test_instance_lookup_override_class_lookups(self):
author_name = Author._meta.get_field("name")
author_alias = Author._meta.get_field("alias")
with register_lookup(models.CharField, CustomStartsWith, lookup_name="st_end"):
with register_lookup(author_alias, CustomEndsWith, lookup_name="st_end"):
self.assertEqual(author_name.get_lookup("st_end"), CustomStartsWith)
self.assertEqual(author_alias.get_lookup("st_end"), CustomEndsWith)
self.assertEqual(author_name.get_lookup("st_end"), CustomStartsWith)
self.assertEqual(author_alias.get_lookup("st_end"), CustomStartsWith)
self.assertIsNone(author_name.get_lookup("st_end"))
self.assertIsNone(author_alias.get_lookup("st_end"))
def test_instance_lookup_override(self):
author_name = Author._meta.get_field("name")
with register_lookup(author_name, CustomStartsWith, lookup_name="st_end"):
self.assertEqual(author_name.get_lookup("st_end"), CustomStartsWith)
author_name.register_lookup(CustomEndsWith, lookup_name="st_end")
self.assertEqual(author_name.get_lookup("st_end"), CustomEndsWith)
self.assertIsNone(author_name.get_lookup("st_end"))
def test_lookup_on_transform(self):
transform = Div3Transform
with register_lookup(Div3Transform, CustomStartsWith):
with register_lookup(Div3Transform, CustomEndsWith):
self.assertEqual(
transform.get_lookups(),
{"sw": CustomStartsWith, "ew": CustomEndsWith},
)
self.assertEqual(transform.get_lookups(), {"sw": CustomStartsWith})
self.assertEqual(transform.get_lookups(), {})
def test_transform_on_field(self):
author_name = Author._meta.get_field("name")
author_alias = Author._meta.get_field("alias")
with register_lookup(models.CharField, Div3Transform):
self.assertEqual(author_alias.get_transform("div3"), Div3Transform)
self.assertEqual(author_name.get_transform("div3"), Div3Transform)
with register_lookup(author_alias, Div3Transform):
self.assertEqual(author_alias.get_transform("div3"), Div3Transform)
self.assertIsNone(author_name.get_transform("div3"))
self.assertIsNone(author_alias.get_transform("div3"))
self.assertIsNone(author_name.get_transform("div3"))
def test_related_lookup(self):
article_author = Article._meta.get_field("author")
with register_lookup(models.Field, CustomStartsWith):
self.assertIsNone(article_author.get_lookup("sw"))
with register_lookup(models.ForeignKey, RelatedMoreThan):
self.assertEqual(article_author.get_lookup("rmt"), RelatedMoreThan)
def test_instance_related_lookup(self):
article_author = Article._meta.get_field("author")
with register_lookup(article_author, RelatedMoreThan):
self.assertEqual(article_author.get_lookup("rmt"), RelatedMoreThan)
self.assertIsNone(article_author.get_lookup("rmt"))
|
d8d03ade1a290e735fc966e66bdef5e22b6de76472894c30a92b9f33ed35d8aa | from django.db import models
class Author(models.Model):
name = models.CharField(max_length=20)
alias = models.CharField(max_length=20)
age = models.IntegerField(null=True)
birthdate = models.DateField(null=True)
average_rating = models.FloatField(null=True)
def __str__(self):
return self.name
class Article(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
class MySQLUnixTimestamp(models.Model):
timestamp = models.PositiveIntegerField()
|
27da3e217b1409dcf93f1ef4adc65a57b1a311ac8b7190a20039530075828e02 | import collections.abc
from datetime import datetime
from math import ceil
from operator import attrgetter
from unittest import skipUnless
from django.core.exceptions import FieldError
from django.db import connection, models
from django.db.models import (
BooleanField,
Case,
Exists,
ExpressionWrapper,
F,
Max,
OuterRef,
Q,
Subquery,
Value,
When,
)
from django.db.models.functions import Cast, Substr
from django.db.models.lookups import (
Exact,
GreaterThan,
GreaterThanOrEqual,
IsNull,
LessThan,
LessThanOrEqual,
)
from django.test import TestCase, skipUnlessDBFeature
from django.test.utils import isolate_apps
from .models import (
Article,
Author,
Freebie,
Game,
IsNullWithNoneAsRHS,
Player,
Product,
Season,
Stock,
Tag,
)
class LookupTests(TestCase):
@classmethod
def setUpTestData(cls):
# Create a few Authors.
cls.au1 = Author.objects.create(name="Author 1", alias="a1")
cls.au2 = Author.objects.create(name="Author 2", alias="a2")
# Create a few Articles.
cls.a1 = Article.objects.create(
headline="Article 1",
pub_date=datetime(2005, 7, 26),
author=cls.au1,
slug="a1",
)
cls.a2 = Article.objects.create(
headline="Article 2",
pub_date=datetime(2005, 7, 27),
author=cls.au1,
slug="a2",
)
cls.a3 = Article.objects.create(
headline="Article 3",
pub_date=datetime(2005, 7, 27),
author=cls.au1,
slug="a3",
)
cls.a4 = Article.objects.create(
headline="Article 4",
pub_date=datetime(2005, 7, 28),
author=cls.au1,
slug="a4",
)
cls.a5 = Article.objects.create(
headline="Article 5",
pub_date=datetime(2005, 8, 1, 9, 0),
author=cls.au2,
slug="a5",
)
cls.a6 = Article.objects.create(
headline="Article 6",
pub_date=datetime(2005, 8, 1, 8, 0),
author=cls.au2,
slug="a6",
)
cls.a7 = Article.objects.create(
headline="Article 7",
pub_date=datetime(2005, 7, 27),
author=cls.au2,
slug="a7",
)
# Create a few Tags.
cls.t1 = Tag.objects.create(name="Tag 1")
cls.t1.articles.add(cls.a1, cls.a2, cls.a3)
cls.t2 = Tag.objects.create(name="Tag 2")
cls.t2.articles.add(cls.a3, cls.a4, cls.a5)
cls.t3 = Tag.objects.create(name="Tag 3")
cls.t3.articles.add(cls.a5, cls.a6, cls.a7)
def test_exists(self):
# We can use .exists() to check that there are some
self.assertTrue(Article.objects.exists())
for a in Article.objects.all():
a.delete()
# There should be none now!
self.assertFalse(Article.objects.exists())
def test_lookup_int_as_str(self):
# Integer value can be queried using string
self.assertSequenceEqual(
Article.objects.filter(id__iexact=str(self.a1.id)),
[self.a1],
)
@skipUnlessDBFeature("supports_date_lookup_using_string")
def test_lookup_date_as_str(self):
# A date lookup can be performed using a string search
self.assertSequenceEqual(
Article.objects.filter(pub_date__startswith="2005"),
[self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1],
)
def test_iterator(self):
# Each QuerySet gets iterator(), which is a generator that "lazily"
# returns results using database-level iteration.
self.assertIsInstance(Article.objects.iterator(), collections.abc.Iterator)
self.assertQuerySetEqual(
Article.objects.iterator(),
[
"Article 5",
"Article 6",
"Article 4",
"Article 2",
"Article 3",
"Article 7",
"Article 1",
],
transform=attrgetter("headline"),
)
# iterator() can be used on any QuerySet.
self.assertQuerySetEqual(
Article.objects.filter(headline__endswith="4").iterator(),
["Article 4"],
transform=attrgetter("headline"),
)
def test_count(self):
# count() returns the number of objects matching search criteria.
self.assertEqual(Article.objects.count(), 7)
self.assertEqual(
Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).count(), 3
)
self.assertEqual(
Article.objects.filter(headline__startswith="Blah blah").count(), 0
)
# count() should respect sliced query sets.
articles = Article.objects.all()
self.assertEqual(articles.count(), 7)
self.assertEqual(articles[:4].count(), 4)
self.assertEqual(articles[1:100].count(), 6)
self.assertEqual(articles[10:100].count(), 0)
# Date and date/time lookups can also be done with strings.
self.assertEqual(
Article.objects.filter(pub_date__exact="2005-07-27 00:00:00").count(), 3
)
def test_in_bulk(self):
# in_bulk() takes a list of IDs and returns a dictionary mapping IDs to objects.
arts = Article.objects.in_bulk([self.a1.id, self.a2.id])
self.assertEqual(arts[self.a1.id], self.a1)
self.assertEqual(arts[self.a2.id], self.a2)
self.assertEqual(
Article.objects.in_bulk(),
{
self.a1.id: self.a1,
self.a2.id: self.a2,
self.a3.id: self.a3,
self.a4.id: self.a4,
self.a5.id: self.a5,
self.a6.id: self.a6,
self.a7.id: self.a7,
},
)
self.assertEqual(Article.objects.in_bulk([self.a3.id]), {self.a3.id: self.a3})
self.assertEqual(Article.objects.in_bulk({self.a3.id}), {self.a3.id: self.a3})
self.assertEqual(
Article.objects.in_bulk(frozenset([self.a3.id])), {self.a3.id: self.a3}
)
self.assertEqual(Article.objects.in_bulk((self.a3.id,)), {self.a3.id: self.a3})
self.assertEqual(Article.objects.in_bulk([1000]), {})
self.assertEqual(Article.objects.in_bulk([]), {})
self.assertEqual(
Article.objects.in_bulk(iter([self.a1.id])), {self.a1.id: self.a1}
)
self.assertEqual(Article.objects.in_bulk(iter([])), {})
with self.assertRaises(TypeError):
Article.objects.in_bulk(headline__startswith="Blah")
def test_in_bulk_lots_of_ids(self):
test_range = 2000
max_query_params = connection.features.max_query_params
expected_num_queries = (
ceil(test_range / max_query_params) if max_query_params else 1
)
Author.objects.bulk_create(
[Author() for i in range(test_range - Author.objects.count())]
)
authors = {author.pk: author for author in Author.objects.all()}
with self.assertNumQueries(expected_num_queries):
self.assertEqual(Author.objects.in_bulk(authors), authors)
def test_in_bulk_with_field(self):
self.assertEqual(
Article.objects.in_bulk(
[self.a1.slug, self.a2.slug, self.a3.slug], field_name="slug"
),
{
self.a1.slug: self.a1,
self.a2.slug: self.a2,
self.a3.slug: self.a3,
},
)
def test_in_bulk_meta_constraint(self):
season_2011 = Season.objects.create(year=2011)
season_2012 = Season.objects.create(year=2012)
Season.objects.create(year=2013)
self.assertEqual(
Season.objects.in_bulk(
[season_2011.year, season_2012.year],
field_name="year",
),
{season_2011.year: season_2011, season_2012.year: season_2012},
)
def test_in_bulk_non_unique_field(self):
msg = "in_bulk()'s field_name must be a unique field but 'author' isn't."
with self.assertRaisesMessage(ValueError, msg):
Article.objects.in_bulk([self.au1], field_name="author")
@skipUnlessDBFeature("can_distinct_on_fields")
def test_in_bulk_distinct_field(self):
self.assertEqual(
Article.objects.order_by("headline")
.distinct("headline")
.in_bulk(
[self.a1.headline, self.a5.headline],
field_name="headline",
),
{self.a1.headline: self.a1, self.a5.headline: self.a5},
)
@skipUnlessDBFeature("can_distinct_on_fields")
def test_in_bulk_multiple_distinct_field(self):
msg = "in_bulk()'s field_name must be a unique field but 'pub_date' isn't."
with self.assertRaisesMessage(ValueError, msg):
Article.objects.order_by("headline", "pub_date").distinct(
"headline",
"pub_date",
).in_bulk(field_name="pub_date")
@isolate_apps("lookup")
def test_in_bulk_non_unique_meta_constaint(self):
class Model(models.Model):
ean = models.CharField(max_length=100)
brand = models.CharField(max_length=100)
name = models.CharField(max_length=80)
class Meta:
constraints = [
models.UniqueConstraint(
fields=["ean"],
name="partial_ean_unique",
condition=models.Q(is_active=True),
),
models.UniqueConstraint(
fields=["brand", "name"],
name="together_brand_name_unique",
),
]
msg = "in_bulk()'s field_name must be a unique field but '%s' isn't."
for field_name in ["brand", "ean"]:
with self.subTest(field_name=field_name):
with self.assertRaisesMessage(ValueError, msg % field_name):
Model.objects.in_bulk(field_name=field_name)
def test_in_bulk_sliced_queryset(self):
msg = "Cannot use 'limit' or 'offset' with in_bulk()."
with self.assertRaisesMessage(TypeError, msg):
Article.objects.all()[0:5].in_bulk([self.a1.id, self.a2.id])
def test_values(self):
# values() returns a list of dictionaries instead of object instances --
# and you can specify which fields you want to retrieve.
self.assertSequenceEqual(
Article.objects.values("headline"),
[
{"headline": "Article 5"},
{"headline": "Article 6"},
{"headline": "Article 4"},
{"headline": "Article 2"},
{"headline": "Article 3"},
{"headline": "Article 7"},
{"headline": "Article 1"},
],
)
self.assertSequenceEqual(
Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).values("id"),
[{"id": self.a2.id}, {"id": self.a3.id}, {"id": self.a7.id}],
)
self.assertSequenceEqual(
Article.objects.values("id", "headline"),
[
{"id": self.a5.id, "headline": "Article 5"},
{"id": self.a6.id, "headline": "Article 6"},
{"id": self.a4.id, "headline": "Article 4"},
{"id": self.a2.id, "headline": "Article 2"},
{"id": self.a3.id, "headline": "Article 3"},
{"id": self.a7.id, "headline": "Article 7"},
{"id": self.a1.id, "headline": "Article 1"},
],
)
# You can use values() with iterator() for memory savings,
# because iterator() uses database-level iteration.
self.assertSequenceEqual(
list(Article.objects.values("id", "headline").iterator()),
[
{"headline": "Article 5", "id": self.a5.id},
{"headline": "Article 6", "id": self.a6.id},
{"headline": "Article 4", "id": self.a4.id},
{"headline": "Article 2", "id": self.a2.id},
{"headline": "Article 3", "id": self.a3.id},
{"headline": "Article 7", "id": self.a7.id},
{"headline": "Article 1", "id": self.a1.id},
],
)
# The values() method works with "extra" fields specified in extra(select).
self.assertSequenceEqual(
Article.objects.extra(select={"id_plus_one": "id + 1"}).values(
"id", "id_plus_one"
),
[
{"id": self.a5.id, "id_plus_one": self.a5.id + 1},
{"id": self.a6.id, "id_plus_one": self.a6.id + 1},
{"id": self.a4.id, "id_plus_one": self.a4.id + 1},
{"id": self.a2.id, "id_plus_one": self.a2.id + 1},
{"id": self.a3.id, "id_plus_one": self.a3.id + 1},
{"id": self.a7.id, "id_plus_one": self.a7.id + 1},
{"id": self.a1.id, "id_plus_one": self.a1.id + 1},
],
)
data = {
"id_plus_one": "id+1",
"id_plus_two": "id+2",
"id_plus_three": "id+3",
"id_plus_four": "id+4",
"id_plus_five": "id+5",
"id_plus_six": "id+6",
"id_plus_seven": "id+7",
"id_plus_eight": "id+8",
}
self.assertSequenceEqual(
Article.objects.filter(id=self.a1.id).extra(select=data).values(*data),
[
{
"id_plus_one": self.a1.id + 1,
"id_plus_two": self.a1.id + 2,
"id_plus_three": self.a1.id + 3,
"id_plus_four": self.a1.id + 4,
"id_plus_five": self.a1.id + 5,
"id_plus_six": self.a1.id + 6,
"id_plus_seven": self.a1.id + 7,
"id_plus_eight": self.a1.id + 8,
}
],
)
# You can specify fields from forward and reverse relations, just like filter().
self.assertSequenceEqual(
Article.objects.values("headline", "author__name"),
[
{"headline": self.a5.headline, "author__name": self.au2.name},
{"headline": self.a6.headline, "author__name": self.au2.name},
{"headline": self.a4.headline, "author__name": self.au1.name},
{"headline": self.a2.headline, "author__name": self.au1.name},
{"headline": self.a3.headline, "author__name": self.au1.name},
{"headline": self.a7.headline, "author__name": self.au2.name},
{"headline": self.a1.headline, "author__name": self.au1.name},
],
)
self.assertSequenceEqual(
Author.objects.values("name", "article__headline").order_by(
"name", "article__headline"
),
[
{"name": self.au1.name, "article__headline": self.a1.headline},
{"name": self.au1.name, "article__headline": self.a2.headline},
{"name": self.au1.name, "article__headline": self.a3.headline},
{"name": self.au1.name, "article__headline": self.a4.headline},
{"name": self.au2.name, "article__headline": self.a5.headline},
{"name": self.au2.name, "article__headline": self.a6.headline},
{"name": self.au2.name, "article__headline": self.a7.headline},
],
)
self.assertSequenceEqual(
(
Author.objects.values(
"name", "article__headline", "article__tag__name"
).order_by("name", "article__headline", "article__tag__name")
),
[
{
"name": self.au1.name,
"article__headline": self.a1.headline,
"article__tag__name": self.t1.name,
},
{
"name": self.au1.name,
"article__headline": self.a2.headline,
"article__tag__name": self.t1.name,
},
{
"name": self.au1.name,
"article__headline": self.a3.headline,
"article__tag__name": self.t1.name,
},
{
"name": self.au1.name,
"article__headline": self.a3.headline,
"article__tag__name": self.t2.name,
},
{
"name": self.au1.name,
"article__headline": self.a4.headline,
"article__tag__name": self.t2.name,
},
{
"name": self.au2.name,
"article__headline": self.a5.headline,
"article__tag__name": self.t2.name,
},
{
"name": self.au2.name,
"article__headline": self.a5.headline,
"article__tag__name": self.t3.name,
},
{
"name": self.au2.name,
"article__headline": self.a6.headline,
"article__tag__name": self.t3.name,
},
{
"name": self.au2.name,
"article__headline": self.a7.headline,
"article__tag__name": self.t3.name,
},
],
)
# However, an exception FieldDoesNotExist will be thrown if you specify
# a nonexistent field name in values() (a field that is neither in the
# model nor in extra(select)).
msg = (
"Cannot resolve keyword 'id_plus_two' into field. Choices are: "
"author, author_id, headline, id, id_plus_one, pub_date, slug, tag"
)
with self.assertRaisesMessage(FieldError, msg):
Article.objects.extra(select={"id_plus_one": "id + 1"}).values(
"id", "id_plus_two"
)
# If you don't specify field names to values(), all are returned.
self.assertSequenceEqual(
Article.objects.filter(id=self.a5.id).values(),
[
{
"id": self.a5.id,
"author_id": self.au2.id,
"headline": "Article 5",
"pub_date": datetime(2005, 8, 1, 9, 0),
"slug": "a5",
}
],
)
def test_values_list(self):
# values_list() is similar to values(), except that the results are
# returned as a list of tuples, rather than a list of dictionaries.
# Within each tuple, the order of the elements is the same as the order
# of fields in the values_list() call.
self.assertSequenceEqual(
Article.objects.values_list("headline"),
[
("Article 5",),
("Article 6",),
("Article 4",),
("Article 2",),
("Article 3",),
("Article 7",),
("Article 1",),
],
)
self.assertSequenceEqual(
Article.objects.values_list("id").order_by("id"),
[
(self.a1.id,),
(self.a2.id,),
(self.a3.id,),
(self.a4.id,),
(self.a5.id,),
(self.a6.id,),
(self.a7.id,),
],
)
self.assertSequenceEqual(
Article.objects.values_list("id", flat=True).order_by("id"),
[
self.a1.id,
self.a2.id,
self.a3.id,
self.a4.id,
self.a5.id,
self.a6.id,
self.a7.id,
],
)
self.assertSequenceEqual(
Article.objects.extra(select={"id_plus_one": "id+1"})
.order_by("id")
.values_list("id"),
[
(self.a1.id,),
(self.a2.id,),
(self.a3.id,),
(self.a4.id,),
(self.a5.id,),
(self.a6.id,),
(self.a7.id,),
],
)
self.assertSequenceEqual(
Article.objects.extra(select={"id_plus_one": "id+1"})
.order_by("id")
.values_list("id_plus_one", "id"),
[
(self.a1.id + 1, self.a1.id),
(self.a2.id + 1, self.a2.id),
(self.a3.id + 1, self.a3.id),
(self.a4.id + 1, self.a4.id),
(self.a5.id + 1, self.a5.id),
(self.a6.id + 1, self.a6.id),
(self.a7.id + 1, self.a7.id),
],
)
self.assertSequenceEqual(
Article.objects.extra(select={"id_plus_one": "id+1"})
.order_by("id")
.values_list("id", "id_plus_one"),
[
(self.a1.id, self.a1.id + 1),
(self.a2.id, self.a2.id + 1),
(self.a3.id, self.a3.id + 1),
(self.a4.id, self.a4.id + 1),
(self.a5.id, self.a5.id + 1),
(self.a6.id, self.a6.id + 1),
(self.a7.id, self.a7.id + 1),
],
)
args = ("name", "article__headline", "article__tag__name")
self.assertSequenceEqual(
Author.objects.values_list(*args).order_by(*args),
[
(self.au1.name, self.a1.headline, self.t1.name),
(self.au1.name, self.a2.headline, self.t1.name),
(self.au1.name, self.a3.headline, self.t1.name),
(self.au1.name, self.a3.headline, self.t2.name),
(self.au1.name, self.a4.headline, self.t2.name),
(self.au2.name, self.a5.headline, self.t2.name),
(self.au2.name, self.a5.headline, self.t3.name),
(self.au2.name, self.a6.headline, self.t3.name),
(self.au2.name, self.a7.headline, self.t3.name),
],
)
with self.assertRaises(TypeError):
Article.objects.values_list("id", "headline", flat=True)
def test_get_next_previous_by(self):
# Every DateField and DateTimeField creates get_next_by_FOO() and
# get_previous_by_FOO() methods. In the case of identical date values,
# these methods will use the ID as a fallback check. This guarantees
# that no records are skipped or duplicated.
self.assertEqual(repr(self.a1.get_next_by_pub_date()), "<Article: Article 2>")
self.assertEqual(repr(self.a2.get_next_by_pub_date()), "<Article: Article 3>")
self.assertEqual(
repr(self.a2.get_next_by_pub_date(headline__endswith="6")),
"<Article: Article 6>",
)
self.assertEqual(repr(self.a3.get_next_by_pub_date()), "<Article: Article 7>")
self.assertEqual(repr(self.a4.get_next_by_pub_date()), "<Article: Article 6>")
with self.assertRaises(Article.DoesNotExist):
self.a5.get_next_by_pub_date()
self.assertEqual(repr(self.a6.get_next_by_pub_date()), "<Article: Article 5>")
self.assertEqual(repr(self.a7.get_next_by_pub_date()), "<Article: Article 4>")
self.assertEqual(
repr(self.a7.get_previous_by_pub_date()), "<Article: Article 3>"
)
self.assertEqual(
repr(self.a6.get_previous_by_pub_date()), "<Article: Article 4>"
)
self.assertEqual(
repr(self.a5.get_previous_by_pub_date()), "<Article: Article 6>"
)
self.assertEqual(
repr(self.a4.get_previous_by_pub_date()), "<Article: Article 7>"
)
self.assertEqual(
repr(self.a3.get_previous_by_pub_date()), "<Article: Article 2>"
)
self.assertEqual(
repr(self.a2.get_previous_by_pub_date()), "<Article: Article 1>"
)
def test_escaping(self):
# Underscores, percent signs and backslashes have special meaning in the
# underlying SQL code, but Django handles the quoting of them automatically.
a8 = Article.objects.create(
headline="Article_ with underscore", pub_date=datetime(2005, 11, 20)
)
self.assertSequenceEqual(
Article.objects.filter(headline__startswith="Article"),
[a8, self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1],
)
self.assertSequenceEqual(
Article.objects.filter(headline__startswith="Article_"),
[a8],
)
a9 = Article.objects.create(
headline="Article% with percent sign", pub_date=datetime(2005, 11, 21)
)
self.assertSequenceEqual(
Article.objects.filter(headline__startswith="Article"),
[a9, a8, self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1],
)
self.assertSequenceEqual(
Article.objects.filter(headline__startswith="Article%"),
[a9],
)
a10 = Article.objects.create(
headline="Article with \\ backslash", pub_date=datetime(2005, 11, 22)
)
self.assertSequenceEqual(
Article.objects.filter(headline__contains="\\"),
[a10],
)
def test_exclude(self):
pub_date = datetime(2005, 11, 20)
a8 = Article.objects.create(
headline="Article_ with underscore", pub_date=pub_date
)
a9 = Article.objects.create(
headline="Article% with percent sign", pub_date=pub_date
)
a10 = Article.objects.create(
headline="Article with \\ backslash", pub_date=pub_date
)
# exclude() is the opposite of filter() when doing lookups:
self.assertSequenceEqual(
Article.objects.filter(headline__contains="Article").exclude(
headline__contains="with"
),
[self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1],
)
self.assertSequenceEqual(
Article.objects.exclude(headline__startswith="Article_"),
[a10, a9, self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1],
)
self.assertSequenceEqual(
Article.objects.exclude(headline="Article 7"),
[a10, a9, a8, self.a5, self.a6, self.a4, self.a2, self.a3, self.a1],
)
def test_none(self):
# none() returns a QuerySet that behaves like any other QuerySet object
self.assertSequenceEqual(Article.objects.none(), [])
self.assertSequenceEqual(
Article.objects.none().filter(headline__startswith="Article"), []
)
self.assertSequenceEqual(
Article.objects.filter(headline__startswith="Article").none(), []
)
self.assertEqual(Article.objects.none().count(), 0)
self.assertEqual(
Article.objects.none().update(headline="This should not take effect"), 0
)
self.assertSequenceEqual(list(Article.objects.none().iterator()), [])
def test_in(self):
self.assertSequenceEqual(
Article.objects.exclude(id__in=[]),
[self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1],
)
def test_in_empty_list(self):
self.assertSequenceEqual(Article.objects.filter(id__in=[]), [])
def test_in_different_database(self):
with self.assertRaisesMessage(
ValueError,
"Subqueries aren't allowed across different databases. Force the "
"inner query to be evaluated using `list(inner_query)`.",
):
list(Article.objects.filter(id__in=Article.objects.using("other").all()))
def test_in_keeps_value_ordering(self):
query = (
Article.objects.filter(slug__in=["a%d" % i for i in range(1, 8)])
.values("pk")
.query
)
self.assertIn(" IN (a1, a2, a3, a4, a5, a6, a7) ", str(query))
def test_in_ignore_none(self):
with self.assertNumQueries(1) as ctx:
self.assertSequenceEqual(
Article.objects.filter(id__in=[None, self.a1.id]),
[self.a1],
)
sql = ctx.captured_queries[0]["sql"]
self.assertIn("IN (%s)" % self.a1.pk, sql)
def test_in_ignore_solo_none(self):
with self.assertNumQueries(0):
self.assertSequenceEqual(Article.objects.filter(id__in=[None]), [])
def test_in_ignore_none_with_unhashable_items(self):
class UnhashableInt(int):
__hash__ = None
with self.assertNumQueries(1) as ctx:
self.assertSequenceEqual(
Article.objects.filter(id__in=[None, UnhashableInt(self.a1.id)]),
[self.a1],
)
sql = ctx.captured_queries[0]["sql"]
self.assertIn("IN (%s)" % self.a1.pk, sql)
def test_error_messages(self):
# Programming errors are pointed out with nice error messages
with self.assertRaisesMessage(
FieldError,
"Cannot resolve keyword 'pub_date_year' into field. Choices are: "
"author, author_id, headline, id, pub_date, slug, tag",
):
Article.objects.filter(pub_date_year="2005").count()
def test_unsupported_lookups(self):
with self.assertRaisesMessage(
FieldError,
"Unsupported lookup 'starts' for CharField or join on the field "
"not permitted, perhaps you meant startswith or istartswith?",
):
Article.objects.filter(headline__starts="Article")
with self.assertRaisesMessage(
FieldError,
"Unsupported lookup 'is_null' for DateTimeField or join on the field "
"not permitted, perhaps you meant isnull?",
):
Article.objects.filter(pub_date__is_null=True)
with self.assertRaisesMessage(
FieldError,
"Unsupported lookup 'gobbledygook' for DateTimeField or join on the field "
"not permitted.",
):
Article.objects.filter(pub_date__gobbledygook="blahblah")
def test_relation_nested_lookup_error(self):
# An invalid nested lookup on a related field raises a useful error.
msg = (
"Unsupported lookup 'editor' for ForeignKey or join on the field not "
"permitted."
)
with self.assertRaisesMessage(FieldError, msg):
Article.objects.filter(author__editor__name="James")
msg = (
"Unsupported lookup 'foo' for ForeignKey or join on the field not "
"permitted."
)
with self.assertRaisesMessage(FieldError, msg):
Tag.objects.filter(articles__foo="bar")
def test_regex(self):
# Create some articles with a bit more interesting headlines for
# testing field lookups.
Article.objects.all().delete()
now = datetime.now()
Article.objects.bulk_create(
[
Article(pub_date=now, headline="f"),
Article(pub_date=now, headline="fo"),
Article(pub_date=now, headline="foo"),
Article(pub_date=now, headline="fooo"),
Article(pub_date=now, headline="hey-Foo"),
Article(pub_date=now, headline="bar"),
Article(pub_date=now, headline="AbBa"),
Article(pub_date=now, headline="baz"),
Article(pub_date=now, headline="baxZ"),
]
)
# zero-or-more
self.assertQuerySetEqual(
Article.objects.filter(headline__regex=r"fo*"),
Article.objects.filter(headline__in=["f", "fo", "foo", "fooo"]),
)
self.assertQuerySetEqual(
Article.objects.filter(headline__iregex=r"fo*"),
Article.objects.filter(headline__in=["f", "fo", "foo", "fooo", "hey-Foo"]),
)
# one-or-more
self.assertQuerySetEqual(
Article.objects.filter(headline__regex=r"fo+"),
Article.objects.filter(headline__in=["fo", "foo", "fooo"]),
)
# wildcard
self.assertQuerySetEqual(
Article.objects.filter(headline__regex=r"fooo?"),
Article.objects.filter(headline__in=["foo", "fooo"]),
)
# leading anchor
self.assertQuerySetEqual(
Article.objects.filter(headline__regex=r"^b"),
Article.objects.filter(headline__in=["bar", "baxZ", "baz"]),
)
self.assertQuerySetEqual(
Article.objects.filter(headline__iregex=r"^a"),
Article.objects.filter(headline="AbBa"),
)
# trailing anchor
self.assertQuerySetEqual(
Article.objects.filter(headline__regex=r"z$"),
Article.objects.filter(headline="baz"),
)
self.assertQuerySetEqual(
Article.objects.filter(headline__iregex=r"z$"),
Article.objects.filter(headline__in=["baxZ", "baz"]),
)
# character sets
self.assertQuerySetEqual(
Article.objects.filter(headline__regex=r"ba[rz]"),
Article.objects.filter(headline__in=["bar", "baz"]),
)
self.assertQuerySetEqual(
Article.objects.filter(headline__regex=r"ba.[RxZ]"),
Article.objects.filter(headline="baxZ"),
)
self.assertQuerySetEqual(
Article.objects.filter(headline__iregex=r"ba[RxZ]"),
Article.objects.filter(headline__in=["bar", "baxZ", "baz"]),
)
# and more articles:
Article.objects.bulk_create(
[
Article(pub_date=now, headline="foobar"),
Article(pub_date=now, headline="foobaz"),
Article(pub_date=now, headline="ooF"),
Article(pub_date=now, headline="foobarbaz"),
Article(pub_date=now, headline="zoocarfaz"),
Article(pub_date=now, headline="barfoobaz"),
Article(pub_date=now, headline="bazbaRFOO"),
]
)
# alternation
self.assertQuerySetEqual(
Article.objects.filter(headline__regex=r"oo(f|b)"),
Article.objects.filter(
headline__in=[
"barfoobaz",
"foobar",
"foobarbaz",
"foobaz",
]
),
)
self.assertQuerySetEqual(
Article.objects.filter(headline__iregex=r"oo(f|b)"),
Article.objects.filter(
headline__in=[
"barfoobaz",
"foobar",
"foobarbaz",
"foobaz",
"ooF",
]
),
)
self.assertQuerySetEqual(
Article.objects.filter(headline__regex=r"^foo(f|b)"),
Article.objects.filter(headline__in=["foobar", "foobarbaz", "foobaz"]),
)
# greedy matching
self.assertQuerySetEqual(
Article.objects.filter(headline__regex=r"b.*az"),
Article.objects.filter(
headline__in=[
"barfoobaz",
"baz",
"bazbaRFOO",
"foobarbaz",
"foobaz",
]
),
)
self.assertQuerySetEqual(
Article.objects.filter(headline__iregex=r"b.*ar"),
Article.objects.filter(
headline__in=[
"bar",
"barfoobaz",
"bazbaRFOO",
"foobar",
"foobarbaz",
]
),
)
@skipUnlessDBFeature("supports_regex_backreferencing")
def test_regex_backreferencing(self):
# grouping and backreferences
now = datetime.now()
Article.objects.bulk_create(
[
Article(pub_date=now, headline="foobar"),
Article(pub_date=now, headline="foobaz"),
Article(pub_date=now, headline="ooF"),
Article(pub_date=now, headline="foobarbaz"),
Article(pub_date=now, headline="zoocarfaz"),
Article(pub_date=now, headline="barfoobaz"),
Article(pub_date=now, headline="bazbaRFOO"),
]
)
self.assertQuerySetEqual(
Article.objects.filter(headline__regex=r"b(.).*b\1").values_list(
"headline", flat=True
),
["barfoobaz", "bazbaRFOO", "foobarbaz"],
)
def test_regex_null(self):
"""
A regex lookup does not fail on null/None values
"""
Season.objects.create(year=2012, gt=None)
self.assertQuerySetEqual(Season.objects.filter(gt__regex=r"^$"), [])
def test_regex_non_string(self):
"""
A regex lookup does not fail on non-string fields
"""
s = Season.objects.create(year=2013, gt=444)
self.assertQuerySetEqual(Season.objects.filter(gt__regex=r"^444$"), [s])
def test_regex_non_ascii(self):
"""
A regex lookup does not trip on non-ASCII characters.
"""
Player.objects.create(name="\u2660")
Player.objects.get(name__regex="\u2660")
def test_nonfield_lookups(self):
"""
A lookup query containing non-fields raises the proper exception.
"""
msg = (
"Unsupported lookup 'blahblah' for CharField or join on the field not "
"permitted."
)
with self.assertRaisesMessage(FieldError, msg):
Article.objects.filter(headline__blahblah=99)
with self.assertRaisesMessage(FieldError, msg):
Article.objects.filter(headline__blahblah__exact=99)
msg = (
"Cannot resolve keyword 'blahblah' into field. Choices are: "
"author, author_id, headline, id, pub_date, slug, tag"
)
with self.assertRaisesMessage(FieldError, msg):
Article.objects.filter(blahblah=99)
def test_lookup_collision(self):
"""
Genuine field names don't collide with built-in lookup types
('year', 'gt', 'range', 'in' etc.) (#11670).
"""
# 'gt' is used as a code number for the year, e.g. 111=>2009.
season_2009 = Season.objects.create(year=2009, gt=111)
season_2009.games.create(home="Houston Astros", away="St. Louis Cardinals")
season_2010 = Season.objects.create(year=2010, gt=222)
season_2010.games.create(home="Houston Astros", away="Chicago Cubs")
season_2010.games.create(home="Houston Astros", away="Milwaukee Brewers")
season_2010.games.create(home="Houston Astros", away="St. Louis Cardinals")
season_2011 = Season.objects.create(year=2011, gt=333)
season_2011.games.create(home="Houston Astros", away="St. Louis Cardinals")
season_2011.games.create(home="Houston Astros", away="Milwaukee Brewers")
hunter_pence = Player.objects.create(name="Hunter Pence")
hunter_pence.games.set(Game.objects.filter(season__year__in=[2009, 2010]))
pudge = Player.objects.create(name="Ivan Rodriquez")
pudge.games.set(Game.objects.filter(season__year=2009))
pedro_feliz = Player.objects.create(name="Pedro Feliz")
pedro_feliz.games.set(Game.objects.filter(season__year__in=[2011]))
johnson = Player.objects.create(name="Johnson")
johnson.games.set(Game.objects.filter(season__year__in=[2011]))
# Games in 2010
self.assertEqual(Game.objects.filter(season__year=2010).count(), 3)
self.assertEqual(Game.objects.filter(season__year__exact=2010).count(), 3)
self.assertEqual(Game.objects.filter(season__gt=222).count(), 3)
self.assertEqual(Game.objects.filter(season__gt__exact=222).count(), 3)
# Games in 2011
self.assertEqual(Game.objects.filter(season__year=2011).count(), 2)
self.assertEqual(Game.objects.filter(season__year__exact=2011).count(), 2)
self.assertEqual(Game.objects.filter(season__gt=333).count(), 2)
self.assertEqual(Game.objects.filter(season__gt__exact=333).count(), 2)
self.assertEqual(Game.objects.filter(season__year__gt=2010).count(), 2)
self.assertEqual(Game.objects.filter(season__gt__gt=222).count(), 2)
# Games played in 2010 and 2011
self.assertEqual(Game.objects.filter(season__year__in=[2010, 2011]).count(), 5)
self.assertEqual(Game.objects.filter(season__year__gt=2009).count(), 5)
self.assertEqual(Game.objects.filter(season__gt__in=[222, 333]).count(), 5)
self.assertEqual(Game.objects.filter(season__gt__gt=111).count(), 5)
# Players who played in 2009
self.assertEqual(
Player.objects.filter(games__season__year=2009).distinct().count(), 2
)
self.assertEqual(
Player.objects.filter(games__season__year__exact=2009).distinct().count(), 2
)
self.assertEqual(
Player.objects.filter(games__season__gt=111).distinct().count(), 2
)
self.assertEqual(
Player.objects.filter(games__season__gt__exact=111).distinct().count(), 2
)
# Players who played in 2010
self.assertEqual(
Player.objects.filter(games__season__year=2010).distinct().count(), 1
)
self.assertEqual(
Player.objects.filter(games__season__year__exact=2010).distinct().count(), 1
)
self.assertEqual(
Player.objects.filter(games__season__gt=222).distinct().count(), 1
)
self.assertEqual(
Player.objects.filter(games__season__gt__exact=222).distinct().count(), 1
)
# Players who played in 2011
self.assertEqual(
Player.objects.filter(games__season__year=2011).distinct().count(), 2
)
self.assertEqual(
Player.objects.filter(games__season__year__exact=2011).distinct().count(), 2
)
self.assertEqual(
Player.objects.filter(games__season__gt=333).distinct().count(), 2
)
self.assertEqual(
Player.objects.filter(games__season__year__gt=2010).distinct().count(), 2
)
self.assertEqual(
Player.objects.filter(games__season__gt__gt=222).distinct().count(), 2
)
def test_chain_date_time_lookups(self):
self.assertCountEqual(
Article.objects.filter(pub_date__month__gt=7),
[self.a5, self.a6],
)
self.assertCountEqual(
Article.objects.filter(pub_date__day__gte=27),
[self.a2, self.a3, self.a4, self.a7],
)
self.assertCountEqual(
Article.objects.filter(pub_date__hour__lt=8),
[self.a1, self.a2, self.a3, self.a4, self.a7],
)
self.assertCountEqual(
Article.objects.filter(pub_date__minute__lte=0),
[self.a1, self.a2, self.a3, self.a4, self.a5, self.a6, self.a7],
)
def test_exact_none_transform(self):
"""Transforms are used for __exact=None."""
Season.objects.create(year=1, nulled_text_field="not null")
self.assertFalse(Season.objects.filter(nulled_text_field__isnull=True))
self.assertTrue(Season.objects.filter(nulled_text_field__nulled__isnull=True))
self.assertTrue(Season.objects.filter(nulled_text_field__nulled__exact=None))
self.assertTrue(Season.objects.filter(nulled_text_field__nulled=None))
def test_exact_sliced_queryset_limit_one(self):
self.assertCountEqual(
Article.objects.filter(author=Author.objects.all()[:1]),
[self.a1, self.a2, self.a3, self.a4],
)
def test_exact_sliced_queryset_limit_one_offset(self):
self.assertCountEqual(
Article.objects.filter(author=Author.objects.all()[1:2]),
[self.a5, self.a6, self.a7],
)
def test_exact_sliced_queryset_not_limited_to_one(self):
msg = (
"The QuerySet value for an exact lookup must be limited to one "
"result using slicing."
)
with self.assertRaisesMessage(ValueError, msg):
list(Article.objects.filter(author=Author.objects.all()[:2]))
with self.assertRaisesMessage(ValueError, msg):
list(Article.objects.filter(author=Author.objects.all()[1:]))
@skipUnless(connection.vendor == "mysql", "MySQL-specific workaround.")
def test_exact_booleanfield(self):
# MySQL ignores indexes with boolean fields unless they're compared
# directly to a boolean value.
product = Product.objects.create(name="Paper", qty_target=5000)
Stock.objects.create(product=product, short=False, qty_available=5100)
stock_1 = Stock.objects.create(product=product, short=True, qty_available=180)
qs = Stock.objects.filter(short=True)
self.assertSequenceEqual(qs, [stock_1])
self.assertIn(
"%s = True" % connection.ops.quote_name("short"),
str(qs.query),
)
@skipUnless(connection.vendor == "mysql", "MySQL-specific workaround.")
def test_exact_booleanfield_annotation(self):
# MySQL ignores indexes with boolean fields unless they're compared
# directly to a boolean value.
qs = Author.objects.annotate(
case=Case(
When(alias="a1", then=True),
default=False,
output_field=BooleanField(),
)
).filter(case=True)
self.assertSequenceEqual(qs, [self.au1])
self.assertIn(" = True", str(qs.query))
qs = Author.objects.annotate(
wrapped=ExpressionWrapper(Q(alias="a1"), output_field=BooleanField()),
).filter(wrapped=True)
self.assertSequenceEqual(qs, [self.au1])
self.assertIn(" = True", str(qs.query))
# EXISTS(...) shouldn't be compared to a boolean value.
qs = Author.objects.annotate(
exists=Exists(Author.objects.filter(alias="a1", pk=OuterRef("pk"))),
).filter(exists=True)
self.assertSequenceEqual(qs, [self.au1])
self.assertNotIn(" = True", str(qs.query))
def test_custom_field_none_rhs(self):
"""
__exact=value is transformed to __isnull=True if Field.get_prep_value()
converts value to None.
"""
season = Season.objects.create(year=2012, nulled_text_field=None)
self.assertTrue(
Season.objects.filter(pk=season.pk, nulled_text_field__isnull=True)
)
self.assertTrue(Season.objects.filter(pk=season.pk, nulled_text_field=""))
def test_pattern_lookups_with_substr(self):
a = Author.objects.create(name="John Smith", alias="Johx")
b = Author.objects.create(name="Rhonda Simpson", alias="sonx")
tests = (
("startswith", [a]),
("istartswith", [a]),
("contains", [a, b]),
("icontains", [a, b]),
("endswith", [b]),
("iendswith", [b]),
)
for lookup, result in tests:
with self.subTest(lookup=lookup):
authors = Author.objects.filter(
**{"name__%s" % lookup: Substr("alias", 1, 3)}
)
self.assertCountEqual(authors, result)
def test_custom_lookup_none_rhs(self):
"""Lookup.can_use_none_as_rhs=True allows None as a lookup value."""
season = Season.objects.create(year=2012, nulled_text_field=None)
query = Season.objects.get_queryset().query
field = query.model._meta.get_field("nulled_text_field")
self.assertIsInstance(
query.build_lookup(["isnull_none_rhs"], field, None), IsNullWithNoneAsRHS
)
self.assertTrue(
Season.objects.filter(pk=season.pk, nulled_text_field__isnull_none_rhs=True)
)
def test_exact_exists(self):
qs = Article.objects.filter(pk=OuterRef("pk"))
seasons = Season.objects.annotate(pk_exists=Exists(qs),).filter(
pk_exists=Exists(qs),
)
self.assertCountEqual(seasons, Season.objects.all())
def test_nested_outerref_lhs(self):
tag = Tag.objects.create(name=self.au1.alias)
tag.articles.add(self.a1)
qs = Tag.objects.annotate(
has_author_alias_match=Exists(
Article.objects.annotate(
author_exists=Exists(
Author.objects.filter(alias=OuterRef(OuterRef("name")))
),
).filter(author_exists=True)
),
)
self.assertEqual(qs.get(has_author_alias_match=True), tag)
def test_exact_query_rhs_with_selected_columns(self):
newest_author = Author.objects.create(name="Author 2")
authors_max_ids = (
Author.objects.filter(
name="Author 2",
)
.values(
"name",
)
.annotate(
max_id=Max("id"),
)
.values("max_id")
)
authors = Author.objects.filter(id=authors_max_ids[:1])
self.assertEqual(authors.get(), newest_author)
def test_isnull_non_boolean_value(self):
msg = "The QuerySet value for an isnull lookup must be True or False."
tests = [
Author.objects.filter(alias__isnull=1),
Article.objects.filter(author__isnull=1),
Season.objects.filter(games__isnull=1),
Freebie.objects.filter(stock__isnull=1),
]
for qs in tests:
with self.subTest(qs=qs):
with self.assertRaisesMessage(ValueError, msg):
qs.exists()
def test_lookup_rhs(self):
product = Product.objects.create(name="GME", qty_target=5000)
stock_1 = Stock.objects.create(product=product, short=True, qty_available=180)
stock_2 = Stock.objects.create(product=product, short=False, qty_available=5100)
Stock.objects.create(product=product, short=False, qty_available=4000)
self.assertCountEqual(
Stock.objects.filter(short=Q(qty_available__lt=F("product__qty_target"))),
[stock_1, stock_2],
)
self.assertCountEqual(
Stock.objects.filter(
short=ExpressionWrapper(
Q(qty_available__lt=F("product__qty_target")),
output_field=BooleanField(),
)
),
[stock_1, stock_2],
)
class LookupQueryingTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.s1 = Season.objects.create(year=1942, gt=1942)
cls.s2 = Season.objects.create(year=1842, gt=1942, nulled_text_field="text")
cls.s3 = Season.objects.create(year=2042, gt=1942)
def test_annotate(self):
qs = Season.objects.annotate(equal=Exact(F("year"), 1942))
self.assertCountEqual(
qs.values_list("year", "equal"),
((1942, True), (1842, False), (2042, False)),
)
def test_alias(self):
qs = Season.objects.alias(greater=GreaterThan(F("year"), 1910))
self.assertCountEqual(qs.filter(greater=True), [self.s1, self.s3])
def test_annotate_value_greater_than_value(self):
qs = Season.objects.annotate(greater=GreaterThan(Value(40), Value(30)))
self.assertCountEqual(
qs.values_list("year", "greater"),
((1942, True), (1842, True), (2042, True)),
)
def test_annotate_field_greater_than_field(self):
qs = Season.objects.annotate(greater=GreaterThan(F("year"), F("gt")))
self.assertCountEqual(
qs.values_list("year", "greater"),
((1942, False), (1842, False), (2042, True)),
)
def test_annotate_field_greater_than_value(self):
qs = Season.objects.annotate(greater=GreaterThan(F("year"), Value(1930)))
self.assertCountEqual(
qs.values_list("year", "greater"),
((1942, True), (1842, False), (2042, True)),
)
def test_annotate_field_greater_than_literal(self):
qs = Season.objects.annotate(greater=GreaterThan(F("year"), 1930))
self.assertCountEqual(
qs.values_list("year", "greater"),
((1942, True), (1842, False), (2042, True)),
)
def test_annotate_literal_greater_than_field(self):
qs = Season.objects.annotate(greater=GreaterThan(1930, F("year")))
self.assertCountEqual(
qs.values_list("year", "greater"),
((1942, False), (1842, True), (2042, False)),
)
def test_annotate_less_than_float(self):
qs = Season.objects.annotate(lesser=LessThan(F("year"), 1942.1))
self.assertCountEqual(
qs.values_list("year", "lesser"),
((1942, True), (1842, True), (2042, False)),
)
def test_annotate_greater_than_or_equal(self):
qs = Season.objects.annotate(greater=GreaterThanOrEqual(F("year"), 1942))
self.assertCountEqual(
qs.values_list("year", "greater"),
((1942, True), (1842, False), (2042, True)),
)
def test_annotate_greater_than_or_equal_float(self):
qs = Season.objects.annotate(greater=GreaterThanOrEqual(F("year"), 1942.1))
self.assertCountEqual(
qs.values_list("year", "greater"),
((1942, False), (1842, False), (2042, True)),
)
def test_combined_lookups(self):
expression = Exact(F("year"), 1942) | GreaterThan(F("year"), 1942)
qs = Season.objects.annotate(gte=expression)
self.assertCountEqual(
qs.values_list("year", "gte"),
((1942, True), (1842, False), (2042, True)),
)
def test_lookup_in_filter(self):
qs = Season.objects.filter(GreaterThan(F("year"), 1910))
self.assertCountEqual(qs, [self.s1, self.s3])
def test_isnull_lookup_in_filter(self):
self.assertSequenceEqual(
Season.objects.filter(IsNull(F("nulled_text_field"), False)),
[self.s2],
)
self.assertCountEqual(
Season.objects.filter(IsNull(F("nulled_text_field"), True)),
[self.s1, self.s3],
)
def test_filter_lookup_lhs(self):
qs = Season.objects.annotate(before_20=LessThan(F("year"), 2000)).filter(
before_20=LessThan(F("year"), 1900),
)
self.assertCountEqual(qs, [self.s2, self.s3])
def test_filter_wrapped_lookup_lhs(self):
qs = (
Season.objects.annotate(
before_20=ExpressionWrapper(
Q(year__lt=2000),
output_field=BooleanField(),
)
)
.filter(before_20=LessThan(F("year"), 1900))
.values_list("year", flat=True)
)
self.assertCountEqual(qs, [1842, 2042])
def test_filter_exists_lhs(self):
qs = Season.objects.annotate(
before_20=Exists(
Season.objects.filter(pk=OuterRef("pk"), year__lt=2000),
)
).filter(before_20=LessThan(F("year"), 1900))
self.assertCountEqual(qs, [self.s2, self.s3])
def test_filter_subquery_lhs(self):
qs = Season.objects.annotate(
before_20=Subquery(
Season.objects.filter(pk=OuterRef("pk")).values(
lesser=LessThan(F("year"), 2000),
),
)
).filter(before_20=LessThan(F("year"), 1900))
self.assertCountEqual(qs, [self.s2, self.s3])
def test_combined_lookups_in_filter(self):
expression = Exact(F("year"), 1942) | GreaterThan(F("year"), 1942)
qs = Season.objects.filter(expression)
self.assertCountEqual(qs, [self.s1, self.s3])
def test_combined_annotated_lookups_in_filter(self):
expression = Exact(F("year"), 1942) | GreaterThan(F("year"), 1942)
qs = Season.objects.annotate(gte=expression).filter(gte=True)
self.assertCountEqual(qs, [self.s1, self.s3])
def test_combined_annotated_lookups_in_filter_false(self):
expression = Exact(F("year"), 1942) | GreaterThan(F("year"), 1942)
qs = Season.objects.annotate(gte=expression).filter(gte=False)
self.assertSequenceEqual(qs, [self.s2])
def test_lookup_in_order_by(self):
qs = Season.objects.order_by(LessThan(F("year"), 1910), F("year"))
self.assertSequenceEqual(qs, [self.s1, self.s3, self.s2])
@skipUnlessDBFeature("supports_boolean_expr_in_select_clause")
def test_aggregate_combined_lookup(self):
expression = Cast(GreaterThan(F("year"), 1900), models.IntegerField())
qs = Season.objects.aggregate(modern=models.Sum(expression))
self.assertEqual(qs["modern"], 2)
def test_conditional_expression(self):
qs = Season.objects.annotate(
century=Case(
When(
GreaterThan(F("year"), 1900) & LessThanOrEqual(F("year"), 2000),
then=Value("20th"),
),
default=Value("other"),
)
).values("year", "century")
self.assertCountEqual(
qs,
[
{"year": 1942, "century": "20th"},
{"year": 1842, "century": "other"},
{"year": 2042, "century": "other"},
],
)
|
b9477608bc0f9b9cfa30738c8567732f2b34682811e321748b11048a916bc0c7 | from django import forms
from django.forms.formsets import DELETION_FIELD_NAME, BaseFormSet
from django.forms.models import (
BaseModelFormSet,
inlineformset_factory,
modelform_factory,
modelformset_factory,
)
from django.forms.utils import ErrorDict, ErrorList
from django.test import TestCase
from .models import (
Host,
Manager,
Network,
ProfileNetwork,
Restaurant,
User,
UserPreferences,
UserProfile,
UserSite,
)
class InlineFormsetTests(TestCase):
def test_formset_over_to_field(self):
"""
A formset over a ForeignKey with a to_field can be saved.
"""
Form = modelform_factory(User, fields="__all__")
FormSet = inlineformset_factory(User, UserSite, fields="__all__")
# Instantiate the Form and FormSet to prove
# you can create a form with no data
form = Form()
form_set = FormSet(instance=User())
# Now create a new User and UserSite instance
data = {
"serial": "1",
"username": "apollo13",
"usersite_set-TOTAL_FORMS": "1",
"usersite_set-INITIAL_FORMS": "0",
"usersite_set-MAX_NUM_FORMS": "0",
"usersite_set-0-data": "10",
"usersite_set-0-user": "apollo13",
}
user = User()
form = Form(data)
if form.is_valid():
user = form.save()
else:
self.fail("Errors found on form:%s" % form_set)
form_set = FormSet(data, instance=user)
if form_set.is_valid():
form_set.save()
usersite = UserSite.objects.values()
self.assertEqual(usersite[0]["data"], 10)
self.assertEqual(usersite[0]["user_id"], "apollo13")
else:
self.fail("Errors found on formset:%s" % form_set.errors)
# Now update the UserSite instance
data = {
"usersite_set-TOTAL_FORMS": "1",
"usersite_set-INITIAL_FORMS": "1",
"usersite_set-MAX_NUM_FORMS": "0",
"usersite_set-0-id": str(usersite[0]["id"]),
"usersite_set-0-data": "11",
"usersite_set-0-user": "apollo13",
}
form_set = FormSet(data, instance=user)
if form_set.is_valid():
form_set.save()
usersite = UserSite.objects.values()
self.assertEqual(usersite[0]["data"], 11)
self.assertEqual(usersite[0]["user_id"], "apollo13")
else:
self.fail("Errors found on formset:%s" % form_set.errors)
# Now add a new UserSite instance
data = {
"usersite_set-TOTAL_FORMS": "2",
"usersite_set-INITIAL_FORMS": "1",
"usersite_set-MAX_NUM_FORMS": "0",
"usersite_set-0-id": str(usersite[0]["id"]),
"usersite_set-0-data": "11",
"usersite_set-0-user": "apollo13",
"usersite_set-1-data": "42",
"usersite_set-1-user": "apollo13",
}
form_set = FormSet(data, instance=user)
if form_set.is_valid():
form_set.save()
usersite = UserSite.objects.values().order_by("data")
self.assertEqual(usersite[0]["data"], 11)
self.assertEqual(usersite[0]["user_id"], "apollo13")
self.assertEqual(usersite[1]["data"], 42)
self.assertEqual(usersite[1]["user_id"], "apollo13")
else:
self.fail("Errors found on formset:%s" % form_set.errors)
def test_formset_over_inherited_model(self):
"""
A formset over a ForeignKey with a to_field can be saved.
"""
Form = modelform_factory(Restaurant, fields="__all__")
FormSet = inlineformset_factory(Restaurant, Manager, fields="__all__")
# Instantiate the Form and FormSet to prove
# you can create a form with no data
form = Form()
form_set = FormSet(instance=Restaurant())
# Now create a new Restaurant and Manager instance
data = {
"name": "Guido's House of Pasta",
"manager_set-TOTAL_FORMS": "1",
"manager_set-INITIAL_FORMS": "0",
"manager_set-MAX_NUM_FORMS": "0",
"manager_set-0-name": "Guido Van Rossum",
}
restaurant = User()
form = Form(data)
if form.is_valid():
restaurant = form.save()
else:
self.fail("Errors found on form:%s" % form_set)
form_set = FormSet(data, instance=restaurant)
if form_set.is_valid():
form_set.save()
manager = Manager.objects.values()
self.assertEqual(manager[0]["name"], "Guido Van Rossum")
else:
self.fail("Errors found on formset:%s" % form_set.errors)
# Now update the Manager instance
data = {
"manager_set-TOTAL_FORMS": "1",
"manager_set-INITIAL_FORMS": "1",
"manager_set-MAX_NUM_FORMS": "0",
"manager_set-0-id": str(manager[0]["id"]),
"manager_set-0-name": "Terry Gilliam",
}
form_set = FormSet(data, instance=restaurant)
if form_set.is_valid():
form_set.save()
manager = Manager.objects.values()
self.assertEqual(manager[0]["name"], "Terry Gilliam")
else:
self.fail("Errors found on formset:%s" % form_set.errors)
# Now add a new Manager instance
data = {
"manager_set-TOTAL_FORMS": "2",
"manager_set-INITIAL_FORMS": "1",
"manager_set-MAX_NUM_FORMS": "0",
"manager_set-0-id": str(manager[0]["id"]),
"manager_set-0-name": "Terry Gilliam",
"manager_set-1-name": "John Cleese",
}
form_set = FormSet(data, instance=restaurant)
if form_set.is_valid():
form_set.save()
manager = Manager.objects.values().order_by("name")
self.assertEqual(manager[0]["name"], "John Cleese")
self.assertEqual(manager[1]["name"], "Terry Gilliam")
else:
self.fail("Errors found on formset:%s" % form_set.errors)
def test_inline_model_with_to_field(self):
"""
#13794 --- An inline model with a to_field of a formset with instance
has working relations.
"""
FormSet = inlineformset_factory(User, UserSite, exclude=("is_superuser",))
user = User.objects.create(username="guido", serial=1337)
UserSite.objects.create(user=user, data=10)
formset = FormSet(instance=user)
# Testing the inline model's relation
self.assertEqual(formset[0].instance.user_id, "guido")
def test_inline_model_with_primary_to_field(self):
"""An inline model with a OneToOneField with to_field & primary key."""
FormSet = inlineformset_factory(
User, UserPreferences, exclude=("is_superuser",)
)
user = User.objects.create(username="guido", serial=1337)
UserPreferences.objects.create(user=user, favorite_number=10)
formset = FormSet(instance=user)
self.assertEqual(formset[0].fields["user"].initial, "guido")
def test_inline_model_with_to_field_to_rel(self):
"""
#13794 --- An inline model with a to_field to a related field of a
formset with instance has working relations.
"""
FormSet = inlineformset_factory(UserProfile, ProfileNetwork, exclude=[])
user = User.objects.create(username="guido", serial=1337, pk=1)
self.assertEqual(user.pk, 1)
profile = UserProfile.objects.create(user=user, about="about", pk=2)
self.assertEqual(profile.pk, 2)
ProfileNetwork.objects.create(profile=profile, network=10, identifier=10)
formset = FormSet(instance=profile)
# Testing the inline model's relation
self.assertEqual(formset[0].instance.profile_id, 1)
def test_formset_with_none_instance(self):
"A formset with instance=None can be created. Regression for #11872"
Form = modelform_factory(User, fields="__all__")
FormSet = inlineformset_factory(User, UserSite, fields="__all__")
# Instantiate the Form and FormSet to prove
# you can create a formset with an instance of None
Form(instance=None)
FormSet(instance=None)
def test_empty_fields_on_modelformset(self):
"""
No fields passed to modelformset_factory() should result in no fields
on returned forms except for the id (#14119).
"""
UserFormSet = modelformset_factory(User, fields=())
formset = UserFormSet()
for form in formset.forms:
self.assertIn("id", form.fields)
self.assertEqual(len(form.fields), 1)
def test_save_as_new_with_new_inlines(self):
"""
Existing and new inlines are saved with save_as_new.
Regression for #14938.
"""
efnet = Network.objects.create(name="EFNet")
host1 = Host.objects.create(hostname="irc.he.net", network=efnet)
HostFormSet = inlineformset_factory(Network, Host, fields="__all__")
# Add a new host, modify previous host, and save-as-new
data = {
"host_set-TOTAL_FORMS": "2",
"host_set-INITIAL_FORMS": "1",
"host_set-MAX_NUM_FORMS": "0",
"host_set-0-id": str(host1.id),
"host_set-0-hostname": "tranquility.hub.dal.net",
"host_set-1-hostname": "matrix.de.eu.dal.net",
}
# To save a formset as new, it needs a new hub instance
dalnet = Network.objects.create(name="DALnet")
formset = HostFormSet(data, instance=dalnet, save_as_new=True)
self.assertTrue(formset.is_valid())
formset.save()
self.assertQuerySetEqual(
dalnet.host_set.order_by("hostname"),
Host.objects.filter(
hostname__in=[
"matrix.de.eu.dal.net",
"tranquility.hub.dal.net",
]
).order_by("hostname"),
)
def test_initial_data(self):
user = User.objects.create(username="bibi", serial=1)
UserSite.objects.create(user=user, data=7)
FormSet = inlineformset_factory(User, UserSite, extra=2, fields="__all__")
formset = FormSet(instance=user, initial=[{"data": 41}, {"data": 42}])
self.assertEqual(formset.forms[0].initial["data"], 7)
self.assertEqual(formset.extra_forms[0].initial["data"], 41)
self.assertIn('value="42"', formset.extra_forms[1].as_p())
class FormsetTests(TestCase):
def test_error_class(self):
"""
Test the type of Formset and Form error attributes
"""
Formset = modelformset_factory(User, fields="__all__")
data = {
"form-TOTAL_FORMS": "2",
"form-INITIAL_FORMS": "0",
"form-MAX_NUM_FORMS": "0",
"form-0-id": "",
"form-0-username": "apollo13",
"form-0-serial": "1",
"form-1-id": "",
"form-1-username": "apollo13",
"form-1-serial": "2",
}
formset = Formset(data)
# check if the returned error classes are correct
# note: formset.errors returns a list as documented
self.assertIsInstance(formset.errors, list)
self.assertIsInstance(formset.non_form_errors(), ErrorList)
for form in formset.forms:
self.assertIsInstance(form.errors, ErrorDict)
self.assertIsInstance(form.non_field_errors(), ErrorList)
def test_initial_data(self):
User.objects.create(username="bibi", serial=1)
Formset = modelformset_factory(User, fields="__all__", extra=2)
formset = Formset(initial=[{"username": "apollo11"}, {"username": "apollo12"}])
self.assertEqual(formset.forms[0].initial["username"], "bibi")
self.assertEqual(formset.extra_forms[0].initial["username"], "apollo11")
self.assertIn('value="apollo12"', formset.extra_forms[1].as_p())
def test_extraneous_query_is_not_run(self):
Formset = modelformset_factory(Network, fields="__all__")
data = {
"test-TOTAL_FORMS": "1",
"test-INITIAL_FORMS": "0",
"test-MAX_NUM_FORMS": "",
"test-0-name": "Random Place",
}
with self.assertNumQueries(1):
formset = Formset(data, prefix="test")
formset.save()
class CustomWidget(forms.widgets.TextInput):
pass
class UserSiteForm(forms.ModelForm):
class Meta:
model = UserSite
fields = "__all__"
widgets = {
"id": CustomWidget,
"data": CustomWidget,
}
localized_fields = ("data",)
class Callback:
def __init__(self):
self.log = []
def __call__(self, db_field, **kwargs):
self.log.append((db_field, kwargs))
return db_field.formfield(**kwargs)
class FormfieldCallbackTests(TestCase):
"""
Regression for #13095 and #17683: Using base forms with widgets
defined in Meta should not raise errors and BaseModelForm should respect
the specified pk widget.
"""
def test_inlineformset_factory_default(self):
Formset = inlineformset_factory(
User, UserSite, form=UserSiteForm, fields="__all__"
)
form = Formset().forms[0]
self.assertIsInstance(form["id"].field.widget, CustomWidget)
self.assertIsInstance(form["data"].field.widget, CustomWidget)
self.assertFalse(form.fields["id"].localize)
self.assertTrue(form.fields["data"].localize)
def test_modelformset_factory_default(self):
Formset = modelformset_factory(UserSite, form=UserSiteForm)
form = Formset().forms[0]
self.assertIsInstance(form["id"].field.widget, CustomWidget)
self.assertIsInstance(form["data"].field.widget, CustomWidget)
self.assertFalse(form.fields["id"].localize)
self.assertTrue(form.fields["data"].localize)
def assertCallbackCalled(self, callback):
id_field, user_field, data_field = UserSite._meta.fields
expected_log = [
(id_field, {"widget": CustomWidget}),
(user_field, {}),
(data_field, {"widget": CustomWidget, "localize": True}),
]
self.assertEqual(callback.log, expected_log)
def test_inlineformset_custom_callback(self):
callback = Callback()
inlineformset_factory(
User,
UserSite,
form=UserSiteForm,
formfield_callback=callback,
fields="__all__",
)
self.assertCallbackCalled(callback)
def test_modelformset_custom_callback(self):
callback = Callback()
modelformset_factory(UserSite, form=UserSiteForm, formfield_callback=callback)
self.assertCallbackCalled(callback)
class BaseCustomDeleteFormSet(BaseFormSet):
"""
A formset mix-in that lets a form decide if it's to be deleted.
Works for BaseFormSets. Also works for ModelFormSets with #14099 fixed.
form.should_delete() is called. The formset delete field is also suppressed.
"""
def add_fields(self, form, index):
super().add_fields(form, index)
self.can_delete = True
if DELETION_FIELD_NAME in form.fields:
del form.fields[DELETION_FIELD_NAME]
def _should_delete_form(self, form):
return hasattr(form, "should_delete") and form.should_delete()
class FormfieldShouldDeleteFormTests(TestCase):
"""
BaseModelFormSet should use ModelFormSet method _should_delete_form.
"""
class BaseCustomDeleteModelFormSet(BaseModelFormSet, BaseCustomDeleteFormSet):
"""Model FormSet with CustomDelete MixIn"""
class CustomDeleteUserForm(forms.ModelForm):
"""A model form with a 'should_delete' method"""
class Meta:
model = User
fields = "__all__"
def should_delete(self):
"""Delete form if odd serial."""
return self.instance.serial % 2 != 0
NormalFormset = modelformset_factory(
User, form=CustomDeleteUserForm, can_delete=True
)
DeleteFormset = modelformset_factory(
User, form=CustomDeleteUserForm, formset=BaseCustomDeleteModelFormSet
)
data = {
"form-TOTAL_FORMS": "4",
"form-INITIAL_FORMS": "0",
"form-MAX_NUM_FORMS": "4",
"form-0-username": "John",
"form-0-serial": "1",
"form-1-username": "Paul",
"form-1-serial": "2",
"form-2-username": "George",
"form-2-serial": "3",
"form-3-username": "Ringo",
"form-3-serial": "5",
}
delete_all_ids = {
"form-0-DELETE": "1",
"form-1-DELETE": "1",
"form-2-DELETE": "1",
"form-3-DELETE": "1",
}
def test_init_database(self):
"""Add test data to database via formset"""
formset = self.NormalFormset(self.data)
self.assertTrue(formset.is_valid())
self.assertEqual(len(formset.save()), 4)
def test_no_delete(self):
"""Verify base formset doesn't modify database"""
# reload database
self.test_init_database()
# pass standard data dict & see none updated
data = dict(self.data)
data["form-INITIAL_FORMS"] = 4
data.update(
{
"form-%d-id" % i: user.pk
for i, user in enumerate(User.objects.order_by("pk"))
}
)
formset = self.NormalFormset(data, queryset=User.objects.all())
self.assertTrue(formset.is_valid())
self.assertEqual(len(formset.save()), 0)
self.assertEqual(len(User.objects.all()), 4)
def test_all_delete(self):
"""Verify base formset honors DELETE field"""
# reload database
self.test_init_database()
# create data dict with all fields marked for deletion
data = dict(self.data)
data["form-INITIAL_FORMS"] = 4
data.update(
{"form-%d-id" % i: user.pk for i, user in enumerate(User.objects.all())}
)
data.update(self.delete_all_ids)
formset = self.NormalFormset(data, queryset=User.objects.all())
self.assertTrue(formset.is_valid())
self.assertEqual(len(formset.save()), 0)
self.assertEqual(len(User.objects.all()), 0)
def test_custom_delete(self):
"""Verify DeleteFormset ignores DELETE field and uses form method"""
# reload database
self.test_init_database()
# Create formset with custom Delete function
# create data dict with all fields marked for deletion
data = dict(self.data)
data["form-INITIAL_FORMS"] = 4
data.update(
{
"form-%d-id" % i: user.pk
for i, user in enumerate(User.objects.order_by("pk"))
}
)
data.update(self.delete_all_ids)
formset = self.DeleteFormset(data, queryset=User.objects.all())
# Three with odd serial values were deleted.
self.assertTrue(formset.is_valid())
self.assertEqual(len(formset.save()), 0)
self.assertEqual(User.objects.count(), 1)
# No odd serial values left.
odd_serials = [user.serial for user in User.objects.all() if user.serial % 2]
self.assertEqual(len(odd_serials), 0)
class RedeleteTests(TestCase):
def test_resubmit(self):
u = User.objects.create(username="foo", serial=1)
us = UserSite.objects.create(user=u, data=7)
formset_cls = inlineformset_factory(User, UserSite, fields="__all__")
data = {
"serial": "1",
"username": "foo",
"usersite_set-TOTAL_FORMS": "1",
"usersite_set-INITIAL_FORMS": "1",
"usersite_set-MAX_NUM_FORMS": "1",
"usersite_set-0-id": str(us.pk),
"usersite_set-0-data": "7",
"usersite_set-0-user": "foo",
"usersite_set-0-DELETE": "1",
}
formset = formset_cls(data, instance=u)
self.assertTrue(formset.is_valid())
formset.save()
self.assertEqual(UserSite.objects.count(), 0)
formset = formset_cls(data, instance=u)
# Even if the "us" object isn't in the DB any more, the form
# validates.
self.assertTrue(formset.is_valid())
formset.save()
self.assertEqual(UserSite.objects.count(), 0)
def test_delete_already_deleted(self):
u = User.objects.create(username="foo", serial=1)
us = UserSite.objects.create(user=u, data=7)
formset_cls = inlineformset_factory(User, UserSite, fields="__all__")
data = {
"serial": "1",
"username": "foo",
"usersite_set-TOTAL_FORMS": "1",
"usersite_set-INITIAL_FORMS": "1",
"usersite_set-MAX_NUM_FORMS": "1",
"usersite_set-0-id": str(us.pk),
"usersite_set-0-data": "7",
"usersite_set-0-user": "foo",
"usersite_set-0-DELETE": "1",
}
formset = formset_cls(data, instance=u)
us.delete()
self.assertTrue(formset.is_valid())
formset.save()
self.assertEqual(UserSite.objects.count(), 0)
|
c3c353f578ae623557526d66db308de2ea9c4d221a33c47dcd126497124fe4af | from django.core.exceptions import FieldDoesNotExist, FieldError
from django.test import SimpleTestCase, TestCase
from .models import (
BigChild,
Child,
ChildProxy,
Primary,
RefreshPrimaryProxy,
Secondary,
ShadowChild,
)
class AssertionMixin:
def assert_delayed(self, obj, num):
"""
Instances with deferred fields look the same as normal instances when
we examine attribute values. Therefore, this method returns the number
of deferred fields on returned instances.
"""
count = len(obj.get_deferred_fields())
self.assertEqual(count, num)
class DeferTests(AssertionMixin, TestCase):
@classmethod
def setUpTestData(cls):
cls.s1 = Secondary.objects.create(first="x1", second="y1")
cls.p1 = Primary.objects.create(name="p1", value="xx", related=cls.s1)
def test_defer(self):
qs = Primary.objects.all()
self.assert_delayed(qs.defer("name")[0], 1)
self.assert_delayed(qs.defer("name").get(pk=self.p1.pk), 1)
self.assert_delayed(qs.defer("related__first")[0], 0)
self.assert_delayed(qs.defer("name").defer("value")[0], 2)
def test_only(self):
qs = Primary.objects.all()
self.assert_delayed(qs.only("name")[0], 2)
self.assert_delayed(qs.only("name").get(pk=self.p1.pk), 2)
self.assert_delayed(qs.only("name").only("value")[0], 2)
self.assert_delayed(qs.only("related__first")[0], 2)
# Using 'pk' with only() should result in 3 deferred fields, namely all
# of them except the model's primary key see #15494
self.assert_delayed(qs.only("pk")[0], 3)
# You can use 'pk' with reverse foreign key lookups.
# The related_id is always set even if it's not fetched from the DB,
# so pk and related_id are not deferred.
self.assert_delayed(self.s1.primary_set.only("pk")[0], 2)
def test_defer_only_chaining(self):
qs = Primary.objects.all()
self.assert_delayed(qs.only("name", "value").defer("name")[0], 2)
self.assert_delayed(qs.defer("name").only("value", "name")[0], 2)
self.assert_delayed(qs.defer("name").only("name").only("value")[0], 2)
self.assert_delayed(qs.defer("name").only("value")[0], 2)
self.assert_delayed(qs.only("name").defer("value")[0], 2)
self.assert_delayed(qs.only("name").defer("name").defer("value")[0], 1)
self.assert_delayed(qs.only("name").defer("name", "value")[0], 1)
def test_defer_only_clear(self):
qs = Primary.objects.all()
self.assert_delayed(qs.only("name").defer("name")[0], 0)
self.assert_delayed(qs.defer("name").only("name")[0], 0)
def test_defer_on_an_already_deferred_field(self):
qs = Primary.objects.all()
self.assert_delayed(qs.defer("name")[0], 1)
self.assert_delayed(qs.defer("name").defer("name")[0], 1)
def test_defer_none_to_clear_deferred_set(self):
qs = Primary.objects.all()
self.assert_delayed(qs.defer("name", "value")[0], 2)
self.assert_delayed(qs.defer(None)[0], 0)
self.assert_delayed(qs.only("name").defer(None)[0], 0)
def test_only_none_raises_error(self):
msg = "Cannot pass None as an argument to only()."
with self.assertRaisesMessage(TypeError, msg):
Primary.objects.only(None)
def test_defer_extra(self):
qs = Primary.objects.all()
self.assert_delayed(qs.defer("name").extra(select={"a": 1})[0], 1)
self.assert_delayed(qs.extra(select={"a": 1}).defer("name")[0], 1)
def test_defer_values_does_not_defer(self):
# User values() won't defer anything (you get the full list of
# dictionaries back), but it still works.
self.assertEqual(
Primary.objects.defer("name").values()[0],
{
"id": self.p1.id,
"name": "p1",
"value": "xx",
"related_id": self.s1.id,
},
)
def test_only_values_does_not_defer(self):
self.assertEqual(
Primary.objects.only("name").values()[0],
{
"id": self.p1.id,
"name": "p1",
"value": "xx",
"related_id": self.s1.id,
},
)
def test_get(self):
# Using defer() and only() with get() is also valid.
qs = Primary.objects.all()
self.assert_delayed(qs.defer("name").get(pk=self.p1.pk), 1)
self.assert_delayed(qs.only("name").get(pk=self.p1.pk), 2)
def test_defer_with_select_related(self):
obj = Primary.objects.select_related().defer(
"related__first", "related__second"
)[0]
self.assert_delayed(obj.related, 2)
self.assert_delayed(obj, 0)
def test_only_with_select_related(self):
obj = Primary.objects.select_related().only("related__first")[0]
self.assert_delayed(obj, 2)
self.assert_delayed(obj.related, 1)
self.assertEqual(obj.related_id, self.s1.pk)
self.assertEqual(obj.name, "p1")
def test_defer_foreign_keys_are_deferred_and_not_traversed(self):
# select_related() overrides defer().
with self.assertNumQueries(1):
obj = Primary.objects.defer("related").select_related()[0]
self.assert_delayed(obj, 1)
self.assertEqual(obj.related.id, self.s1.pk)
def test_saving_object_with_deferred_field(self):
# Saving models with deferred fields is possible (but inefficient,
# since every field has to be retrieved first).
Primary.objects.create(name="p2", value="xy", related=self.s1)
obj = Primary.objects.defer("value").get(name="p2")
obj.name = "a new name"
obj.save()
self.assertQuerySetEqual(
Primary.objects.all(),
[
"p1",
"a new name",
],
lambda p: p.name,
ordered=False,
)
def test_defer_baseclass_when_subclass_has_no_added_fields(self):
# Regression for #10572 - A subclass with no extra fields can defer
# fields from the base class
Child.objects.create(name="c1", value="foo", related=self.s1)
# You can defer a field on a baseclass when the subclass has no fields
obj = Child.objects.defer("value").get(name="c1")
self.assert_delayed(obj, 1)
self.assertEqual(obj.name, "c1")
self.assertEqual(obj.value, "foo")
def test_only_baseclass_when_subclass_has_no_added_fields(self):
# You can retrieve a single column on a base class with no fields
Child.objects.create(name="c1", value="foo", related=self.s1)
obj = Child.objects.only("name").get(name="c1")
# on an inherited model, its PK is also fetched, hence '3' deferred fields.
self.assert_delayed(obj, 3)
self.assertEqual(obj.name, "c1")
self.assertEqual(obj.value, "foo")
def test_defer_of_overridden_scalar(self):
ShadowChild.objects.create()
obj = ShadowChild.objects.defer("name").get()
self.assertEqual(obj.name, "adonis")
class BigChildDeferTests(AssertionMixin, TestCase):
@classmethod
def setUpTestData(cls):
cls.s1 = Secondary.objects.create(first="x1", second="y1")
BigChild.objects.create(name="b1", value="foo", related=cls.s1, other="bar")
def test_defer_baseclass_when_subclass_has_added_field(self):
# You can defer a field on a baseclass
obj = BigChild.objects.defer("value").get(name="b1")
self.assert_delayed(obj, 1)
self.assertEqual(obj.name, "b1")
self.assertEqual(obj.value, "foo")
self.assertEqual(obj.other, "bar")
def test_defer_subclass(self):
# You can defer a field on a subclass
obj = BigChild.objects.defer("other").get(name="b1")
self.assert_delayed(obj, 1)
self.assertEqual(obj.name, "b1")
self.assertEqual(obj.value, "foo")
self.assertEqual(obj.other, "bar")
def test_defer_subclass_both(self):
# Deferring fields from both superclass and subclass works.
obj = BigChild.objects.defer("other", "value").get(name="b1")
self.assert_delayed(obj, 2)
def test_only_baseclass_when_subclass_has_added_field(self):
# You can retrieve a single field on a baseclass
obj = BigChild.objects.only("name").get(name="b1")
# when inherited model, its PK is also fetched, hence '4' deferred fields.
self.assert_delayed(obj, 4)
self.assertEqual(obj.name, "b1")
self.assertEqual(obj.value, "foo")
self.assertEqual(obj.other, "bar")
def test_only_subclass(self):
# You can retrieve a single field on a subclass
obj = BigChild.objects.only("other").get(name="b1")
self.assert_delayed(obj, 4)
self.assertEqual(obj.name, "b1")
self.assertEqual(obj.value, "foo")
self.assertEqual(obj.other, "bar")
class TestDefer2(AssertionMixin, TestCase):
def test_defer_proxy(self):
"""
Ensure select_related together with only on a proxy model behaves
as expected. See #17876.
"""
related = Secondary.objects.create(first="x1", second="x2")
ChildProxy.objects.create(name="p1", value="xx", related=related)
children = ChildProxy.objects.select_related().only("id", "name")
self.assertEqual(len(children), 1)
child = children[0]
self.assert_delayed(child, 2)
self.assertEqual(child.name, "p1")
self.assertEqual(child.value, "xx")
def test_defer_inheritance_pk_chaining(self):
"""
When an inherited model is fetched from the DB, its PK is also fetched.
When getting the PK of the parent model it is useful to use the already
fetched parent model PK if it happens to be available.
"""
s1 = Secondary.objects.create(first="x1", second="y1")
bc = BigChild.objects.create(name="b1", value="foo", related=s1, other="bar")
bc_deferred = BigChild.objects.only("name").get(pk=bc.pk)
with self.assertNumQueries(0):
bc_deferred.id
self.assertEqual(bc_deferred.pk, bc_deferred.id)
def test_eq(self):
s1 = Secondary.objects.create(first="x1", second="y1")
s1_defer = Secondary.objects.only("pk").get(pk=s1.pk)
self.assertEqual(s1, s1_defer)
self.assertEqual(s1_defer, s1)
def test_refresh_not_loading_deferred_fields(self):
s = Secondary.objects.create()
rf = Primary.objects.create(name="foo", value="bar", related=s)
rf2 = Primary.objects.only("related", "value").get()
rf.name = "new foo"
rf.value = "new bar"
rf.save()
with self.assertNumQueries(1):
rf2.refresh_from_db()
self.assertEqual(rf2.value, "new bar")
with self.assertNumQueries(1):
self.assertEqual(rf2.name, "new foo")
def test_custom_refresh_on_deferred_loading(self):
s = Secondary.objects.create()
rf = RefreshPrimaryProxy.objects.create(name="foo", value="bar", related=s)
rf2 = RefreshPrimaryProxy.objects.only("related").get()
rf.name = "new foo"
rf.value = "new bar"
rf.save()
with self.assertNumQueries(1):
# Customized refresh_from_db() reloads all deferred fields on
# access of any of them.
self.assertEqual(rf2.name, "new foo")
self.assertEqual(rf2.value, "new bar")
class InvalidDeferTests(SimpleTestCase):
def test_invalid_defer(self):
msg = "Primary has no field named 'missing'"
with self.assertRaisesMessage(FieldDoesNotExist, msg):
list(Primary.objects.defer("missing"))
with self.assertRaisesMessage(FieldError, "missing"):
list(Primary.objects.defer("value__missing"))
msg = "Secondary has no field named 'missing'"
with self.assertRaisesMessage(FieldDoesNotExist, msg):
list(Primary.objects.defer("related__missing"))
def test_invalid_only(self):
msg = "Primary has no field named 'missing'"
with self.assertRaisesMessage(FieldDoesNotExist, msg):
list(Primary.objects.only("missing"))
with self.assertRaisesMessage(FieldError, "missing"):
list(Primary.objects.only("value__missing"))
msg = "Secondary has no field named 'missing'"
with self.assertRaisesMessage(FieldDoesNotExist, msg):
list(Primary.objects.only("related__missing"))
def test_defer_select_related_raises_invalid_query(self):
msg = (
"Field Primary.related cannot be both deferred and traversed using "
"select_related at the same time."
)
with self.assertRaisesMessage(FieldError, msg):
Primary.objects.defer("related").select_related("related")[0]
def test_only_select_related_raises_invalid_query(self):
msg = (
"Field Primary.related cannot be both deferred and traversed using "
"select_related at the same time."
)
with self.assertRaisesMessage(FieldError, msg):
Primary.objects.only("name").select_related("related")[0]
|
f48e069d36787a3cf522e701aca7823a89b695b836b4aa3ee82a8bd5a4b237ea | import asyncio
import os
from unittest import mock
from asgiref.sync import async_to_sync
from django.core.cache import DEFAULT_CACHE_ALIAS, caches
from django.core.exceptions import ImproperlyConfigured, SynchronousOnlyOperation
from django.http import HttpResponse, HttpResponseNotAllowed
from django.test import RequestFactory, SimpleTestCase
from django.utils.asyncio import async_unsafe
from django.views.generic.base import View
from .models import SimpleModel
class CacheTest(SimpleTestCase):
def test_caches_local(self):
@async_to_sync
async def async_cache():
return caches[DEFAULT_CACHE_ALIAS]
cache_1 = async_cache()
cache_2 = async_cache()
self.assertIs(cache_1, cache_2)
class DatabaseConnectionTest(SimpleTestCase):
"""A database connection cannot be used in an async context."""
async def test_get_async_connection(self):
with self.assertRaises(SynchronousOnlyOperation):
list(SimpleModel.objects.all())
class AsyncUnsafeTest(SimpleTestCase):
"""
async_unsafe decorator should work correctly and returns the correct
message.
"""
@async_unsafe
def dangerous_method(self):
return True
async def test_async_unsafe(self):
# async_unsafe decorator catches bad access and returns the right
# message.
msg = (
"You cannot call this from an async context - use a thread or "
"sync_to_async."
)
with self.assertRaisesMessage(SynchronousOnlyOperation, msg):
self.dangerous_method()
@mock.patch.dict(os.environ, {"DJANGO_ALLOW_ASYNC_UNSAFE": "true"})
@async_to_sync # mock.patch() is not async-aware.
async def test_async_unsafe_suppressed(self):
# Decorator doesn't trigger check when the environment variable to
# suppress it is set.
try:
self.dangerous_method()
except SynchronousOnlyOperation:
self.fail("SynchronousOnlyOperation should not be raised.")
class SyncView(View):
def get(self, request, *args, **kwargs):
return HttpResponse("Hello (sync) world!")
class AsyncView(View):
async def get(self, request, *args, **kwargs):
return HttpResponse("Hello (async) world!")
class ViewTests(SimpleTestCase):
def test_views_are_correctly_marked(self):
tests = [
(SyncView, False),
(AsyncView, True),
]
for view_cls, is_async in tests:
with self.subTest(view_cls=view_cls, is_async=is_async):
self.assertIs(view_cls.view_is_async, is_async)
callback = view_cls.as_view()
self.assertIs(asyncio.iscoroutinefunction(callback), is_async)
def test_mixed_views_raise_error(self):
class MixedView(View):
def get(self, request, *args, **kwargs):
return HttpResponse("Hello (mixed) world!")
async def post(self, request, *args, **kwargs):
return HttpResponse("Hello (mixed) world!")
msg = (
f"{MixedView.__qualname__} HTTP handlers must either be all sync or all "
"async."
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
MixedView.as_view()
def test_options_handler_responds_correctly(self):
tests = [
(SyncView, False),
(AsyncView, True),
]
for view_cls, is_coroutine in tests:
with self.subTest(view_cls=view_cls, is_coroutine=is_coroutine):
instance = view_cls()
response = instance.options(None)
self.assertIs(
asyncio.iscoroutine(response),
is_coroutine,
)
if is_coroutine:
response = asyncio.run(response)
self.assertIsInstance(response, HttpResponse)
def test_http_method_not_allowed_responds_correctly(self):
request_factory = RequestFactory()
tests = [
(SyncView, False),
(AsyncView, True),
]
for view_cls, is_coroutine in tests:
with self.subTest(view_cls=view_cls, is_coroutine=is_coroutine):
instance = view_cls()
response = instance.http_method_not_allowed(request_factory.post("/"))
self.assertIs(
asyncio.iscoroutine(response),
is_coroutine,
)
if is_coroutine:
response = asyncio.run(response)
self.assertIsInstance(response, HttpResponseNotAllowed)
def test_base_view_class_is_sync(self):
"""
View and by extension any subclasses that don't define handlers are
sync.
"""
self.assertIs(View.view_is_async, False)
|
eee950f9376222fcbea8b01cdc76137d5409f5b67c81baf07e76bc89ed41d303 | from operator import attrgetter
from django.core.exceptions import FieldError, ValidationError
from django.db import connection, models
from django.db.models.query_utils import DeferredAttribute
from django.test import SimpleTestCase, TestCase
from django.test.utils import CaptureQueriesContext, isolate_apps
from .models import (
Base,
Chef,
CommonInfo,
GrandChild,
GrandParent,
ItalianRestaurant,
MixinModel,
Parent,
ParkingLot,
Place,
Post,
Restaurant,
Student,
SubBase,
Supplier,
Title,
Worker,
)
class ModelInheritanceTests(TestCase):
def test_abstract(self):
# The Student and Worker models both have 'name' and 'age' fields on
# them and inherit the __str__() method, just as with normal Python
# subclassing. This is useful if you want to factor out common
# information for programming purposes, but still completely
# independent separate models at the database level.
w1 = Worker.objects.create(name="Fred", age=35, job="Quarry worker")
Worker.objects.create(name="Barney", age=34, job="Quarry worker")
s = Student.objects.create(name="Pebbles", age=5, school_class="1B")
self.assertEqual(str(w1), "Worker Fred")
self.assertEqual(str(s), "Student Pebbles")
# The children inherit the Meta class of their parents (if they don't
# specify their own).
self.assertSequenceEqual(
Worker.objects.values("name"),
[
{"name": "Barney"},
{"name": "Fred"},
],
)
# Since Student does not subclass CommonInfo's Meta, it has the effect
# of completely overriding it. So ordering by name doesn't take place
# for Students.
self.assertEqual(Student._meta.ordering, [])
# However, the CommonInfo class cannot be used as a normal model (it
# doesn't exist as a model).
with self.assertRaisesMessage(
AttributeError, "'CommonInfo' has no attribute 'objects'"
):
CommonInfo.objects.all()
def test_reverse_relation_for_different_hierarchy_tree(self):
# Even though p.supplier for a Place 'p' (a parent of a Supplier), a
# Restaurant object cannot access that reverse relation, since it's not
# part of the Place-Supplier Hierarchy.
self.assertSequenceEqual(Place.objects.filter(supplier__name="foo"), [])
msg = (
"Cannot resolve keyword 'supplier' into field. Choices are: "
"address, chef, chef_id, id, italianrestaurant, lot, name, "
"place_ptr, place_ptr_id, provider, rating, serves_hot_dogs, serves_pizza"
)
with self.assertRaisesMessage(FieldError, msg):
Restaurant.objects.filter(supplier__name="foo")
def test_model_with_distinct_accessors(self):
# The Post model has distinct accessors for the Comment and Link models.
post = Post.objects.create(title="Lorem Ipsum")
post.attached_comment_set.create(content="Save $ on V1agr@", is_spam=True)
post.attached_link_set.create(
content="The web framework for perfections with deadlines.",
url="http://www.djangoproject.com/",
)
# The Post model doesn't have an attribute called
# 'attached_%(class)s_set'.
msg = "'Post' object has no attribute 'attached_%(class)s_set'"
with self.assertRaisesMessage(AttributeError, msg):
getattr(post, "attached_%(class)s_set")
def test_model_with_distinct_related_query_name(self):
self.assertSequenceEqual(
Post.objects.filter(attached_model_inheritance_comments__is_spam=True), []
)
# The Post model doesn't have a related query accessor based on
# related_name (attached_comment_set).
msg = "Cannot resolve keyword 'attached_comment_set' into field."
with self.assertRaisesMessage(FieldError, msg):
Post.objects.filter(attached_comment_set__is_spam=True)
def test_meta_fields_and_ordering(self):
# Make sure Restaurant and ItalianRestaurant have the right fields in
# the right order.
self.assertEqual(
[f.name for f in Restaurant._meta.fields],
[
"id",
"name",
"address",
"place_ptr",
"rating",
"serves_hot_dogs",
"serves_pizza",
"chef",
],
)
self.assertEqual(
[f.name for f in ItalianRestaurant._meta.fields],
[
"id",
"name",
"address",
"place_ptr",
"rating",
"serves_hot_dogs",
"serves_pizza",
"chef",
"restaurant_ptr",
"serves_gnocchi",
],
)
self.assertEqual(Restaurant._meta.ordering, ["-rating"])
def test_custompk_m2m(self):
b = Base.objects.create()
b.titles.add(Title.objects.create(title="foof"))
s = SubBase.objects.create(sub_id=b.id)
b = Base.objects.get(pk=s.id)
self.assertNotEqual(b.pk, s.pk)
# Low-level test for related_val
self.assertEqual(s.titles.related_val, (s.id,))
# Higher level test for correct query values (title foof not
# accidentally found).
self.assertSequenceEqual(s.titles.all(), [])
def test_update_parent_filtering(self):
"""
Updating a field of a model subclass doesn't issue an UPDATE
query constrained by an inner query (#10399).
"""
supplier = Supplier.objects.create(
name="Central market",
address="610 some street",
)
# Capture the expected query in a database agnostic way
with CaptureQueriesContext(connection) as captured_queries:
Place.objects.filter(pk=supplier.pk).update(name=supplier.name)
expected_sql = captured_queries[0]["sql"]
# Capture the queries executed when a subclassed model instance is saved.
with CaptureQueriesContext(connection) as captured_queries:
supplier.save(update_fields=("name",))
for query in captured_queries:
sql = query["sql"]
if "UPDATE" in sql:
self.assertEqual(expected_sql, sql)
def test_create_child_no_update(self):
"""Creating a child with non-abstract parents only issues INSERTs."""
def a():
GrandChild.objects.create(
email="[email protected]",
first_name="grand",
last_name="parent",
)
def b():
GrandChild().save()
for i, test in enumerate([a, b]):
with self.subTest(i=i), self.assertNumQueries(4), CaptureQueriesContext(
connection
) as queries:
test()
for query in queries:
sql = query["sql"]
self.assertIn("INSERT INTO", sql, sql)
def test_eq(self):
# Equality doesn't transfer in multitable inheritance.
self.assertNotEqual(Place(id=1), Restaurant(id=1))
self.assertNotEqual(Restaurant(id=1), Place(id=1))
def test_mixin_init(self):
m = MixinModel()
self.assertEqual(m.other_attr, 1)
@isolate_apps("model_inheritance")
def test_abstract_parent_link(self):
class A(models.Model):
pass
class B(A):
a = models.OneToOneField("A", parent_link=True, on_delete=models.CASCADE)
class Meta:
abstract = True
class C(B):
pass
self.assertIs(C._meta.parents[A], C._meta.get_field("a"))
@isolate_apps("model_inheritance")
def test_init_subclass(self):
saved_kwargs = {}
class A(models.Model):
def __init_subclass__(cls, **kwargs):
super().__init_subclass__()
saved_kwargs.update(kwargs)
kwargs = {"x": 1, "y": 2, "z": 3}
class B(A, **kwargs):
pass
self.assertEqual(saved_kwargs, kwargs)
@isolate_apps("model_inheritance")
def test_set_name(self):
class ClassAttr:
called = None
def __set_name__(self_, owner, name):
self.assertIsNone(self_.called)
self_.called = (owner, name)
class A(models.Model):
attr = ClassAttr()
self.assertEqual(A.attr.called, (A, "attr"))
def test_inherited_ordering_pk_desc(self):
p1 = Parent.objects.create(first_name="Joe", email="[email protected]")
p2 = Parent.objects.create(first_name="Jon", email="[email protected]")
expected_order_by_sql = "ORDER BY %s.%s DESC" % (
connection.ops.quote_name(Parent._meta.db_table),
connection.ops.quote_name(Parent._meta.get_field("grandparent_ptr").column),
)
qs = Parent.objects.all()
self.assertSequenceEqual(qs, [p2, p1])
self.assertIn(expected_order_by_sql, str(qs.query))
def test_queryset_class_getitem(self):
self.assertIs(models.QuerySet[Post], models.QuerySet)
self.assertIs(models.QuerySet[Post, Post], models.QuerySet)
self.assertIs(models.QuerySet[Post, int, str], models.QuerySet)
def test_shadow_parent_attribute_with_field(self):
class ScalarParent(models.Model):
foo = 1
class ScalarOverride(ScalarParent):
foo = models.IntegerField()
self.assertEqual(type(ScalarOverride.foo), DeferredAttribute)
def test_shadow_parent_property_with_field(self):
class PropertyParent(models.Model):
@property
def foo(self):
pass
class PropertyOverride(PropertyParent):
foo = models.IntegerField()
self.assertEqual(type(PropertyOverride.foo), DeferredAttribute)
def test_shadow_parent_method_with_field(self):
class MethodParent(models.Model):
def foo(self):
pass
class MethodOverride(MethodParent):
foo = models.IntegerField()
self.assertEqual(type(MethodOverride.foo), DeferredAttribute)
class ModelInheritanceDataTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.restaurant = Restaurant.objects.create(
name="Demon Dogs",
address="944 W. Fullerton",
serves_hot_dogs=True,
serves_pizza=False,
rating=2,
)
chef = Chef.objects.create(name="Albert")
cls.italian_restaurant = ItalianRestaurant.objects.create(
name="Ristorante Miron",
address="1234 W. Ash",
serves_hot_dogs=False,
serves_pizza=False,
serves_gnocchi=True,
rating=4,
chef=chef,
)
def test_filter_inherited_model(self):
self.assertQuerySetEqual(
ItalianRestaurant.objects.filter(address="1234 W. Ash"),
[
"Ristorante Miron",
],
attrgetter("name"),
)
def test_update_inherited_model(self):
self.italian_restaurant.address = "1234 W. Elm"
self.italian_restaurant.save()
self.assertQuerySetEqual(
ItalianRestaurant.objects.filter(address="1234 W. Elm"),
[
"Ristorante Miron",
],
attrgetter("name"),
)
def test_parent_fields_available_for_filtering_in_child_model(self):
# Parent fields can be used directly in filters on the child model.
self.assertQuerySetEqual(
Restaurant.objects.filter(name="Demon Dogs"),
[
"Demon Dogs",
],
attrgetter("name"),
)
self.assertQuerySetEqual(
ItalianRestaurant.objects.filter(address="1234 W. Ash"),
[
"Ristorante Miron",
],
attrgetter("name"),
)
def test_filter_on_parent_returns_object_of_parent_type(self):
# Filters against the parent model return objects of the parent's type.
p = Place.objects.get(name="Demon Dogs")
self.assertIs(type(p), Place)
def test_parent_child_one_to_one_link(self):
# Since the parent and child are linked by an automatically created
# OneToOneField, you can get from the parent to the child by using the
# child's name.
self.assertEqual(
Place.objects.get(name="Demon Dogs").restaurant,
Restaurant.objects.get(name="Demon Dogs"),
)
self.assertEqual(
Place.objects.get(name="Ristorante Miron").restaurant.italianrestaurant,
ItalianRestaurant.objects.get(name="Ristorante Miron"),
)
self.assertEqual(
Restaurant.objects.get(name="Ristorante Miron").italianrestaurant,
ItalianRestaurant.objects.get(name="Ristorante Miron"),
)
def test_parent_child_one_to_one_link_on_nonrelated_objects(self):
# This won't work because the Demon Dogs restaurant is not an Italian
# restaurant.
with self.assertRaises(ItalianRestaurant.DoesNotExist):
Place.objects.get(name="Demon Dogs").restaurant.italianrestaurant
def test_inherited_does_not_exist_exception(self):
# An ItalianRestaurant which does not exist is also a Place which does
# not exist.
with self.assertRaises(Place.DoesNotExist):
ItalianRestaurant.objects.get(name="The Noodle Void")
def test_inherited_multiple_objects_returned_exception(self):
# MultipleObjectsReturned is also inherited.
with self.assertRaises(Place.MultipleObjectsReturned):
Restaurant.objects.get()
def test_related_objects_for_inherited_models(self):
# Related objects work just as they normally do.
s1 = Supplier.objects.create(name="Joe's Chickens", address="123 Sesame St")
s1.customers.set([self.restaurant, self.italian_restaurant])
s2 = Supplier.objects.create(name="Luigi's Pasta", address="456 Sesame St")
s2.customers.set([self.italian_restaurant])
# This won't work because the Place we select is not a Restaurant (it's
# a Supplier).
p = Place.objects.get(name="Joe's Chickens")
with self.assertRaises(Restaurant.DoesNotExist):
p.restaurant
self.assertEqual(p.supplier, s1)
self.assertQuerySetEqual(
self.italian_restaurant.provider.order_by("-name"),
["Luigi's Pasta", "Joe's Chickens"],
attrgetter("name"),
)
self.assertQuerySetEqual(
Restaurant.objects.filter(provider__name__contains="Chickens"),
[
"Ristorante Miron",
"Demon Dogs",
],
attrgetter("name"),
)
self.assertQuerySetEqual(
ItalianRestaurant.objects.filter(provider__name__contains="Chickens"),
[
"Ristorante Miron",
],
attrgetter("name"),
)
ParkingLot.objects.create(name="Main St", address="111 Main St", main_site=s1)
ParkingLot.objects.create(
name="Well Lit", address="124 Sesame St", main_site=self.italian_restaurant
)
self.assertEqual(
Restaurant.objects.get(lot__name="Well Lit").name, "Ristorante Miron"
)
def test_update_works_on_parent_and_child_models_at_once(self):
# The update() command can update fields in parent and child classes at
# once (although it executed multiple SQL queries to do so).
rows = Restaurant.objects.filter(
serves_hot_dogs=True, name__contains="D"
).update(name="Demon Puppies", serves_hot_dogs=False)
self.assertEqual(rows, 1)
r1 = Restaurant.objects.get(pk=self.restaurant.pk)
self.assertFalse(r1.serves_hot_dogs)
self.assertEqual(r1.name, "Demon Puppies")
def test_values_works_on_parent_model_fields(self):
# The values() command also works on fields from parent models.
self.assertSequenceEqual(
ItalianRestaurant.objects.values("name", "rating"),
[
{"rating": 4, "name": "Ristorante Miron"},
],
)
def test_select_related_works_on_parent_model_fields(self):
# select_related works with fields from the parent object as if they
# were a normal part of the model.
self.assertNumQueries(2, lambda: ItalianRestaurant.objects.all()[0].chef)
self.assertNumQueries(
1, lambda: ItalianRestaurant.objects.select_related("chef")[0].chef
)
def test_select_related_defer(self):
"""
#23370 - Should be able to defer child fields when using
select_related() from parent to child.
"""
qs = (
Restaurant.objects.select_related("italianrestaurant")
.defer("italianrestaurant__serves_gnocchi")
.order_by("rating")
)
# The field was actually deferred
with self.assertNumQueries(2):
objs = list(qs.all())
self.assertTrue(objs[1].italianrestaurant.serves_gnocchi)
# Model fields where assigned correct values
self.assertEqual(qs[0].name, "Demon Dogs")
self.assertEqual(qs[0].rating, 2)
self.assertEqual(qs[1].italianrestaurant.name, "Ristorante Miron")
self.assertEqual(qs[1].italianrestaurant.rating, 4)
def test_parent_cache_reuse(self):
place = Place.objects.create()
GrandChild.objects.create(place=place)
grand_parent = GrandParent.objects.latest("pk")
with self.assertNumQueries(1):
self.assertEqual(grand_parent.place, place)
parent = grand_parent.parent
with self.assertNumQueries(0):
self.assertEqual(parent.place, place)
child = parent.child
with self.assertNumQueries(0):
self.assertEqual(child.place, place)
grandchild = child.grandchild
with self.assertNumQueries(0):
self.assertEqual(grandchild.place, place)
def test_update_query_counts(self):
"""
Update queries do not generate unnecessary queries (#18304).
"""
with self.assertNumQueries(3):
self.italian_restaurant.save()
def test_filter_inherited_on_null(self):
# Refs #12567
Supplier.objects.create(
name="Central market",
address="610 some street",
)
self.assertQuerySetEqual(
Place.objects.filter(supplier__isnull=False),
[
"Central market",
],
attrgetter("name"),
)
self.assertQuerySetEqual(
Place.objects.filter(supplier__isnull=True).order_by("name"),
[
"Demon Dogs",
"Ristorante Miron",
],
attrgetter("name"),
)
def test_exclude_inherited_on_null(self):
# Refs #12567
Supplier.objects.create(
name="Central market",
address="610 some street",
)
self.assertQuerySetEqual(
Place.objects.exclude(supplier__isnull=False).order_by("name"),
[
"Demon Dogs",
"Ristorante Miron",
],
attrgetter("name"),
)
self.assertQuerySetEqual(
Place.objects.exclude(supplier__isnull=True),
[
"Central market",
],
attrgetter("name"),
)
@isolate_apps("model_inheritance", "model_inheritance.tests")
class InheritanceSameModelNameTests(SimpleTestCase):
def test_abstract_fk_related_name(self):
related_name = "%(app_label)s_%(class)s_references"
class Referenced(models.Model):
class Meta:
app_label = "model_inheritance"
class AbstractReferent(models.Model):
reference = models.ForeignKey(
Referenced, models.CASCADE, related_name=related_name
)
class Meta:
app_label = "model_inheritance"
abstract = True
class Referent(AbstractReferent):
class Meta:
app_label = "model_inheritance"
LocalReferent = Referent
class Referent(AbstractReferent):
class Meta:
app_label = "tests"
ForeignReferent = Referent
self.assertFalse(hasattr(Referenced, related_name))
self.assertIs(
Referenced.model_inheritance_referent_references.field.model, LocalReferent
)
self.assertIs(Referenced.tests_referent_references.field.model, ForeignReferent)
class InheritanceUniqueTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.grand_parent = GrandParent.objects.create(
email="[email protected]",
first_name="grand",
last_name="parent",
)
def test_unique(self):
grand_child = GrandChild(
email=self.grand_parent.email,
first_name="grand",
last_name="child",
)
msg = "Grand parent with this Email already exists."
with self.assertRaisesMessage(ValidationError, msg):
grand_child.validate_unique()
def test_unique_together(self):
grand_child = GrandChild(
email="[email protected]",
first_name=self.grand_parent.first_name,
last_name=self.grand_parent.last_name,
)
msg = "Grand parent with this First name and Last name already exists."
with self.assertRaisesMessage(ValidationError, msg):
grand_child.validate_unique()
|
21860258213514446a4ae9981973f8de62d5ffbb597dfdb235548bc09caf3ab1 | from unittest import mock
from django.apps.registry import Apps
from django.db import models
from django.db.models import signals
from django.dispatch import receiver
from django.test import SimpleTestCase, TestCase
from django.test.utils import isolate_apps
from .models import Author, Book, Car, Page, Person
class BaseSignalSetup:
def setUp(self):
# Save up the number of connected signals so that we can check at the
# end that all the signals we register get properly unregistered (#9989)
self.pre_signals = (
len(signals.pre_save.receivers),
len(signals.post_save.receivers),
len(signals.pre_delete.receivers),
len(signals.post_delete.receivers),
)
def tearDown(self):
# All our signals got disconnected properly.
post_signals = (
len(signals.pre_save.receivers),
len(signals.post_save.receivers),
len(signals.pre_delete.receivers),
len(signals.post_delete.receivers),
)
self.assertEqual(self.pre_signals, post_signals)
class SignalTests(BaseSignalSetup, TestCase):
def test_model_pre_init_and_post_init(self):
data = []
def pre_init_callback(sender, args, **kwargs):
data.append(kwargs["kwargs"])
signals.pre_init.connect(pre_init_callback)
def post_init_callback(sender, instance, **kwargs):
data.append(instance)
signals.post_init.connect(post_init_callback)
p1 = Person(first_name="John", last_name="Doe")
self.assertEqual(data, [{}, p1])
def test_save_signals(self):
data = []
def pre_save_handler(signal, sender, instance, **kwargs):
data.append((instance, sender, kwargs.get("raw", False)))
def post_save_handler(signal, sender, instance, **kwargs):
data.append(
(instance, sender, kwargs.get("created"), kwargs.get("raw", False))
)
signals.pre_save.connect(pre_save_handler, weak=False)
signals.post_save.connect(post_save_handler, weak=False)
try:
p1 = Person.objects.create(first_name="John", last_name="Smith")
self.assertEqual(
data,
[
(p1, Person, False),
(p1, Person, True, False),
],
)
data[:] = []
p1.first_name = "Tom"
p1.save()
self.assertEqual(
data,
[
(p1, Person, False),
(p1, Person, False, False),
],
)
data[:] = []
# Calling an internal method purely so that we can trigger a "raw" save.
p1.save_base(raw=True)
self.assertEqual(
data,
[
(p1, Person, True),
(p1, Person, False, True),
],
)
data[:] = []
p2 = Person(first_name="James", last_name="Jones")
p2.id = 99999
p2.save()
self.assertEqual(
data,
[
(p2, Person, False),
(p2, Person, True, False),
],
)
data[:] = []
p2.id = 99998
p2.save()
self.assertEqual(
data,
[
(p2, Person, False),
(p2, Person, True, False),
],
)
# The sender should stay the same when using defer().
data[:] = []
p3 = Person.objects.defer("first_name").get(pk=p1.pk)
p3.last_name = "Reese"
p3.save()
self.assertEqual(
data,
[
(p3, Person, False),
(p3, Person, False, False),
],
)
finally:
signals.pre_save.disconnect(pre_save_handler)
signals.post_save.disconnect(post_save_handler)
def test_delete_signals(self):
data = []
def pre_delete_handler(signal, sender, instance, origin, **kwargs):
data.append((instance, sender, instance.id is None, origin))
# #8285: signals can be any callable
class PostDeleteHandler:
def __init__(self, data):
self.data = data
def __call__(self, signal, sender, instance, origin, **kwargs):
self.data.append((instance, sender, instance.id is None, origin))
post_delete_handler = PostDeleteHandler(data)
signals.pre_delete.connect(pre_delete_handler, weak=False)
signals.post_delete.connect(post_delete_handler, weak=False)
try:
p1 = Person.objects.create(first_name="John", last_name="Smith")
p1.delete()
self.assertEqual(
data,
[
(p1, Person, False, p1),
(p1, Person, False, p1),
],
)
data[:] = []
p2 = Person(first_name="James", last_name="Jones")
p2.id = 99999
p2.save()
p2.id = 99998
p2.save()
p2.delete()
self.assertEqual(
data,
[
(p2, Person, False, p2),
(p2, Person, False, p2),
],
)
data[:] = []
self.assertQuerySetEqual(
Person.objects.all(),
[
"James Jones",
],
str,
)
finally:
signals.pre_delete.disconnect(pre_delete_handler)
signals.post_delete.disconnect(post_delete_handler)
def test_delete_signals_origin_model(self):
data = []
def pre_delete_handler(signal, sender, instance, origin, **kwargs):
data.append((sender, origin))
def post_delete_handler(signal, sender, instance, origin, **kwargs):
data.append((sender, origin))
person = Person.objects.create(first_name="John", last_name="Smith")
book = Book.objects.create(name="Rayuela")
Page.objects.create(text="Page 1", book=book)
Page.objects.create(text="Page 2", book=book)
signals.pre_delete.connect(pre_delete_handler, weak=False)
signals.post_delete.connect(post_delete_handler, weak=False)
try:
# Instance deletion.
person.delete()
self.assertEqual(data, [(Person, person), (Person, person)])
data[:] = []
# Cascade deletion.
book.delete()
self.assertEqual(
data,
[
(Page, book),
(Page, book),
(Book, book),
(Page, book),
(Page, book),
(Book, book),
],
)
finally:
signals.pre_delete.disconnect(pre_delete_handler)
signals.post_delete.disconnect(post_delete_handler)
def test_delete_signals_origin_queryset(self):
data = []
def pre_delete_handler(signal, sender, instance, origin, **kwargs):
data.append((sender, origin))
def post_delete_handler(signal, sender, instance, origin, **kwargs):
data.append((sender, origin))
Person.objects.create(first_name="John", last_name="Smith")
book = Book.objects.create(name="Rayuela")
Page.objects.create(text="Page 1", book=book)
Page.objects.create(text="Page 2", book=book)
signals.pre_delete.connect(pre_delete_handler, weak=False)
signals.post_delete.connect(post_delete_handler, weak=False)
try:
# Queryset deletion.
qs = Person.objects.all()
qs.delete()
self.assertEqual(data, [(Person, qs), (Person, qs)])
data[:] = []
# Cascade deletion.
qs = Book.objects.all()
qs.delete()
self.assertEqual(
data,
[
(Page, qs),
(Page, qs),
(Book, qs),
(Page, qs),
(Page, qs),
(Book, qs),
],
)
finally:
signals.pre_delete.disconnect(pre_delete_handler)
signals.post_delete.disconnect(post_delete_handler)
def test_decorators(self):
data = []
@receiver(signals.pre_save, weak=False)
def decorated_handler(signal, sender, instance, **kwargs):
data.append(instance)
@receiver(signals.pre_save, sender=Car, weak=False)
def decorated_handler_with_sender_arg(signal, sender, instance, **kwargs):
data.append(instance)
try:
c1 = Car.objects.create(make="Volkswagen", model="Passat")
self.assertEqual(data, [c1, c1])
finally:
signals.pre_save.disconnect(decorated_handler)
signals.pre_save.disconnect(decorated_handler_with_sender_arg, sender=Car)
def test_save_and_delete_signals_with_m2m(self):
data = []
def pre_save_handler(signal, sender, instance, **kwargs):
data.append("pre_save signal, %s" % instance)
if kwargs.get("raw"):
data.append("Is raw")
def post_save_handler(signal, sender, instance, **kwargs):
data.append("post_save signal, %s" % instance)
if "created" in kwargs:
if kwargs["created"]:
data.append("Is created")
else:
data.append("Is updated")
if kwargs.get("raw"):
data.append("Is raw")
def pre_delete_handler(signal, sender, instance, **kwargs):
data.append("pre_delete signal, %s" % instance)
data.append("instance.id is not None: %s" % (instance.id is not None))
def post_delete_handler(signal, sender, instance, **kwargs):
data.append("post_delete signal, %s" % instance)
data.append("instance.id is not None: %s" % (instance.id is not None))
signals.pre_save.connect(pre_save_handler, weak=False)
signals.post_save.connect(post_save_handler, weak=False)
signals.pre_delete.connect(pre_delete_handler, weak=False)
signals.post_delete.connect(post_delete_handler, weak=False)
try:
a1 = Author.objects.create(name="Neal Stephenson")
self.assertEqual(
data,
[
"pre_save signal, Neal Stephenson",
"post_save signal, Neal Stephenson",
"Is created",
],
)
data[:] = []
b1 = Book.objects.create(name="Snow Crash")
self.assertEqual(
data,
[
"pre_save signal, Snow Crash",
"post_save signal, Snow Crash",
"Is created",
],
)
data[:] = []
# Assigning and removing to/from m2m shouldn't generate an m2m signal.
b1.authors.set([a1])
self.assertEqual(data, [])
b1.authors.set([])
self.assertEqual(data, [])
finally:
signals.pre_save.disconnect(pre_save_handler)
signals.post_save.disconnect(post_save_handler)
signals.pre_delete.disconnect(pre_delete_handler)
signals.post_delete.disconnect(post_delete_handler)
def test_disconnect_in_dispatch(self):
"""
Signals that disconnect when being called don't mess future
dispatching.
"""
class Handler:
def __init__(self, param):
self.param = param
self._run = False
def __call__(self, signal, sender, **kwargs):
self._run = True
signal.disconnect(receiver=self, sender=sender)
a, b = Handler(1), Handler(2)
signals.post_save.connect(a, sender=Person, weak=False)
signals.post_save.connect(b, sender=Person, weak=False)
Person.objects.create(first_name="John", last_name="Smith")
self.assertTrue(a._run)
self.assertTrue(b._run)
self.assertEqual(signals.post_save.receivers, [])
@mock.patch("weakref.ref")
def test_lazy_model_signal(self, ref):
def callback(sender, args, **kwargs):
pass
signals.pre_init.connect(callback)
signals.pre_init.disconnect(callback)
self.assertTrue(ref.called)
ref.reset_mock()
signals.pre_init.connect(callback, weak=False)
signals.pre_init.disconnect(callback)
ref.assert_not_called()
@isolate_apps("signals", kwarg_name="apps")
def test_disconnect_model(self, apps):
received = []
def receiver(**kwargs):
received.append(kwargs)
class Created(models.Model):
pass
signals.post_init.connect(receiver, sender=Created, apps=apps)
try:
self.assertIs(
signals.post_init.disconnect(receiver, sender=Created, apps=apps),
True,
)
self.assertIs(
signals.post_init.disconnect(receiver, sender=Created, apps=apps),
False,
)
Created()
self.assertEqual(received, [])
finally:
signals.post_init.disconnect(receiver, sender=Created)
class LazyModelRefTests(BaseSignalSetup, SimpleTestCase):
def setUp(self):
super().setUp()
self.received = []
def receiver(self, **kwargs):
self.received.append(kwargs)
def test_invalid_sender_model_name(self):
msg = (
"Invalid model reference 'invalid'. String model references must be of the "
"form 'app_label.ModelName'."
)
with self.assertRaisesMessage(ValueError, msg):
signals.post_init.connect(self.receiver, sender="invalid")
def test_already_loaded_model(self):
signals.post_init.connect(self.receiver, sender="signals.Book", weak=False)
try:
instance = Book()
self.assertEqual(
self.received,
[{"signal": signals.post_init, "sender": Book, "instance": instance}],
)
finally:
signals.post_init.disconnect(self.receiver, sender=Book)
@isolate_apps("signals", kwarg_name="apps")
def test_not_loaded_model(self, apps):
signals.post_init.connect(
self.receiver, sender="signals.Created", weak=False, apps=apps
)
try:
class Created(models.Model):
pass
instance = Created()
self.assertEqual(
self.received,
[
{
"signal": signals.post_init,
"sender": Created,
"instance": instance,
}
],
)
finally:
signals.post_init.disconnect(self.receiver, sender=Created)
@isolate_apps("signals", kwarg_name="apps")
def test_disconnect_registered_model(self, apps):
received = []
def receiver(**kwargs):
received.append(kwargs)
class Created(models.Model):
pass
signals.post_init.connect(receiver, sender="signals.Created", apps=apps)
try:
self.assertIsNone(
signals.post_init.disconnect(
receiver, sender="signals.Created", apps=apps
)
)
self.assertIsNone(
signals.post_init.disconnect(
receiver, sender="signals.Created", apps=apps
)
)
Created()
self.assertEqual(received, [])
finally:
signals.post_init.disconnect(receiver, sender="signals.Created")
@isolate_apps("signals", kwarg_name="apps")
def test_disconnect_unregistered_model(self, apps):
received = []
def receiver(**kwargs):
received.append(kwargs)
signals.post_init.connect(receiver, sender="signals.Created", apps=apps)
try:
self.assertIsNone(
signals.post_init.disconnect(
receiver, sender="signals.Created", apps=apps
)
)
self.assertIsNone(
signals.post_init.disconnect(
receiver, sender="signals.Created", apps=apps
)
)
class Created(models.Model):
pass
Created()
self.assertEqual(received, [])
finally:
signals.post_init.disconnect(receiver, sender="signals.Created")
def test_register_model_class_senders_immediately(self):
"""
Model signals registered with model classes as senders don't use the
Apps.lazy_model_operation() mechanism.
"""
# Book isn't registered with apps2, so it will linger in
# apps2._pending_operations if ModelSignal does the wrong thing.
apps2 = Apps()
signals.post_init.connect(self.receiver, sender=Book, apps=apps2)
self.assertEqual(list(apps2._pending_operations), [])
|
b4661a22a788dd8758ed0d9debaa0d48ed6ecf8fda6ba463ae36753b1d0b4721 | from operator import attrgetter
from django.db import models
from django.test import SimpleTestCase, TestCase
from django.test.utils import isolate_apps
from .base_tests import BaseOrderWithRespectToTests
from .models import Answer, Dimension, Entity, Post, Question
class OrderWithRespectToBaseTests(BaseOrderWithRespectToTests, TestCase):
Answer = Answer
Post = Post
Question = Question
class OrderWithRespectToTests(SimpleTestCase):
@isolate_apps("order_with_respect_to")
def test_duplicate_order_field(self):
class Bar(models.Model):
class Meta:
app_label = "order_with_respect_to"
class Foo(models.Model):
bar = models.ForeignKey(Bar, models.CASCADE)
order = models.OrderWrt()
class Meta:
order_with_respect_to = "bar"
app_label = "order_with_respect_to"
count = 0
for field in Foo._meta.local_fields:
if isinstance(field, models.OrderWrt):
count += 1
self.assertEqual(count, 1)
class TestOrderWithRespectToOneToOnePK(TestCase):
def test_set_order(self):
e = Entity.objects.create()
d = Dimension.objects.create(entity=e)
c1 = d.component_set.create()
c2 = d.component_set.create()
d.set_component_order([c1.id, c2.id])
self.assertQuerySetEqual(
d.component_set.all(), [c1.id, c2.id], attrgetter("pk")
)
|
c6284d790cb3d934f098757999b200f6c60b996570c1ffa20ff6c665520847a2 | """
The tests are shared with contenttypes_tests and so shouldn't import or
reference any models directly. Subclasses should inherit django.test.TestCase.
"""
from operator import attrgetter
class BaseOrderWithRespectToTests:
databases = {"default", "other"}
# Hook to allow subclasses to run these tests with alternate models.
Answer = None
Post = None
Question = None
@classmethod
def setUpTestData(cls):
cls.q1 = cls.Question.objects.create(
text="Which Beatle starts with the letter 'R'?"
)
cls.Answer.objects.create(text="John", question=cls.q1)
cls.Answer.objects.create(text="Paul", question=cls.q1)
cls.Answer.objects.create(text="George", question=cls.q1)
cls.Answer.objects.create(text="Ringo", question=cls.q1)
def test_default_to_insertion_order(self):
# Answers will always be ordered in the order they were inserted.
self.assertQuerySetEqual(
self.q1.answer_set.all(),
[
"John",
"Paul",
"George",
"Ringo",
],
attrgetter("text"),
)
def test_previous_and_next_in_order(self):
# We can retrieve the answers related to a particular object, in the
# order they were created, once we have a particular object.
a1 = self.q1.answer_set.all()[0]
self.assertEqual(a1.text, "John")
self.assertEqual(a1.get_next_in_order().text, "Paul")
a2 = list(self.q1.answer_set.all())[-1]
self.assertEqual(a2.text, "Ringo")
self.assertEqual(a2.get_previous_in_order().text, "George")
def test_item_ordering(self):
# We can retrieve the ordering of the queryset from a particular item.
a1 = self.q1.answer_set.all()[1]
id_list = [o.pk for o in self.q1.answer_set.all()]
self.assertSequenceEqual(a1.question.get_answer_order(), id_list)
# It doesn't matter which answer we use to check the order, it will
# always be the same.
a2 = self.Answer.objects.create(text="Number five", question=self.q1)
self.assertEqual(
list(a1.question.get_answer_order()), list(a2.question.get_answer_order())
)
def test_set_order_unrelated_object(self):
"""An answer that's not related isn't updated."""
q = self.Question.objects.create(text="other")
a = self.Answer.objects.create(text="Number five", question=q)
self.q1.set_answer_order([o.pk for o in self.q1.answer_set.all()] + [a.pk])
self.assertEqual(self.Answer.objects.get(pk=a.pk)._order, 0)
def test_change_ordering(self):
# The ordering can be altered
a = self.Answer.objects.create(text="Number five", question=self.q1)
# Swap the last two items in the order list
id_list = [o.pk for o in self.q1.answer_set.all()]
x = id_list.pop()
id_list.insert(-1, x)
# By default, the ordering is different from the swapped version
self.assertNotEqual(list(a.question.get_answer_order()), id_list)
# Change the ordering to the swapped version -
# this changes the ordering of the queryset.
a.question.set_answer_order(id_list)
self.assertQuerySetEqual(
self.q1.answer_set.all(),
["John", "Paul", "George", "Number five", "Ringo"],
attrgetter("text"),
)
def test_recursive_ordering(self):
p1 = self.Post.objects.create(title="1")
p2 = self.Post.objects.create(title="2")
p1_1 = self.Post.objects.create(title="1.1", parent=p1)
p1_2 = self.Post.objects.create(title="1.2", parent=p1)
self.Post.objects.create(title="2.1", parent=p2)
p1_3 = self.Post.objects.create(title="1.3", parent=p1)
self.assertSequenceEqual(p1.get_post_order(), [p1_1.pk, p1_2.pk, p1_3.pk])
def test_delete_and_insert(self):
q1 = self.Question.objects.create(text="What is your favorite color?")
q2 = self.Question.objects.create(text="What color is it?")
a1 = self.Answer.objects.create(text="Blue", question=q1)
a2 = self.Answer.objects.create(text="Red", question=q1)
a3 = self.Answer.objects.create(text="Green", question=q1)
a4 = self.Answer.objects.create(text="Yellow", question=q1)
self.assertSequenceEqual(q1.answer_set.all(), [a1, a2, a3, a4])
a3.question = q2
a3.save()
a1.delete()
new_answer = self.Answer.objects.create(text="Black", question=q1)
self.assertSequenceEqual(q1.answer_set.all(), [a2, a4, new_answer])
def test_database_routing(self):
class WriteToOtherRouter:
def db_for_write(self, model, **hints):
return "other"
with self.settings(DATABASE_ROUTERS=[WriteToOtherRouter()]):
with self.assertNumQueries(0, using="default"), self.assertNumQueries(
1,
using="other",
):
self.q1.set_answer_order([3, 1, 2, 4])
|
a62904718c9c38c9d8757fe7654eede31a973df8b2937ab6e23db6a0c34b3399 | import datetime
import pickle
from io import StringIO
from operator import attrgetter
from unittest.mock import Mock
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core import management
from django.db import DEFAULT_DB_ALIAS, router, transaction
from django.db.models import signals
from django.db.utils import ConnectionRouter
from django.test import SimpleTestCase, TestCase, override_settings
from .models import Book, Person, Pet, Review, UserProfile
from .routers import AuthRouter, TestRouter, WriteRouter
class QueryTestCase(TestCase):
databases = {"default", "other"}
def test_db_selection(self):
"Querysets will use the default database by default"
self.assertEqual(Book.objects.db, DEFAULT_DB_ALIAS)
self.assertEqual(Book.objects.all().db, DEFAULT_DB_ALIAS)
self.assertEqual(Book.objects.using("other").db, "other")
self.assertEqual(Book.objects.db_manager("other").db, "other")
self.assertEqual(Book.objects.db_manager("other").all().db, "other")
def test_default_creation(self):
"Objects created on the default database don't leak onto other databases"
# Create a book on the default database using create()
Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
# Create a book on the default database using a save
dive = Book()
dive.title = "Dive into Python"
dive.published = datetime.date(2009, 5, 4)
dive.save()
# Book exists on the default database, but not on other database
try:
Book.objects.get(title="Pro Django")
Book.objects.using("default").get(title="Pro Django")
except Book.DoesNotExist:
self.fail('"Pro Django" should exist on default database')
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("other").get(title="Pro Django")
try:
Book.objects.get(title="Dive into Python")
Book.objects.using("default").get(title="Dive into Python")
except Book.DoesNotExist:
self.fail('"Dive into Python" should exist on default database')
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("other").get(title="Dive into Python")
def test_other_creation(self):
"Objects created on another database don't leak onto the default database"
# Create a book on the second database
Book.objects.using("other").create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
# Create a book on the default database using a save
dive = Book()
dive.title = "Dive into Python"
dive.published = datetime.date(2009, 5, 4)
dive.save(using="other")
# Book exists on the default database, but not on other database
try:
Book.objects.using("other").get(title="Pro Django")
except Book.DoesNotExist:
self.fail('"Pro Django" should exist on other database')
with self.assertRaises(Book.DoesNotExist):
Book.objects.get(title="Pro Django")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("default").get(title="Pro Django")
try:
Book.objects.using("other").get(title="Dive into Python")
except Book.DoesNotExist:
self.fail('"Dive into Python" should exist on other database')
with self.assertRaises(Book.DoesNotExist):
Book.objects.get(title="Dive into Python")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("default").get(title="Dive into Python")
def test_refresh(self):
dive = Book(title="Dive into Python", published=datetime.date(2009, 5, 4))
dive.save(using="other")
dive2 = Book.objects.using("other").get()
dive2.title = "Dive into Python (on default)"
dive2.save(using="default")
dive.refresh_from_db()
self.assertEqual(dive.title, "Dive into Python")
dive.refresh_from_db(using="default")
self.assertEqual(dive.title, "Dive into Python (on default)")
self.assertEqual(dive._state.db, "default")
def test_refresh_router_instance_hint(self):
router = Mock()
router.db_for_read.return_value = None
book = Book.objects.create(
title="Dive Into Python", published=datetime.date(1957, 10, 12)
)
with self.settings(DATABASE_ROUTERS=[router]):
book.refresh_from_db()
router.db_for_read.assert_called_once_with(Book, instance=book)
def test_basic_queries(self):
"Queries are constrained to a single database"
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
dive = Book.objects.using("other").get(published=datetime.date(2009, 5, 4))
self.assertEqual(dive.title, "Dive into Python")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("default").get(published=datetime.date(2009, 5, 4))
dive = Book.objects.using("other").get(title__icontains="dive")
self.assertEqual(dive.title, "Dive into Python")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("default").get(title__icontains="dive")
dive = Book.objects.using("other").get(title__iexact="dive INTO python")
self.assertEqual(dive.title, "Dive into Python")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("default").get(title__iexact="dive INTO python")
dive = Book.objects.using("other").get(published__year=2009)
self.assertEqual(dive.title, "Dive into Python")
self.assertEqual(dive.published, datetime.date(2009, 5, 4))
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("default").get(published__year=2009)
years = Book.objects.using("other").dates("published", "year")
self.assertEqual([o.year for o in years], [2009])
years = Book.objects.using("default").dates("published", "year")
self.assertEqual([o.year for o in years], [])
months = Book.objects.using("other").dates("published", "month")
self.assertEqual([o.month for o in months], [5])
months = Book.objects.using("default").dates("published", "month")
self.assertEqual([o.month for o in months], [])
def test_m2m_separation(self):
"M2M fields are constrained to a single database"
# Create a book and author on the default database
pro = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
marty = Person.objects.create(name="Marty Alchin")
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
mark = Person.objects.using("other").create(name="Mark Pilgrim")
# Save the author relations
pro.authors.set([marty])
dive.authors.set([mark])
# Inspect the m2m tables directly.
# There should be 1 entry in each database
self.assertEqual(Book.authors.through.objects.using("default").count(), 1)
self.assertEqual(Book.authors.through.objects.using("other").count(), 1)
# Queries work across m2m joins
self.assertEqual(
list(
Book.objects.using("default")
.filter(authors__name="Marty Alchin")
.values_list("title", flat=True)
),
["Pro Django"],
)
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="Marty Alchin")
.values_list("title", flat=True)
),
[],
)
self.assertEqual(
list(
Book.objects.using("default")
.filter(authors__name="Mark Pilgrim")
.values_list("title", flat=True)
),
[],
)
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="Mark Pilgrim")
.values_list("title", flat=True)
),
["Dive into Python"],
)
# Reget the objects to clear caches
dive = Book.objects.using("other").get(title="Dive into Python")
mark = Person.objects.using("other").get(name="Mark Pilgrim")
# Retrieve related object by descriptor. Related objects should be
# database-bound.
self.assertEqual(
list(dive.authors.values_list("name", flat=True)), ["Mark Pilgrim"]
)
self.assertEqual(
list(mark.book_set.values_list("title", flat=True)),
["Dive into Python"],
)
def test_m2m_forward_operations(self):
"M2M forward manipulations are all constrained to a single DB"
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
mark = Person.objects.using("other").create(name="Mark Pilgrim")
# Save the author relations
dive.authors.set([mark])
# Add a second author
john = Person.objects.using("other").create(name="John Smith")
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="John Smith")
.values_list("title", flat=True)
),
[],
)
dive.authors.add(john)
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="Mark Pilgrim")
.values_list("title", flat=True)
),
["Dive into Python"],
)
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="John Smith")
.values_list("title", flat=True)
),
["Dive into Python"],
)
# Remove the second author
dive.authors.remove(john)
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="Mark Pilgrim")
.values_list("title", flat=True)
),
["Dive into Python"],
)
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="John Smith")
.values_list("title", flat=True)
),
[],
)
# Clear all authors
dive.authors.clear()
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="Mark Pilgrim")
.values_list("title", flat=True)
),
[],
)
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="John Smith")
.values_list("title", flat=True)
),
[],
)
# Create an author through the m2m interface
dive.authors.create(name="Jane Brown")
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="Mark Pilgrim")
.values_list("title", flat=True)
),
[],
)
self.assertEqual(
list(
Book.objects.using("other")
.filter(authors__name="Jane Brown")
.values_list("title", flat=True)
),
["Dive into Python"],
)
def test_m2m_reverse_operations(self):
"M2M reverse manipulations are all constrained to a single DB"
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
mark = Person.objects.using("other").create(name="Mark Pilgrim")
# Save the author relations
dive.authors.set([mark])
# Create a second book on the other database
grease = Book.objects.using("other").create(
title="Greasemonkey Hacks", published=datetime.date(2005, 11, 1)
)
# Add a books to the m2m
mark.book_set.add(grease)
self.assertEqual(
list(
Person.objects.using("other")
.filter(book__title="Dive into Python")
.values_list("name", flat=True)
),
["Mark Pilgrim"],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(book__title="Greasemonkey Hacks")
.values_list("name", flat=True)
),
["Mark Pilgrim"],
)
# Remove a book from the m2m
mark.book_set.remove(grease)
self.assertEqual(
list(
Person.objects.using("other")
.filter(book__title="Dive into Python")
.values_list("name", flat=True)
),
["Mark Pilgrim"],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(book__title="Greasemonkey Hacks")
.values_list("name", flat=True)
),
[],
)
# Clear the books associated with mark
mark.book_set.clear()
self.assertEqual(
list(
Person.objects.using("other")
.filter(book__title="Dive into Python")
.values_list("name", flat=True)
),
[],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(book__title="Greasemonkey Hacks")
.values_list("name", flat=True)
),
[],
)
# Create a book through the m2m interface
mark.book_set.create(
title="Dive into HTML5", published=datetime.date(2020, 1, 1)
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(book__title="Dive into Python")
.values_list("name", flat=True)
),
[],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(book__title="Dive into HTML5")
.values_list("name", flat=True)
),
["Mark Pilgrim"],
)
def test_m2m_cross_database_protection(self):
"Operations that involve sharing M2M objects across databases raise an error"
# Create a book and author on the default database
pro = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
marty = Person.objects.create(name="Marty Alchin")
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
mark = Person.objects.using("other").create(name="Mark Pilgrim")
# Set a foreign key set with an object from a different database
msg = (
'Cannot assign "<Person: Marty Alchin>": the current database '
"router prevents this relation."
)
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using="default"):
marty.edited.set([pro, dive])
# Add to an m2m with an object from a different database
msg = (
'Cannot add "<Book: Dive into Python>": instance is on '
'database "default", value is on database "other"'
)
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using="default"):
marty.book_set.add(dive)
# Set a m2m with an object from a different database
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using="default"):
marty.book_set.set([pro, dive])
# Add to a reverse m2m with an object from a different database
msg = (
'Cannot add "<Person: Marty Alchin>": instance is on '
'database "other", value is on database "default"'
)
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using="other"):
dive.authors.add(marty)
# Set a reverse m2m with an object from a different database
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using="other"):
dive.authors.set([mark, marty])
def test_m2m_deletion(self):
"Cascaded deletions of m2m relations issue queries on the right database"
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
mark = Person.objects.using("other").create(name="Mark Pilgrim")
dive.authors.set([mark])
# Check the initial state
self.assertEqual(Person.objects.using("default").count(), 0)
self.assertEqual(Book.objects.using("default").count(), 0)
self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
self.assertEqual(Person.objects.using("other").count(), 1)
self.assertEqual(Book.objects.using("other").count(), 1)
self.assertEqual(Book.authors.through.objects.using("other").count(), 1)
# Delete the object on the other database
dive.delete(using="other")
self.assertEqual(Person.objects.using("default").count(), 0)
self.assertEqual(Book.objects.using("default").count(), 0)
self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
# The person still exists ...
self.assertEqual(Person.objects.using("other").count(), 1)
# ... but the book has been deleted
self.assertEqual(Book.objects.using("other").count(), 0)
# ... and the relationship object has also been deleted.
self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
# Now try deletion in the reverse direction. Set up the relation again
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
dive.authors.set([mark])
# Check the initial state
self.assertEqual(Person.objects.using("default").count(), 0)
self.assertEqual(Book.objects.using("default").count(), 0)
self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
self.assertEqual(Person.objects.using("other").count(), 1)
self.assertEqual(Book.objects.using("other").count(), 1)
self.assertEqual(Book.authors.through.objects.using("other").count(), 1)
# Delete the object on the other database
mark.delete(using="other")
self.assertEqual(Person.objects.using("default").count(), 0)
self.assertEqual(Book.objects.using("default").count(), 0)
self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
# The person has been deleted ...
self.assertEqual(Person.objects.using("other").count(), 0)
# ... but the book still exists
self.assertEqual(Book.objects.using("other").count(), 1)
# ... and the relationship object has been deleted.
self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
def test_foreign_key_separation(self):
"FK fields are constrained to a single database"
# Create a book and author on the default database
pro = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
george = Person.objects.create(name="George Vilches")
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
chris = Person.objects.using("other").create(name="Chris Mills")
# Save the author's favorite books
pro.editor = george
pro.save()
dive.editor = chris
dive.save()
pro = Book.objects.using("default").get(title="Pro Django")
self.assertEqual(pro.editor.name, "George Vilches")
dive = Book.objects.using("other").get(title="Dive into Python")
self.assertEqual(dive.editor.name, "Chris Mills")
# Queries work across foreign key joins
self.assertEqual(
list(
Person.objects.using("default")
.filter(edited__title="Pro Django")
.values_list("name", flat=True)
),
["George Vilches"],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Pro Django")
.values_list("name", flat=True)
),
[],
)
self.assertEqual(
list(
Person.objects.using("default")
.filter(edited__title="Dive into Python")
.values_list("name", flat=True)
),
[],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into Python")
.values_list("name", flat=True)
),
["Chris Mills"],
)
# Reget the objects to clear caches
chris = Person.objects.using("other").get(name="Chris Mills")
dive = Book.objects.using("other").get(title="Dive into Python")
# Retrieve related object by descriptor. Related objects should be
# database-bound.
self.assertEqual(
list(chris.edited.values_list("title", flat=True)), ["Dive into Python"]
)
def test_foreign_key_reverse_operations(self):
"FK reverse manipulations are all constrained to a single DB"
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
chris = Person.objects.using("other").create(name="Chris Mills")
# Save the author relations
dive.editor = chris
dive.save()
# Add a second book edited by chris
html5 = Book.objects.using("other").create(
title="Dive into HTML5", published=datetime.date(2010, 3, 15)
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into HTML5")
.values_list("name", flat=True)
),
[],
)
chris.edited.add(html5)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into HTML5")
.values_list("name", flat=True)
),
["Chris Mills"],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into Python")
.values_list("name", flat=True)
),
["Chris Mills"],
)
# Remove the second editor
chris.edited.remove(html5)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into HTML5")
.values_list("name", flat=True)
),
[],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into Python")
.values_list("name", flat=True)
),
["Chris Mills"],
)
# Clear all edited books
chris.edited.clear()
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into HTML5")
.values_list("name", flat=True)
),
[],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into Python")
.values_list("name", flat=True)
),
[],
)
# Create an author through the m2m interface
chris.edited.create(
title="Dive into Water", published=datetime.date(2010, 3, 15)
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into HTML5")
.values_list("name", flat=True)
),
[],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into Water")
.values_list("name", flat=True)
),
["Chris Mills"],
)
self.assertEqual(
list(
Person.objects.using("other")
.filter(edited__title="Dive into Python")
.values_list("name", flat=True)
),
[],
)
def test_foreign_key_cross_database_protection(self):
"Operations that involve sharing FK objects across databases raise an error"
# Create a book and author on the default database
pro = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
marty = Person.objects.create(name="Marty Alchin")
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
# Set a foreign key with an object from a different database
msg = (
'Cannot assign "<Person: Marty Alchin>": the current database '
"router prevents this relation."
)
with self.assertRaisesMessage(ValueError, msg):
dive.editor = marty
# Set a foreign key set with an object from a different database
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using="default"):
marty.edited.set([pro, dive])
# Add to a foreign key set with an object from a different database
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using="default"):
marty.edited.add(dive)
def test_foreign_key_deletion(self):
"""
Cascaded deletions of Foreign Key relations issue queries on the right
database.
"""
mark = Person.objects.using("other").create(name="Mark Pilgrim")
Pet.objects.using("other").create(name="Fido", owner=mark)
# Check the initial state
self.assertEqual(Person.objects.using("default").count(), 0)
self.assertEqual(Pet.objects.using("default").count(), 0)
self.assertEqual(Person.objects.using("other").count(), 1)
self.assertEqual(Pet.objects.using("other").count(), 1)
# Delete the person object, which will cascade onto the pet
mark.delete(using="other")
self.assertEqual(Person.objects.using("default").count(), 0)
self.assertEqual(Pet.objects.using("default").count(), 0)
# Both the pet and the person have been deleted from the right database
self.assertEqual(Person.objects.using("other").count(), 0)
self.assertEqual(Pet.objects.using("other").count(), 0)
def test_foreign_key_validation(self):
"ForeignKey.validate() uses the correct database"
mickey = Person.objects.using("other").create(name="Mickey")
pluto = Pet.objects.using("other").create(name="Pluto", owner=mickey)
self.assertIsNone(pluto.full_clean())
# Any router that accesses `model` in db_for_read() works here.
@override_settings(DATABASE_ROUTERS=[AuthRouter()])
def test_foreign_key_validation_with_router(self):
"""
ForeignKey.validate() passes `model` to db_for_read() even if
model_instance=None.
"""
mickey = Person.objects.create(name="Mickey")
owner_field = Pet._meta.get_field("owner")
self.assertEqual(owner_field.clean(mickey.pk, None), mickey.pk)
def test_o2o_separation(self):
"OneToOne fields are constrained to a single database"
# Create a user and profile on the default database
alice = User.objects.db_manager("default").create_user(
"alice", "[email protected]"
)
alice_profile = UserProfile.objects.using("default").create(
user=alice, flavor="chocolate"
)
# Create a user and profile on the other database
bob = User.objects.db_manager("other").create_user("bob", "[email protected]")
bob_profile = UserProfile.objects.using("other").create(
user=bob, flavor="crunchy frog"
)
# Retrieve related objects; queries should be database constrained
alice = User.objects.using("default").get(username="alice")
self.assertEqual(alice.userprofile.flavor, "chocolate")
bob = User.objects.using("other").get(username="bob")
self.assertEqual(bob.userprofile.flavor, "crunchy frog")
# Queries work across joins
self.assertEqual(
list(
User.objects.using("default")
.filter(userprofile__flavor="chocolate")
.values_list("username", flat=True)
),
["alice"],
)
self.assertEqual(
list(
User.objects.using("other")
.filter(userprofile__flavor="chocolate")
.values_list("username", flat=True)
),
[],
)
self.assertEqual(
list(
User.objects.using("default")
.filter(userprofile__flavor="crunchy frog")
.values_list("username", flat=True)
),
[],
)
self.assertEqual(
list(
User.objects.using("other")
.filter(userprofile__flavor="crunchy frog")
.values_list("username", flat=True)
),
["bob"],
)
# Reget the objects to clear caches
alice_profile = UserProfile.objects.using("default").get(flavor="chocolate")
bob_profile = UserProfile.objects.using("other").get(flavor="crunchy frog")
# Retrieve related object by descriptor. Related objects should be
# database-bound.
self.assertEqual(alice_profile.user.username, "alice")
self.assertEqual(bob_profile.user.username, "bob")
def test_o2o_cross_database_protection(self):
"Operations that involve sharing FK objects across databases raise an error"
# Create a user and profile on the default database
alice = User.objects.db_manager("default").create_user(
"alice", "[email protected]"
)
# Create a user and profile on the other database
bob = User.objects.db_manager("other").create_user("bob", "[email protected]")
# Set a one-to-one relation with an object from a different database
alice_profile = UserProfile.objects.using("default").create(
user=alice, flavor="chocolate"
)
msg = (
'Cannot assign "%r": the current database router prevents this '
"relation." % alice_profile
)
with self.assertRaisesMessage(ValueError, msg):
bob.userprofile = alice_profile
# BUT! if you assign a FK object when the base object hasn't
# been saved yet, you implicitly assign the database for the
# base object.
bob_profile = UserProfile.objects.using("other").create(
user=bob, flavor="crunchy frog"
)
new_bob_profile = UserProfile(flavor="spring surprise")
# assigning a profile requires an explicit pk as the object isn't saved
charlie = User(pk=51, username="charlie", email="[email protected]")
charlie.set_unusable_password()
# initially, no db assigned
self.assertIsNone(new_bob_profile._state.db)
self.assertIsNone(charlie._state.db)
# old object comes from 'other', so the new object is set to use 'other'...
new_bob_profile.user = bob
charlie.userprofile = bob_profile
self.assertEqual(new_bob_profile._state.db, "other")
self.assertEqual(charlie._state.db, "other")
# ... but it isn't saved yet
self.assertEqual(
list(User.objects.using("other").values_list("username", flat=True)),
["bob"],
)
self.assertEqual(
list(UserProfile.objects.using("other").values_list("flavor", flat=True)),
["crunchy frog"],
)
# When saved (no using required), new objects goes to 'other'
charlie.save()
bob_profile.save()
new_bob_profile.save()
self.assertEqual(
list(User.objects.using("default").values_list("username", flat=True)),
["alice"],
)
self.assertEqual(
list(User.objects.using("other").values_list("username", flat=True)),
["bob", "charlie"],
)
self.assertEqual(
list(UserProfile.objects.using("default").values_list("flavor", flat=True)),
["chocolate"],
)
self.assertEqual(
list(UserProfile.objects.using("other").values_list("flavor", flat=True)),
["crunchy frog", "spring surprise"],
)
# This also works if you assign the O2O relation in the constructor
denise = User.objects.db_manager("other").create_user(
"denise", "[email protected]"
)
denise_profile = UserProfile(flavor="tofu", user=denise)
self.assertEqual(denise_profile._state.db, "other")
# ... but it isn't saved yet
self.assertEqual(
list(UserProfile.objects.using("default").values_list("flavor", flat=True)),
["chocolate"],
)
self.assertEqual(
list(UserProfile.objects.using("other").values_list("flavor", flat=True)),
["crunchy frog", "spring surprise"],
)
# When saved, the new profile goes to 'other'
denise_profile.save()
self.assertEqual(
list(UserProfile.objects.using("default").values_list("flavor", flat=True)),
["chocolate"],
)
self.assertEqual(
list(UserProfile.objects.using("other").values_list("flavor", flat=True)),
["crunchy frog", "spring surprise", "tofu"],
)
def test_generic_key_separation(self):
"Generic fields are constrained to a single database"
# Create a book and author on the default database
pro = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
review1 = Review.objects.create(source="Python Monthly", content_object=pro)
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
review2 = Review.objects.using("other").create(
source="Python Weekly", content_object=dive
)
review1 = Review.objects.using("default").get(source="Python Monthly")
self.assertEqual(review1.content_object.title, "Pro Django")
review2 = Review.objects.using("other").get(source="Python Weekly")
self.assertEqual(review2.content_object.title, "Dive into Python")
# Reget the objects to clear caches
dive = Book.objects.using("other").get(title="Dive into Python")
# Retrieve related object by descriptor. Related objects should be
# database-bound.
self.assertEqual(
list(dive.reviews.values_list("source", flat=True)), ["Python Weekly"]
)
def test_generic_key_reverse_operations(self):
"Generic reverse manipulations are all constrained to a single DB"
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
temp = Book.objects.using("other").create(
title="Temp", published=datetime.date(2009, 5, 4)
)
review1 = Review.objects.using("other").create(
source="Python Weekly", content_object=dive
)
review2 = Review.objects.using("other").create(
source="Python Monthly", content_object=temp
)
self.assertEqual(
list(
Review.objects.using("default")
.filter(object_id=dive.pk)
.values_list("source", flat=True)
),
[],
)
self.assertEqual(
list(
Review.objects.using("other")
.filter(object_id=dive.pk)
.values_list("source", flat=True)
),
["Python Weekly"],
)
# Add a second review
dive.reviews.add(review2)
self.assertEqual(
list(
Review.objects.using("default")
.filter(object_id=dive.pk)
.values_list("source", flat=True)
),
[],
)
self.assertEqual(
list(
Review.objects.using("other")
.filter(object_id=dive.pk)
.values_list("source", flat=True)
),
["Python Monthly", "Python Weekly"],
)
# Remove the second author
dive.reviews.remove(review1)
self.assertEqual(
list(
Review.objects.using("default")
.filter(object_id=dive.pk)
.values_list("source", flat=True)
),
[],
)
self.assertEqual(
list(
Review.objects.using("other")
.filter(object_id=dive.pk)
.values_list("source", flat=True)
),
["Python Monthly"],
)
# Clear all reviews
dive.reviews.clear()
self.assertEqual(
list(
Review.objects.using("default")
.filter(object_id=dive.pk)
.values_list("source", flat=True)
),
[],
)
self.assertEqual(
list(
Review.objects.using("other")
.filter(object_id=dive.pk)
.values_list("source", flat=True)
),
[],
)
# Create an author through the generic interface
dive.reviews.create(source="Python Daily")
self.assertEqual(
list(
Review.objects.using("default")
.filter(object_id=dive.pk)
.values_list("source", flat=True)
),
[],
)
self.assertEqual(
list(
Review.objects.using("other")
.filter(object_id=dive.pk)
.values_list("source", flat=True)
),
["Python Daily"],
)
def test_generic_key_cross_database_protection(self):
"""
Operations that involve sharing generic key objects across databases
raise an error.
"""
# Create a book and author on the default database
pro = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
review1 = Review.objects.create(source="Python Monthly", content_object=pro)
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
Review.objects.using("other").create(
source="Python Weekly", content_object=dive
)
# Set a foreign key with an object from a different database
msg = (
'Cannot assign "<ContentType: multiple_database | book>": the '
"current database router prevents this relation."
)
with self.assertRaisesMessage(ValueError, msg):
review1.content_object = dive
# Add to a foreign key set with an object from a different database
msg = (
"<Review: Python Monthly> instance isn't saved. "
"Use bulk=False or save the object first."
)
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using="other"):
dive.reviews.add(review1)
# BUT! if you assign a FK object when the base object hasn't
# been saved yet, you implicitly assign the database for the
# base object.
review3 = Review(source="Python Daily")
# initially, no db assigned
self.assertIsNone(review3._state.db)
# Dive comes from 'other', so review3 is set to use 'other'...
review3.content_object = dive
self.assertEqual(review3._state.db, "other")
# ... but it isn't saved yet
self.assertEqual(
list(
Review.objects.using("default")
.filter(object_id=pro.pk)
.values_list("source", flat=True)
),
["Python Monthly"],
)
self.assertEqual(
list(
Review.objects.using("other")
.filter(object_id=dive.pk)
.values_list("source", flat=True)
),
["Python Weekly"],
)
# When saved, John goes to 'other'
review3.save()
self.assertEqual(
list(
Review.objects.using("default")
.filter(object_id=pro.pk)
.values_list("source", flat=True)
),
["Python Monthly"],
)
self.assertEqual(
list(
Review.objects.using("other")
.filter(object_id=dive.pk)
.values_list("source", flat=True)
),
["Python Daily", "Python Weekly"],
)
def test_generic_key_deletion(self):
"""
Cascaded deletions of Generic Key relations issue queries on the right
database.
"""
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
Review.objects.using("other").create(
source="Python Weekly", content_object=dive
)
# Check the initial state
self.assertEqual(Book.objects.using("default").count(), 0)
self.assertEqual(Review.objects.using("default").count(), 0)
self.assertEqual(Book.objects.using("other").count(), 1)
self.assertEqual(Review.objects.using("other").count(), 1)
# Delete the Book object, which will cascade onto the pet
dive.delete(using="other")
self.assertEqual(Book.objects.using("default").count(), 0)
self.assertEqual(Review.objects.using("default").count(), 0)
# Both the pet and the person have been deleted from the right database
self.assertEqual(Book.objects.using("other").count(), 0)
self.assertEqual(Review.objects.using("other").count(), 0)
def test_ordering(self):
"get_next_by_XXX commands stick to a single database"
Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
learn = Book.objects.using("other").create(
title="Learning Python", published=datetime.date(2008, 7, 16)
)
self.assertEqual(learn.get_next_by_published().title, "Dive into Python")
self.assertEqual(dive.get_previous_by_published().title, "Learning Python")
def test_raw(self):
"test the raw() method across databases"
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
val = Book.objects.db_manager("other").raw(
"SELECT id FROM multiple_database_book"
)
self.assertQuerySetEqual(val, [dive.pk], attrgetter("pk"))
val = Book.objects.raw("SELECT id FROM multiple_database_book").using("other")
self.assertQuerySetEqual(val, [dive.pk], attrgetter("pk"))
def test_select_related(self):
"""
Database assignment is retained if an object is retrieved with
select_related().
"""
# Create a book and author on the other database
mark = Person.objects.using("other").create(name="Mark Pilgrim")
Book.objects.using("other").create(
title="Dive into Python",
published=datetime.date(2009, 5, 4),
editor=mark,
)
# Retrieve the Person using select_related()
book = (
Book.objects.using("other")
.select_related("editor")
.get(title="Dive into Python")
)
# The editor instance should have a db state
self.assertEqual(book.editor._state.db, "other")
def test_subquery(self):
"""Make sure as_sql works with subqueries and primary/replica."""
sub = Person.objects.using("other").filter(name="fff")
qs = Book.objects.filter(editor__in=sub)
# When you call __str__ on the query object, it doesn't know about using
# so it falls back to the default. If the subquery explicitly uses a
# different database, an error should be raised.
msg = (
"Subqueries aren't allowed across different databases. Force the "
"inner query to be evaluated using `list(inner_query)`."
)
with self.assertRaisesMessage(ValueError, msg):
str(qs.query)
# Evaluating the query shouldn't work, either
with self.assertRaisesMessage(ValueError, msg):
for obj in qs:
pass
def test_related_manager(self):
"Related managers return managers, not querysets"
mark = Person.objects.using("other").create(name="Mark Pilgrim")
# extra_arg is removed by the BookManager's implementation of
# create(); but the BookManager's implementation won't get called
# unless edited returns a Manager, not a queryset
mark.book_set.create(
title="Dive into Python",
published=datetime.date(2009, 5, 4),
extra_arg=True,
)
mark.book_set.get_or_create(
title="Dive into Python",
published=datetime.date(2009, 5, 4),
extra_arg=True,
)
mark.edited.create(
title="Dive into Water", published=datetime.date(2009, 5, 4), extra_arg=True
)
mark.edited.get_or_create(
title="Dive into Water", published=datetime.date(2009, 5, 4), extra_arg=True
)
class ConnectionRouterTestCase(SimpleTestCase):
@override_settings(
DATABASE_ROUTERS=[
"multiple_database.tests.TestRouter",
"multiple_database.tests.WriteRouter",
]
)
def test_router_init_default(self):
connection_router = ConnectionRouter()
self.assertEqual(
[r.__class__.__name__ for r in connection_router.routers],
["TestRouter", "WriteRouter"],
)
def test_router_init_arg(self):
connection_router = ConnectionRouter(
[
"multiple_database.tests.TestRouter",
"multiple_database.tests.WriteRouter",
]
)
self.assertEqual(
[r.__class__.__name__ for r in connection_router.routers],
["TestRouter", "WriteRouter"],
)
# Init with instances instead of strings
connection_router = ConnectionRouter([TestRouter(), WriteRouter()])
self.assertEqual(
[r.__class__.__name__ for r in connection_router.routers],
["TestRouter", "WriteRouter"],
)
# Make the 'other' database appear to be a replica of the 'default'
@override_settings(DATABASE_ROUTERS=[TestRouter()])
class RouterTestCase(TestCase):
databases = {"default", "other"}
def test_db_selection(self):
"Querysets obey the router for db suggestions"
self.assertEqual(Book.objects.db, "other")
self.assertEqual(Book.objects.all().db, "other")
self.assertEqual(Book.objects.using("default").db, "default")
self.assertEqual(Book.objects.db_manager("default").db, "default")
self.assertEqual(Book.objects.db_manager("default").all().db, "default")
def test_migrate_selection(self):
"Synchronization behavior is predictable"
self.assertTrue(router.allow_migrate_model("default", User))
self.assertTrue(router.allow_migrate_model("default", Book))
self.assertTrue(router.allow_migrate_model("other", User))
self.assertTrue(router.allow_migrate_model("other", Book))
with override_settings(DATABASE_ROUTERS=[TestRouter(), AuthRouter()]):
# Add the auth router to the chain. TestRouter is a universal
# synchronizer, so it should have no effect.
self.assertTrue(router.allow_migrate_model("default", User))
self.assertTrue(router.allow_migrate_model("default", Book))
self.assertTrue(router.allow_migrate_model("other", User))
self.assertTrue(router.allow_migrate_model("other", Book))
with override_settings(DATABASE_ROUTERS=[AuthRouter(), TestRouter()]):
# Now check what happens if the router order is reversed.
self.assertFalse(router.allow_migrate_model("default", User))
self.assertTrue(router.allow_migrate_model("default", Book))
self.assertTrue(router.allow_migrate_model("other", User))
self.assertTrue(router.allow_migrate_model("other", Book))
def test_partial_router(self):
"A router can choose to implement a subset of methods"
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
# First check the baseline behavior.
self.assertEqual(router.db_for_read(User), "other")
self.assertEqual(router.db_for_read(Book), "other")
self.assertEqual(router.db_for_write(User), "default")
self.assertEqual(router.db_for_write(Book), "default")
self.assertTrue(router.allow_relation(dive, dive))
self.assertTrue(router.allow_migrate_model("default", User))
self.assertTrue(router.allow_migrate_model("default", Book))
with override_settings(
DATABASE_ROUTERS=[WriteRouter(), AuthRouter(), TestRouter()]
):
self.assertEqual(router.db_for_read(User), "default")
self.assertEqual(router.db_for_read(Book), "other")
self.assertEqual(router.db_for_write(User), "writer")
self.assertEqual(router.db_for_write(Book), "writer")
self.assertTrue(router.allow_relation(dive, dive))
self.assertFalse(router.allow_migrate_model("default", User))
self.assertTrue(router.allow_migrate_model("default", Book))
def test_database_routing(self):
marty = Person.objects.using("default").create(name="Marty Alchin")
pro = Book.objects.using("default").create(
title="Pro Django",
published=datetime.date(2008, 12, 16),
editor=marty,
)
pro.authors.set([marty])
# Create a book and author on the other database
Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
# An update query will be routed to the default database
Book.objects.filter(title="Pro Django").update(pages=200)
with self.assertRaises(Book.DoesNotExist):
# By default, the get query will be directed to 'other'
Book.objects.get(title="Pro Django")
# But the same query issued explicitly at a database will work.
pro = Book.objects.using("default").get(title="Pro Django")
# The update worked.
self.assertEqual(pro.pages, 200)
# An update query with an explicit using clause will be routed
# to the requested database.
Book.objects.using("other").filter(title="Dive into Python").update(pages=300)
self.assertEqual(Book.objects.get(title="Dive into Python").pages, 300)
# Related object queries stick to the same database
# as the original object, regardless of the router
self.assertEqual(
list(pro.authors.values_list("name", flat=True)), ["Marty Alchin"]
)
self.assertEqual(pro.editor.name, "Marty Alchin")
# get_or_create is a special case. The get needs to be targeted at
# the write database in order to avoid potential transaction
# consistency problems
book, created = Book.objects.get_or_create(title="Pro Django")
self.assertFalse(created)
book, created = Book.objects.get_or_create(
title="Dive Into Python", defaults={"published": datetime.date(2009, 5, 4)}
)
self.assertTrue(created)
# Check the head count of objects
self.assertEqual(Book.objects.using("default").count(), 2)
self.assertEqual(Book.objects.using("other").count(), 1)
# If a database isn't specified, the read database is used
self.assertEqual(Book.objects.count(), 1)
# A delete query will also be routed to the default database
Book.objects.filter(pages__gt=150).delete()
# The default database has lost the book.
self.assertEqual(Book.objects.using("default").count(), 1)
self.assertEqual(Book.objects.using("other").count(), 1)
def test_invalid_set_foreign_key_assignment(self):
marty = Person.objects.using("default").create(name="Marty Alchin")
dive = Book.objects.using("other").create(
title="Dive into Python",
published=datetime.date(2009, 5, 4),
)
# Set a foreign key set with an object from a different database
msg = (
"<Book: Dive into Python> instance isn't saved. Use bulk=False or save the "
"object first."
)
with self.assertRaisesMessage(ValueError, msg):
marty.edited.set([dive])
def test_foreign_key_cross_database_protection(self):
"Foreign keys can cross databases if they two databases have a common source"
# Create a book and author on the default database
pro = Book.objects.using("default").create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
marty = Person.objects.using("default").create(name="Marty Alchin")
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
mark = Person.objects.using("other").create(name="Mark Pilgrim")
# Set a foreign key with an object from a different database
dive.editor = marty
# Database assignments of original objects haven't changed...
self.assertEqual(marty._state.db, "default")
self.assertEqual(pro._state.db, "default")
self.assertEqual(dive._state.db, "other")
self.assertEqual(mark._state.db, "other")
# ... but they will when the affected object is saved.
dive.save()
self.assertEqual(dive._state.db, "default")
# ...and the source database now has a copy of any object saved
Book.objects.using("default").get(title="Dive into Python").delete()
# This isn't a real primary/replica database, so restore the original from other
dive = Book.objects.using("other").get(title="Dive into Python")
self.assertEqual(dive._state.db, "other")
# Set a foreign key set with an object from a different database
marty.edited.set([pro, dive], bulk=False)
# Assignment implies a save, so database assignments of original
# objects have changed...
self.assertEqual(marty._state.db, "default")
self.assertEqual(pro._state.db, "default")
self.assertEqual(dive._state.db, "default")
self.assertEqual(mark._state.db, "other")
# ...and the source database now has a copy of any object saved
Book.objects.using("default").get(title="Dive into Python").delete()
# This isn't a real primary/replica database, so restore the original from other
dive = Book.objects.using("other").get(title="Dive into Python")
self.assertEqual(dive._state.db, "other")
# Add to a foreign key set with an object from a different database
marty.edited.add(dive, bulk=False)
# Add implies a save, so database assignments of original objects have
# changed...
self.assertEqual(marty._state.db, "default")
self.assertEqual(pro._state.db, "default")
self.assertEqual(dive._state.db, "default")
self.assertEqual(mark._state.db, "other")
# ...and the source database now has a copy of any object saved
Book.objects.using("default").get(title="Dive into Python").delete()
# This isn't a real primary/replica database, so restore the original from other
dive = Book.objects.using("other").get(title="Dive into Python")
# If you assign a FK object when the base object hasn't
# been saved yet, you implicitly assign the database for the
# base object.
chris = Person(name="Chris Mills")
html5 = Book(title="Dive into HTML5", published=datetime.date(2010, 3, 15))
# initially, no db assigned
self.assertIsNone(chris._state.db)
self.assertIsNone(html5._state.db)
# old object comes from 'other', so the new object is set to use the
# source of 'other'...
self.assertEqual(dive._state.db, "other")
chris.save()
dive.editor = chris
html5.editor = mark
self.assertEqual(dive._state.db, "other")
self.assertEqual(mark._state.db, "other")
self.assertEqual(chris._state.db, "default")
self.assertEqual(html5._state.db, "default")
# This also works if you assign the FK in the constructor
water = Book(
title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark
)
self.assertEqual(water._state.db, "default")
# For the remainder of this test, create a copy of 'mark' in the
# 'default' database to prevent integrity errors on backends that
# don't defer constraints checks until the end of the transaction
mark.save(using="default")
# This moved 'mark' in the 'default' database, move it back in 'other'
mark.save(using="other")
self.assertEqual(mark._state.db, "other")
# If you create an object through a FK relation, it will be
# written to the write database, even if the original object
# was on the read database
cheesecake = mark.edited.create(
title="Dive into Cheesecake", published=datetime.date(2010, 3, 15)
)
self.assertEqual(cheesecake._state.db, "default")
# Same goes for get_or_create, regardless of whether getting or creating
cheesecake, created = mark.edited.get_or_create(
title="Dive into Cheesecake",
published=datetime.date(2010, 3, 15),
)
self.assertEqual(cheesecake._state.db, "default")
puddles, created = mark.edited.get_or_create(
title="Dive into Puddles", published=datetime.date(2010, 3, 15)
)
self.assertEqual(puddles._state.db, "default")
def test_m2m_cross_database_protection(self):
"M2M relations can cross databases if the database share a source"
# Create books and authors on the inverse to the usual database
pro = Book.objects.using("other").create(
pk=1, title="Pro Django", published=datetime.date(2008, 12, 16)
)
marty = Person.objects.using("other").create(pk=1, name="Marty Alchin")
dive = Book.objects.using("default").create(
pk=2, title="Dive into Python", published=datetime.date(2009, 5, 4)
)
mark = Person.objects.using("default").create(pk=2, name="Mark Pilgrim")
# Now save back onto the usual database.
# This simulates primary/replica - the objects exist on both database,
# but the _state.db is as it is for all other tests.
pro.save(using="default")
marty.save(using="default")
dive.save(using="other")
mark.save(using="other")
# We have 2 of both types of object on both databases
self.assertEqual(Book.objects.using("default").count(), 2)
self.assertEqual(Book.objects.using("other").count(), 2)
self.assertEqual(Person.objects.using("default").count(), 2)
self.assertEqual(Person.objects.using("other").count(), 2)
# Set a m2m set with an object from a different database
marty.book_set.set([pro, dive])
# Database assignments don't change
self.assertEqual(marty._state.db, "default")
self.assertEqual(pro._state.db, "default")
self.assertEqual(dive._state.db, "other")
self.assertEqual(mark._state.db, "other")
# All m2m relations should be saved on the default database
self.assertEqual(Book.authors.through.objects.using("default").count(), 2)
self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
# Reset relations
Book.authors.through.objects.using("default").delete()
# Add to an m2m with an object from a different database
marty.book_set.add(dive)
# Database assignments don't change
self.assertEqual(marty._state.db, "default")
self.assertEqual(pro._state.db, "default")
self.assertEqual(dive._state.db, "other")
self.assertEqual(mark._state.db, "other")
# All m2m relations should be saved on the default database
self.assertEqual(Book.authors.through.objects.using("default").count(), 1)
self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
# Reset relations
Book.authors.through.objects.using("default").delete()
# Set a reverse m2m with an object from a different database
dive.authors.set([mark, marty])
# Database assignments don't change
self.assertEqual(marty._state.db, "default")
self.assertEqual(pro._state.db, "default")
self.assertEqual(dive._state.db, "other")
self.assertEqual(mark._state.db, "other")
# All m2m relations should be saved on the default database
self.assertEqual(Book.authors.through.objects.using("default").count(), 2)
self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
# Reset relations
Book.authors.through.objects.using("default").delete()
self.assertEqual(Book.authors.through.objects.using("default").count(), 0)
self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
# Add to a reverse m2m with an object from a different database
dive.authors.add(marty)
# Database assignments don't change
self.assertEqual(marty._state.db, "default")
self.assertEqual(pro._state.db, "default")
self.assertEqual(dive._state.db, "other")
self.assertEqual(mark._state.db, "other")
# All m2m relations should be saved on the default database
self.assertEqual(Book.authors.through.objects.using("default").count(), 1)
self.assertEqual(Book.authors.through.objects.using("other").count(), 0)
# If you create an object through a M2M relation, it will be
# written to the write database, even if the original object
# was on the read database
alice = dive.authors.create(name="Alice", pk=3)
self.assertEqual(alice._state.db, "default")
# Same goes for get_or_create, regardless of whether getting or creating
alice, created = dive.authors.get_or_create(name="Alice")
self.assertEqual(alice._state.db, "default")
bob, created = dive.authors.get_or_create(name="Bob", defaults={"pk": 4})
self.assertEqual(bob._state.db, "default")
def test_o2o_cross_database_protection(self):
"Operations that involve sharing FK objects across databases raise an error"
# Create a user and profile on the default database
alice = User.objects.db_manager("default").create_user(
"alice", "[email protected]"
)
# Create a user and profile on the other database
bob = User.objects.db_manager("other").create_user("bob", "[email protected]")
# Set a one-to-one relation with an object from a different database
alice_profile = UserProfile.objects.create(user=alice, flavor="chocolate")
bob.userprofile = alice_profile
# Database assignments of original objects haven't changed...
self.assertEqual(alice._state.db, "default")
self.assertEqual(alice_profile._state.db, "default")
self.assertEqual(bob._state.db, "other")
# ... but they will when the affected object is saved.
bob.save()
self.assertEqual(bob._state.db, "default")
def test_generic_key_cross_database_protection(self):
"Generic Key operations can span databases if they share a source"
# Create a book and author on the default database
pro = Book.objects.using("default").create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
review1 = Review.objects.using("default").create(
source="Python Monthly", content_object=pro
)
# Create a book and author on the other database
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
review2 = Review.objects.using("other").create(
source="Python Weekly", content_object=dive
)
# Set a generic foreign key with an object from a different database
review1.content_object = dive
# Database assignments of original objects haven't changed...
self.assertEqual(pro._state.db, "default")
self.assertEqual(review1._state.db, "default")
self.assertEqual(dive._state.db, "other")
self.assertEqual(review2._state.db, "other")
# ... but they will when the affected object is saved.
dive.save()
self.assertEqual(review1._state.db, "default")
self.assertEqual(dive._state.db, "default")
# ...and the source database now has a copy of any object saved
Book.objects.using("default").get(title="Dive into Python").delete()
# This isn't a real primary/replica database, so restore the original from other
dive = Book.objects.using("other").get(title="Dive into Python")
self.assertEqual(dive._state.db, "other")
# Add to a generic foreign key set with an object from a different database
dive.reviews.add(review1)
# Database assignments of original objects haven't changed...
self.assertEqual(pro._state.db, "default")
self.assertEqual(review1._state.db, "default")
self.assertEqual(dive._state.db, "other")
self.assertEqual(review2._state.db, "other")
# ... but they will when the affected object is saved.
dive.save()
self.assertEqual(dive._state.db, "default")
# ...and the source database now has a copy of any object saved
Book.objects.using("default").get(title="Dive into Python").delete()
# BUT! if you assign a FK object when the base object hasn't
# been saved yet, you implicitly assign the database for the
# base object.
review3 = Review(source="Python Daily")
# initially, no db assigned
self.assertIsNone(review3._state.db)
# Dive comes from 'other', so review3 is set to use the source of 'other'...
review3.content_object = dive
self.assertEqual(review3._state.db, "default")
# If you create an object through a M2M relation, it will be
# written to the write database, even if the original object
# was on the read database
dive = Book.objects.using("other").get(title="Dive into Python")
nyt = dive.reviews.create(source="New York Times", content_object=dive)
self.assertEqual(nyt._state.db, "default")
def test_m2m_managers(self):
"M2M relations are represented by managers, and can be controlled like managers"
pro = Book.objects.using("other").create(
pk=1, title="Pro Django", published=datetime.date(2008, 12, 16)
)
marty = Person.objects.using("other").create(pk=1, name="Marty Alchin")
self.assertEqual(pro.authors.db, "other")
self.assertEqual(pro.authors.db_manager("default").db, "default")
self.assertEqual(pro.authors.db_manager("default").all().db, "default")
self.assertEqual(marty.book_set.db, "other")
self.assertEqual(marty.book_set.db_manager("default").db, "default")
self.assertEqual(marty.book_set.db_manager("default").all().db, "default")
def test_foreign_key_managers(self):
"""
FK reverse relations are represented by managers, and can be controlled
like managers.
"""
marty = Person.objects.using("other").create(pk=1, name="Marty Alchin")
Book.objects.using("other").create(
pk=1,
title="Pro Django",
published=datetime.date(2008, 12, 16),
editor=marty,
)
self.assertEqual(marty.edited.db, "other")
self.assertEqual(marty.edited.db_manager("default").db, "default")
self.assertEqual(marty.edited.db_manager("default").all().db, "default")
def test_generic_key_managers(self):
"""
Generic key relations are represented by managers, and can be
controlled like managers.
"""
pro = Book.objects.using("other").create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
Review.objects.using("other").create(
source="Python Monthly", content_object=pro
)
self.assertEqual(pro.reviews.db, "other")
self.assertEqual(pro.reviews.db_manager("default").db, "default")
self.assertEqual(pro.reviews.db_manager("default").all().db, "default")
def test_subquery(self):
"""Make sure as_sql works with subqueries and primary/replica."""
# Create a book and author on the other database
mark = Person.objects.using("other").create(name="Mark Pilgrim")
Book.objects.using("other").create(
title="Dive into Python",
published=datetime.date(2009, 5, 4),
editor=mark,
)
sub = Person.objects.filter(name="Mark Pilgrim")
qs = Book.objects.filter(editor__in=sub)
# When you call __str__ on the query object, it doesn't know about using
# so it falls back to the default. Don't let routing instructions
# force the subquery to an incompatible database.
str(qs.query)
# If you evaluate the query, it should work, running on 'other'
self.assertEqual(list(qs.values_list("title", flat=True)), ["Dive into Python"])
def test_deferred_models(self):
mark_def = Person.objects.using("default").create(name="Mark Pilgrim")
mark_other = Person.objects.using("other").create(name="Mark Pilgrim")
orig_b = Book.objects.using("other").create(
title="Dive into Python",
published=datetime.date(2009, 5, 4),
editor=mark_other,
)
b = Book.objects.using("other").only("title").get(pk=orig_b.pk)
self.assertEqual(b.published, datetime.date(2009, 5, 4))
b = Book.objects.using("other").only("title").get(pk=orig_b.pk)
b.editor = mark_def
b.save(using="default")
self.assertEqual(
Book.objects.using("default").get(pk=b.pk).published,
datetime.date(2009, 5, 4),
)
@override_settings(DATABASE_ROUTERS=[AuthRouter()])
class AuthTestCase(TestCase):
databases = {"default", "other"}
def test_auth_manager(self):
"The methods on the auth manager obey database hints"
# Create one user using default allocation policy
User.objects.create_user("alice", "[email protected]")
# Create another user, explicitly specifying the database
User.objects.db_manager("default").create_user("bob", "[email protected]")
# The second user only exists on the other database
alice = User.objects.using("other").get(username="alice")
self.assertEqual(alice.username, "alice")
self.assertEqual(alice._state.db, "other")
with self.assertRaises(User.DoesNotExist):
User.objects.using("default").get(username="alice")
# The second user only exists on the default database
bob = User.objects.using("default").get(username="bob")
self.assertEqual(bob.username, "bob")
self.assertEqual(bob._state.db, "default")
with self.assertRaises(User.DoesNotExist):
User.objects.using("other").get(username="bob")
# That is... there is one user on each database
self.assertEqual(User.objects.using("default").count(), 1)
self.assertEqual(User.objects.using("other").count(), 1)
def test_dumpdata(self):
"dumpdata honors allow_migrate restrictions on the router"
User.objects.create_user("alice", "[email protected]")
User.objects.db_manager("default").create_user("bob", "[email protected]")
# dumping the default database doesn't try to include auth because
# allow_migrate prohibits auth on default
new_io = StringIO()
management.call_command(
"dumpdata", "auth", format="json", database="default", stdout=new_io
)
command_output = new_io.getvalue().strip()
self.assertEqual(command_output, "[]")
# dumping the other database does include auth
new_io = StringIO()
management.call_command(
"dumpdata", "auth", format="json", database="other", stdout=new_io
)
command_output = new_io.getvalue().strip()
self.assertIn('"email": "[email protected]"', command_output)
class AntiPetRouter:
# A router that only expresses an opinion on migrate,
# passing pets to the 'other' database
def allow_migrate(self, db, app_label, model_name=None, **hints):
if db == "other":
return model_name == "pet"
else:
return model_name != "pet"
class FixtureTestCase(TestCase):
databases = {"default", "other"}
fixtures = ["multidb-common", "multidb"]
@override_settings(DATABASE_ROUTERS=[AntiPetRouter()])
def test_fixture_loading(self):
"Multi-db fixtures are loaded correctly"
# "Pro Django" exists on the default database, but not on other database
Book.objects.get(title="Pro Django")
Book.objects.using("default").get(title="Pro Django")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("other").get(title="Pro Django")
# "Dive into Python" exists on the default database, but not on other database
Book.objects.using("other").get(title="Dive into Python")
with self.assertRaises(Book.DoesNotExist):
Book.objects.get(title="Dive into Python")
with self.assertRaises(Book.DoesNotExist):
Book.objects.using("default").get(title="Dive into Python")
# "Definitive Guide" exists on the both databases
Book.objects.get(title="The Definitive Guide to Django")
Book.objects.using("default").get(title="The Definitive Guide to Django")
Book.objects.using("other").get(title="The Definitive Guide to Django")
@override_settings(DATABASE_ROUTERS=[AntiPetRouter()])
def test_pseudo_empty_fixtures(self):
"""
A fixture can contain entries, but lead to nothing in the database;
this shouldn't raise an error (#14068).
"""
new_io = StringIO()
management.call_command("loaddata", "pets", stdout=new_io, stderr=new_io)
command_output = new_io.getvalue().strip()
# No objects will actually be loaded
self.assertEqual(
command_output, "Installed 0 object(s) (of 2) from 1 fixture(s)"
)
class PickleQuerySetTestCase(TestCase):
databases = {"default", "other"}
def test_pickling(self):
for db in self.databases:
Book.objects.using(db).create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
qs = Book.objects.all()
self.assertEqual(qs.db, pickle.loads(pickle.dumps(qs)).db)
class DatabaseReceiver:
"""
Used in the tests for the database argument in signals (#13552)
"""
def __call__(self, signal, sender, **kwargs):
self._database = kwargs["using"]
class WriteToOtherRouter:
"""
A router that sends all writes to the other database.
"""
def db_for_write(self, model, **hints):
return "other"
class SignalTests(TestCase):
databases = {"default", "other"}
def override_router(self):
return override_settings(DATABASE_ROUTERS=[WriteToOtherRouter()])
def test_database_arg_save_and_delete(self):
"""
The pre/post_save signal contains the correct database.
"""
# Make some signal receivers
pre_save_receiver = DatabaseReceiver()
post_save_receiver = DatabaseReceiver()
pre_delete_receiver = DatabaseReceiver()
post_delete_receiver = DatabaseReceiver()
# Make model and connect receivers
signals.pre_save.connect(sender=Person, receiver=pre_save_receiver)
signals.post_save.connect(sender=Person, receiver=post_save_receiver)
signals.pre_delete.connect(sender=Person, receiver=pre_delete_receiver)
signals.post_delete.connect(sender=Person, receiver=post_delete_receiver)
p = Person.objects.create(name="Darth Vader")
# Save and test receivers got calls
p.save()
self.assertEqual(pre_save_receiver._database, DEFAULT_DB_ALIAS)
self.assertEqual(post_save_receiver._database, DEFAULT_DB_ALIAS)
# Delete, and test
p.delete()
self.assertEqual(pre_delete_receiver._database, DEFAULT_DB_ALIAS)
self.assertEqual(post_delete_receiver._database, DEFAULT_DB_ALIAS)
# Save again to a different database
p.save(using="other")
self.assertEqual(pre_save_receiver._database, "other")
self.assertEqual(post_save_receiver._database, "other")
# Delete, and test
p.delete(using="other")
self.assertEqual(pre_delete_receiver._database, "other")
self.assertEqual(post_delete_receiver._database, "other")
signals.pre_save.disconnect(sender=Person, receiver=pre_save_receiver)
signals.post_save.disconnect(sender=Person, receiver=post_save_receiver)
signals.pre_delete.disconnect(sender=Person, receiver=pre_delete_receiver)
signals.post_delete.disconnect(sender=Person, receiver=post_delete_receiver)
def test_database_arg_m2m(self):
"""
The m2m_changed signal has a correct database arg.
"""
# Make a receiver
receiver = DatabaseReceiver()
# Connect it
signals.m2m_changed.connect(receiver=receiver)
# Create the models that will be used for the tests
b = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
p = Person.objects.create(name="Marty Alchin")
# Create a copy of the models on the 'other' database to prevent
# integrity errors on backends that don't defer constraints checks
Book.objects.using("other").create(
pk=b.pk, title=b.title, published=b.published
)
Person.objects.using("other").create(pk=p.pk, name=p.name)
# Test addition
b.authors.add(p)
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
with self.override_router():
b.authors.add(p)
self.assertEqual(receiver._database, "other")
# Test removal
b.authors.remove(p)
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
with self.override_router():
b.authors.remove(p)
self.assertEqual(receiver._database, "other")
# Test addition in reverse
p.book_set.add(b)
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
with self.override_router():
p.book_set.add(b)
self.assertEqual(receiver._database, "other")
# Test clearing
b.authors.clear()
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
with self.override_router():
b.authors.clear()
self.assertEqual(receiver._database, "other")
class AttributeErrorRouter:
"A router to test the exception handling of ConnectionRouter"
def db_for_read(self, model, **hints):
raise AttributeError
def db_for_write(self, model, **hints):
raise AttributeError
class RouterAttributeErrorTestCase(TestCase):
databases = {"default", "other"}
def override_router(self):
return override_settings(DATABASE_ROUTERS=[AttributeErrorRouter()])
def test_attribute_error_read(self):
"The AttributeError from AttributeErrorRouter bubbles up"
b = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
with self.override_router():
with self.assertRaises(AttributeError):
Book.objects.get(pk=b.pk)
def test_attribute_error_save(self):
"The AttributeError from AttributeErrorRouter bubbles up"
dive = Book()
dive.title = "Dive into Python"
dive.published = datetime.date(2009, 5, 4)
with self.override_router():
with self.assertRaises(AttributeError):
dive.save()
def test_attribute_error_delete(self):
"The AttributeError from AttributeErrorRouter bubbles up"
b = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
p = Person.objects.create(name="Marty Alchin")
b.authors.set([p])
b.editor = p
with self.override_router():
with self.assertRaises(AttributeError):
b.delete()
def test_attribute_error_m2m(self):
"The AttributeError from AttributeErrorRouter bubbles up"
b = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
p = Person.objects.create(name="Marty Alchin")
with self.override_router():
with self.assertRaises(AttributeError):
b.authors.set([p])
class ModelMetaRouter:
"A router to ensure model arguments are real model classes"
def db_for_write(self, model, **hints):
if not hasattr(model, "_meta"):
raise ValueError
@override_settings(DATABASE_ROUTERS=[ModelMetaRouter()])
class RouterModelArgumentTestCase(TestCase):
databases = {"default", "other"}
def test_m2m_collection(self):
b = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
p = Person.objects.create(name="Marty Alchin")
# test add
b.authors.add(p)
# test remove
b.authors.remove(p)
# test clear
b.authors.clear()
# test setattr
b.authors.set([p])
# test M2M collection
b.delete()
def test_foreignkey_collection(self):
person = Person.objects.create(name="Bob")
Pet.objects.create(owner=person, name="Wart")
# test related FK collection
person.delete()
class SyncOnlyDefaultDatabaseRouter:
def allow_migrate(self, db, app_label, **hints):
return db == DEFAULT_DB_ALIAS
class MigrateTestCase(TestCase):
# Limit memory usage when calling 'migrate'.
available_apps = [
"multiple_database",
"django.contrib.auth",
"django.contrib.contenttypes",
]
databases = {"default", "other"}
def test_migrate_to_other_database(self):
"""Regression test for #16039: migrate with --database option."""
cts = ContentType.objects.using("other").filter(app_label="multiple_database")
count = cts.count()
self.assertGreater(count, 0)
cts.delete()
management.call_command(
"migrate", verbosity=0, interactive=False, database="other"
)
self.assertEqual(cts.count(), count)
def test_migrate_to_other_database_with_router(self):
"""Regression test for #16039: migrate with --database option."""
cts = ContentType.objects.using("other").filter(app_label="multiple_database")
cts.delete()
with override_settings(DATABASE_ROUTERS=[SyncOnlyDefaultDatabaseRouter()]):
management.call_command(
"migrate", verbosity=0, interactive=False, database="other"
)
self.assertEqual(cts.count(), 0)
class RouterUsed(Exception):
WRITE = "write"
def __init__(self, mode, model, hints):
self.mode = mode
self.model = model
self.hints = hints
class RouteForWriteTestCase(TestCase):
databases = {"default", "other"}
class WriteCheckRouter:
def db_for_write(self, model, **hints):
raise RouterUsed(mode=RouterUsed.WRITE, model=model, hints=hints)
def override_router(self):
return override_settings(
DATABASE_ROUTERS=[RouteForWriteTestCase.WriteCheckRouter()]
)
def test_fk_delete(self):
owner = Person.objects.create(name="Someone")
pet = Pet.objects.create(name="fido", owner=owner)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
pet.owner.delete()
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Person)
self.assertEqual(e.hints, {"instance": owner})
def test_reverse_fk_delete(self):
owner = Person.objects.create(name="Someone")
to_del_qs = owner.pet_set.all()
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
to_del_qs.delete()
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Pet)
self.assertEqual(e.hints, {"instance": owner})
def test_reverse_fk_get_or_create(self):
owner = Person.objects.create(name="Someone")
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
owner.pet_set.get_or_create(name="fido")
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Pet)
self.assertEqual(e.hints, {"instance": owner})
def test_reverse_fk_update(self):
owner = Person.objects.create(name="Someone")
Pet.objects.create(name="fido", owner=owner)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
owner.pet_set.update(name="max")
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Pet)
self.assertEqual(e.hints, {"instance": owner})
def test_m2m_add(self):
auth = Person.objects.create(name="Someone")
book = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
book.authors.add(auth)
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {"instance": book})
def test_m2m_clear(self):
auth = Person.objects.create(name="Someone")
book = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
book.authors.clear()
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {"instance": book})
def test_m2m_delete(self):
auth = Person.objects.create(name="Someone")
book = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
book.authors.all().delete()
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Person)
self.assertEqual(e.hints, {"instance": book})
def test_m2m_get_or_create(self):
Person.objects.create(name="Someone")
book = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
book.authors.get_or_create(name="Someone else")
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book)
self.assertEqual(e.hints, {"instance": book})
def test_m2m_remove(self):
auth = Person.objects.create(name="Someone")
book = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
book.authors.remove(auth)
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {"instance": book})
def test_m2m_update(self):
auth = Person.objects.create(name="Someone")
book = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
book.authors.update(name="Different")
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Person)
self.assertEqual(e.hints, {"instance": book})
def test_reverse_m2m_add(self):
auth = Person.objects.create(name="Someone")
book = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
auth.book_set.add(book)
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {"instance": auth})
def test_reverse_m2m_clear(self):
auth = Person.objects.create(name="Someone")
book = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
auth.book_set.clear()
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {"instance": auth})
def test_reverse_m2m_delete(self):
auth = Person.objects.create(name="Someone")
book = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
auth.book_set.all().delete()
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book)
self.assertEqual(e.hints, {"instance": auth})
def test_reverse_m2m_get_or_create(self):
auth = Person.objects.create(name="Someone")
Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
auth.book_set.get_or_create(
title="New Book", published=datetime.datetime.now()
)
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Person)
self.assertEqual(e.hints, {"instance": auth})
def test_reverse_m2m_remove(self):
auth = Person.objects.create(name="Someone")
book = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
auth.book_set.remove(book)
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book.authors.through)
self.assertEqual(e.hints, {"instance": auth})
def test_reverse_m2m_update(self):
auth = Person.objects.create(name="Someone")
book = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
auth.book_set.update(title="Different")
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book)
self.assertEqual(e.hints, {"instance": auth})
class NoRelationRouter:
"""Disallow all relations."""
def allow_relation(self, obj1, obj2, **hints):
return False
@override_settings(DATABASE_ROUTERS=[NoRelationRouter()])
class RelationAssignmentTests(SimpleTestCase):
"""allow_relation() is called with unsaved model instances."""
databases = {"default", "other"}
router_prevents_msg = "the current database router prevents this relation"
def test_foreign_key_relation(self):
person = Person(name="Someone")
pet = Pet()
with self.assertRaisesMessage(ValueError, self.router_prevents_msg):
pet.owner = person
def test_reverse_one_to_one_relation(self):
user = User(username="Someone", password="fake_hash")
profile = UserProfile()
with self.assertRaisesMessage(ValueError, self.router_prevents_msg):
user.userprofile = profile
|
4b1103f394b5c9e845ba243419b669542f800305380e45b17fd831aab48c9061 | from django.db import connection, transaction
from django.test import TransactionTestCase, skipUnlessDBFeature
from .models import Thing
class ForcedError(Exception):
pass
@skipUnlessDBFeature("supports_transactions")
class TestConnectionOnCommit(TransactionTestCase):
"""
Tests for transaction.on_commit().
Creation/checking of database objects in parallel with callback tracking is
to verify that the behavior of the two match in all tested cases.
"""
available_apps = ["transaction_hooks"]
def setUp(self):
self.notified = []
def notify(self, id_):
if id_ == "error":
raise ForcedError()
self.notified.append(id_)
def do(self, num):
"""Create a Thing instance and notify about it."""
Thing.objects.create(num=num)
transaction.on_commit(lambda: self.notify(num))
def assertDone(self, nums):
self.assertNotified(nums)
self.assertEqual(sorted(t.num for t in Thing.objects.all()), sorted(nums))
def assertNotified(self, nums):
self.assertEqual(self.notified, nums)
def test_executes_immediately_if_no_transaction(self):
self.do(1)
self.assertDone([1])
def test_robust_if_no_transaction(self):
def robust_callback():
raise ForcedError("robust callback")
with self.assertLogs("django.db.backends.base", "ERROR") as cm:
transaction.on_commit(robust_callback, robust=True)
self.do(1)
self.assertDone([1])
log_record = cm.records[0]
self.assertEqual(
log_record.getMessage(),
"Error calling TestConnectionOnCommit.test_robust_if_no_transaction."
"<locals>.robust_callback in on_commit() (robust callback).",
)
self.assertIsNotNone(log_record.exc_info)
raised_exception = log_record.exc_info[1]
self.assertIsInstance(raised_exception, ForcedError)
self.assertEqual(str(raised_exception), "robust callback")
def test_robust_transaction(self):
def robust_callback():
raise ForcedError("robust callback")
with self.assertLogs("django.db.backends", "ERROR") as cm:
with transaction.atomic():
transaction.on_commit(robust_callback, robust=True)
self.do(1)
self.assertDone([1])
log_record = cm.records[0]
self.assertEqual(
log_record.getMessage(),
"Error calling TestConnectionOnCommit.test_robust_transaction.<locals>."
"robust_callback in on_commit() during transaction (robust callback).",
)
self.assertIsNotNone(log_record.exc_info)
raised_exception = log_record.exc_info[1]
self.assertIsInstance(raised_exception, ForcedError)
self.assertEqual(str(raised_exception), "robust callback")
def test_delays_execution_until_after_transaction_commit(self):
with transaction.atomic():
self.do(1)
self.assertNotified([])
self.assertDone([1])
def test_does_not_execute_if_transaction_rolled_back(self):
try:
with transaction.atomic():
self.do(1)
raise ForcedError()
except ForcedError:
pass
self.assertDone([])
def test_executes_only_after_final_transaction_committed(self):
with transaction.atomic():
with transaction.atomic():
self.do(1)
self.assertNotified([])
self.assertNotified([])
self.assertDone([1])
def test_discards_hooks_from_rolled_back_savepoint(self):
with transaction.atomic():
# one successful savepoint
with transaction.atomic():
self.do(1)
# one failed savepoint
try:
with transaction.atomic():
self.do(2)
raise ForcedError()
except ForcedError:
pass
# another successful savepoint
with transaction.atomic():
self.do(3)
# only hooks registered during successful savepoints execute
self.assertDone([1, 3])
def test_no_hooks_run_from_failed_transaction(self):
"""If outer transaction fails, no hooks from within it run."""
try:
with transaction.atomic():
with transaction.atomic():
self.do(1)
raise ForcedError()
except ForcedError:
pass
self.assertDone([])
def test_inner_savepoint_rolled_back_with_outer(self):
with transaction.atomic():
try:
with transaction.atomic():
with transaction.atomic():
self.do(1)
raise ForcedError()
except ForcedError:
pass
self.do(2)
self.assertDone([2])
def test_no_savepoints_atomic_merged_with_outer(self):
with transaction.atomic():
with transaction.atomic():
self.do(1)
try:
with transaction.atomic(savepoint=False):
raise ForcedError()
except ForcedError:
pass
self.assertDone([])
def test_inner_savepoint_does_not_affect_outer(self):
with transaction.atomic():
with transaction.atomic():
self.do(1)
try:
with transaction.atomic():
raise ForcedError()
except ForcedError:
pass
self.assertDone([1])
def test_runs_hooks_in_order_registered(self):
with transaction.atomic():
self.do(1)
with transaction.atomic():
self.do(2)
self.do(3)
self.assertDone([1, 2, 3])
def test_hooks_cleared_after_successful_commit(self):
with transaction.atomic():
self.do(1)
with transaction.atomic():
self.do(2)
self.assertDone([1, 2]) # not [1, 1, 2]
def test_hooks_cleared_after_rollback(self):
try:
with transaction.atomic():
self.do(1)
raise ForcedError()
except ForcedError:
pass
with transaction.atomic():
self.do(2)
self.assertDone([2])
@skipUnlessDBFeature("test_db_allows_multiple_connections")
def test_hooks_cleared_on_reconnect(self):
with transaction.atomic():
self.do(1)
connection.close()
connection.connect()
with transaction.atomic():
self.do(2)
self.assertDone([2])
def test_error_in_hook_doesnt_prevent_clearing_hooks(self):
try:
with transaction.atomic():
transaction.on_commit(lambda: self.notify("error"))
except ForcedError:
pass
with transaction.atomic():
self.do(1)
self.assertDone([1])
def test_db_query_in_hook(self):
with transaction.atomic():
Thing.objects.create(num=1)
transaction.on_commit(
lambda: [self.notify(t.num) for t in Thing.objects.all()]
)
self.assertDone([1])
def test_transaction_in_hook(self):
def on_commit():
with transaction.atomic():
t = Thing.objects.create(num=1)
self.notify(t.num)
with transaction.atomic():
transaction.on_commit(on_commit)
self.assertDone([1])
def test_hook_in_hook(self):
def on_commit(i, add_hook):
with transaction.atomic():
if add_hook:
transaction.on_commit(lambda: on_commit(i + 10, False))
t = Thing.objects.create(num=i)
self.notify(t.num)
with transaction.atomic():
transaction.on_commit(lambda: on_commit(1, True))
transaction.on_commit(lambda: on_commit(2, True))
self.assertDone([1, 11, 2, 12])
def test_raises_exception_non_autocommit_mode(self):
def should_never_be_called():
raise AssertionError("this function should never be called")
try:
connection.set_autocommit(False)
msg = "on_commit() cannot be used in manual transaction management"
with self.assertRaisesMessage(transaction.TransactionManagementError, msg):
transaction.on_commit(should_never_be_called)
finally:
connection.set_autocommit(True)
def test_raises_exception_non_callable(self):
msg = "on_commit()'s callback must be a callable."
with self.assertRaisesMessage(TypeError, msg):
transaction.on_commit(None)
|
549ef7c8f8ea3dfb5c04f4c6ca7a159049eca9e2e6cbe9d8c0abfe51f2ff9346 | from datetime import datetime
from django.test import TestCase
from .models import Article, Category
class M2MMultipleTests(TestCase):
def test_multiple(self):
c1, c2, c3, c4 = [
Category.objects.create(name=name)
for name in ["Sports", "News", "Crime", "Life"]
]
a1 = Article.objects.create(
headline="Parrot steals", pub_date=datetime(2005, 11, 27)
)
a1.primary_categories.add(c2, c3)
a1.secondary_categories.add(c4)
a2 = Article.objects.create(
headline="Parrot runs", pub_date=datetime(2005, 11, 28)
)
a2.primary_categories.add(c1, c2)
a2.secondary_categories.add(c4)
self.assertQuerySetEqual(
a1.primary_categories.all(),
[
"Crime",
"News",
],
lambda c: c.name,
)
self.assertQuerySetEqual(
a2.primary_categories.all(),
[
"News",
"Sports",
],
lambda c: c.name,
)
self.assertQuerySetEqual(
a1.secondary_categories.all(),
[
"Life",
],
lambda c: c.name,
)
self.assertQuerySetEqual(
c1.primary_article_set.all(),
[
"Parrot runs",
],
lambda a: a.headline,
)
self.assertQuerySetEqual(c1.secondary_article_set.all(), [])
self.assertQuerySetEqual(
c2.primary_article_set.all(),
[
"Parrot steals",
"Parrot runs",
],
lambda a: a.headline,
)
self.assertQuerySetEqual(c2.secondary_article_set.all(), [])
self.assertQuerySetEqual(
c3.primary_article_set.all(),
[
"Parrot steals",
],
lambda a: a.headline,
)
self.assertQuerySetEqual(c3.secondary_article_set.all(), [])
self.assertQuerySetEqual(c4.primary_article_set.all(), [])
self.assertQuerySetEqual(
c4.secondary_article_set.all(),
[
"Parrot steals",
"Parrot runs",
],
lambda a: a.headline,
)
|
3772019ac0949f28361f873103741bbee951d7c1e3c931d588890fff3b7bd420 | import datetime
from unittest import mock
from django.contrib import admin
from django.contrib.admin.models import LogEntry
from django.contrib.admin.options import IncorrectLookupParameters
from django.contrib.admin.templatetags.admin_list import pagination
from django.contrib.admin.tests import AdminSeleniumTestCase
from django.contrib.admin.views.main import (
ALL_VAR,
IS_POPUP_VAR,
ORDER_VAR,
PAGE_VAR,
SEARCH_VAR,
TO_FIELD_VAR,
)
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.messages.storage.cookie import CookieStorage
from django.db import DatabaseError, connection, models
from django.db.models import F, Field, IntegerField
from django.db.models.functions import Upper
from django.db.models.lookups import Contains, Exact
from django.template import Context, Template, TemplateSyntaxError
from django.test import TestCase, override_settings, skipUnlessDBFeature
from django.test.client import RequestFactory
from django.test.utils import CaptureQueriesContext, isolate_apps, register_lookup
from django.urls import reverse
from django.utils import formats
from .admin import (
BandAdmin,
ChildAdmin,
ChordsBandAdmin,
ConcertAdmin,
CustomPaginationAdmin,
CustomPaginator,
DynamicListDisplayChildAdmin,
DynamicListDisplayLinksChildAdmin,
DynamicListFilterChildAdmin,
DynamicSearchFieldsChildAdmin,
EmptyValueChildAdmin,
EventAdmin,
FilteredChildAdmin,
GroupAdmin,
InvitationAdmin,
NoListDisplayLinksParentAdmin,
ParentAdmin,
ParentAdminTwoSearchFields,
QuartetAdmin,
SwallowAdmin,
)
from .admin import site as custom_site
from .models import (
Band,
CharPK,
Child,
ChordsBand,
ChordsMusician,
Concert,
CustomIdUser,
Event,
Genre,
Group,
Invitation,
Membership,
Musician,
OrderedObject,
Parent,
Quartet,
Swallow,
SwallowOneToOne,
UnorderedObject,
)
def build_tbody_html(pk, href, extra_fields):
return (
"<tbody><tr>"
'<td class="action-checkbox">'
'<input type="checkbox" name="_selected_action" value="{}" '
'class="action-select"></td>'
'<th class="field-name"><a href="{}">name</a></th>'
"{}</tr></tbody>"
).format(pk, href, extra_fields)
@override_settings(ROOT_URLCONF="admin_changelist.urls")
class ChangeListTests(TestCase):
factory = RequestFactory()
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", email="[email protected]", password="xxx"
)
def _create_superuser(self, username):
return User.objects.create_superuser(
username=username, email="[email protected]", password="xxx"
)
def _mocked_authenticated_request(self, url, user):
request = self.factory.get(url)
request.user = user
return request
def test_repr(self):
m = ChildAdmin(Child, custom_site)
request = self.factory.get("/child/")
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertEqual(repr(cl), "<ChangeList: model=Child model_admin=ChildAdmin>")
def test_specified_ordering_by_f_expression(self):
class OrderedByFBandAdmin(admin.ModelAdmin):
list_display = ["name", "genres", "nr_of_members"]
ordering = (
F("nr_of_members").desc(nulls_last=True),
Upper(F("name")).asc(),
F("genres").asc(),
)
m = OrderedByFBandAdmin(Band, custom_site)
request = self.factory.get("/band/")
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertEqual(cl.get_ordering_field_columns(), {3: "desc", 2: "asc"})
def test_specified_ordering_by_f_expression_without_asc_desc(self):
class OrderedByFBandAdmin(admin.ModelAdmin):
list_display = ["name", "genres", "nr_of_members"]
ordering = (F("nr_of_members"), Upper("name"), F("genres"))
m = OrderedByFBandAdmin(Band, custom_site)
request = self.factory.get("/band/")
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertEqual(cl.get_ordering_field_columns(), {3: "asc", 2: "asc"})
def test_select_related_preserved(self):
"""
Regression test for #10348: ChangeList.get_queryset() shouldn't
overwrite a custom select_related provided by ModelAdmin.get_queryset().
"""
m = ChildAdmin(Child, custom_site)
request = self.factory.get("/child/")
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertEqual(cl.queryset.query.select_related, {"parent": {}})
def test_select_related_preserved_when_multi_valued_in_search_fields(self):
parent = Parent.objects.create(name="Mary")
Child.objects.create(parent=parent, name="Danielle")
Child.objects.create(parent=parent, name="Daniel")
m = ParentAdmin(Parent, custom_site)
request = self.factory.get("/parent/", data={SEARCH_VAR: "daniel"})
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertEqual(cl.queryset.count(), 1)
# select_related is preserved.
self.assertEqual(cl.queryset.query.select_related, {"child": {}})
def test_select_related_as_tuple(self):
ia = InvitationAdmin(Invitation, custom_site)
request = self.factory.get("/invitation/")
request.user = self.superuser
cl = ia.get_changelist_instance(request)
self.assertEqual(cl.queryset.query.select_related, {"player": {}})
def test_select_related_as_empty_tuple(self):
ia = InvitationAdmin(Invitation, custom_site)
ia.list_select_related = ()
request = self.factory.get("/invitation/")
request.user = self.superuser
cl = ia.get_changelist_instance(request)
self.assertIs(cl.queryset.query.select_related, False)
def test_get_select_related_custom_method(self):
class GetListSelectRelatedAdmin(admin.ModelAdmin):
list_display = ("band", "player")
def get_list_select_related(self, request):
return ("band", "player")
ia = GetListSelectRelatedAdmin(Invitation, custom_site)
request = self.factory.get("/invitation/")
request.user = self.superuser
cl = ia.get_changelist_instance(request)
self.assertEqual(cl.queryset.query.select_related, {"player": {}, "band": {}})
def test_many_search_terms(self):
parent = Parent.objects.create(name="Mary")
Child.objects.create(parent=parent, name="Danielle")
Child.objects.create(parent=parent, name="Daniel")
m = ParentAdmin(Parent, custom_site)
request = self.factory.get("/parent/", data={SEARCH_VAR: "daniel " * 80})
request.user = self.superuser
cl = m.get_changelist_instance(request)
with CaptureQueriesContext(connection) as context:
object_count = cl.queryset.count()
self.assertEqual(object_count, 1)
self.assertEqual(context.captured_queries[0]["sql"].count("JOIN"), 1)
def test_related_field_multiple_search_terms(self):
"""
Searches over multi-valued relationships return rows from related
models only when all searched fields match that row.
"""
parent = Parent.objects.create(name="Mary")
Child.objects.create(parent=parent, name="Danielle", age=18)
Child.objects.create(parent=parent, name="Daniel", age=19)
m = ParentAdminTwoSearchFields(Parent, custom_site)
request = self.factory.get("/parent/", data={SEARCH_VAR: "danielle 19"})
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertEqual(cl.queryset.count(), 0)
request = self.factory.get("/parent/", data={SEARCH_VAR: "daniel 19"})
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertEqual(cl.queryset.count(), 1)
def test_result_list_empty_changelist_value(self):
"""
Regression test for #14982: EMPTY_CHANGELIST_VALUE should be honored
for relationship fields
"""
new_child = Child.objects.create(name="name", parent=None)
request = self.factory.get("/child/")
request.user = self.superuser
m = ChildAdmin(Child, custom_site)
cl = m.get_changelist_instance(request)
cl.formset = None
template = Template(
"{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}"
)
context = Context({"cl": cl, "opts": Child._meta})
table_output = template.render(context)
link = reverse("admin:admin_changelist_child_change", args=(new_child.id,))
row_html = build_tbody_html(
new_child.id, link, '<td class="field-parent nowrap">-</td>'
)
self.assertNotEqual(
table_output.find(row_html),
-1,
"Failed to find expected row element: %s" % table_output,
)
def test_result_list_set_empty_value_display_on_admin_site(self):
"""
Empty value display can be set on AdminSite.
"""
new_child = Child.objects.create(name="name", parent=None)
request = self.factory.get("/child/")
request.user = self.superuser
# Set a new empty display value on AdminSite.
admin.site.empty_value_display = "???"
m = ChildAdmin(Child, admin.site)
cl = m.get_changelist_instance(request)
cl.formset = None
template = Template(
"{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}"
)
context = Context({"cl": cl, "opts": Child._meta})
table_output = template.render(context)
link = reverse("admin:admin_changelist_child_change", args=(new_child.id,))
row_html = build_tbody_html(
new_child.id, link, '<td class="field-parent nowrap">???</td>'
)
self.assertNotEqual(
table_output.find(row_html),
-1,
"Failed to find expected row element: %s" % table_output,
)
def test_result_list_set_empty_value_display_in_model_admin(self):
"""
Empty value display can be set in ModelAdmin or individual fields.
"""
new_child = Child.objects.create(name="name", parent=None)
request = self.factory.get("/child/")
request.user = self.superuser
m = EmptyValueChildAdmin(Child, admin.site)
cl = m.get_changelist_instance(request)
cl.formset = None
template = Template(
"{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}"
)
context = Context({"cl": cl, "opts": Child._meta})
table_output = template.render(context)
link = reverse("admin:admin_changelist_child_change", args=(new_child.id,))
row_html = build_tbody_html(
new_child.id,
link,
'<td class="field-age_display">&dagger;</td>'
'<td class="field-age">-empty-</td>',
)
self.assertNotEqual(
table_output.find(row_html),
-1,
"Failed to find expected row element: %s" % table_output,
)
def test_result_list_html(self):
"""
Inclusion tag result_list generates a table when with default
ModelAdmin settings.
"""
new_parent = Parent.objects.create(name="parent")
new_child = Child.objects.create(name="name", parent=new_parent)
request = self.factory.get("/child/")
request.user = self.superuser
m = ChildAdmin(Child, custom_site)
cl = m.get_changelist_instance(request)
cl.formset = None
template = Template(
"{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}"
)
context = Context({"cl": cl, "opts": Child._meta})
table_output = template.render(context)
link = reverse("admin:admin_changelist_child_change", args=(new_child.id,))
row_html = build_tbody_html(
new_child.id, link, '<td class="field-parent nowrap">%s</td>' % new_parent
)
self.assertNotEqual(
table_output.find(row_html),
-1,
"Failed to find expected row element: %s" % table_output,
)
def test_result_list_editable_html(self):
"""
Regression tests for #11791: Inclusion tag result_list generates a
table and this checks that the items are nested within the table
element tags.
Also a regression test for #13599, verifies that hidden fields
when list_editable is enabled are rendered in a div outside the
table.
"""
new_parent = Parent.objects.create(name="parent")
new_child = Child.objects.create(name="name", parent=new_parent)
request = self.factory.get("/child/")
request.user = self.superuser
m = ChildAdmin(Child, custom_site)
# Test with list_editable fields
m.list_display = ["id", "name", "parent"]
m.list_display_links = ["id"]
m.list_editable = ["name"]
cl = m.get_changelist_instance(request)
FormSet = m.get_changelist_formset(request)
cl.formset = FormSet(queryset=cl.result_list)
template = Template(
"{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}"
)
context = Context({"cl": cl, "opts": Child._meta})
table_output = template.render(context)
# make sure that hidden fields are in the correct place
hiddenfields_div = (
'<div class="hiddenfields">'
'<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id">'
"</div>"
) % new_child.id
self.assertInHTML(
hiddenfields_div, table_output, msg_prefix="Failed to find hidden fields"
)
# make sure that list editable fields are rendered in divs correctly
editable_name_field = (
'<input name="form-0-name" value="name" class="vTextField" '
'maxlength="30" type="text" id="id_form-0-name">'
)
self.assertInHTML(
'<td class="field-name">%s</td>' % editable_name_field,
table_output,
msg_prefix='Failed to find "name" list_editable field',
)
def test_result_list_editable(self):
"""
Regression test for #14312: list_editable with pagination
"""
new_parent = Parent.objects.create(name="parent")
for i in range(1, 201):
Child.objects.create(name="name %s" % i, parent=new_parent)
request = self.factory.get("/child/", data={"p": -1}) # Anything outside range
request.user = self.superuser
m = ChildAdmin(Child, custom_site)
# Test with list_editable fields
m.list_display = ["id", "name", "parent"]
m.list_display_links = ["id"]
m.list_editable = ["name"]
with self.assertRaises(IncorrectLookupParameters):
m.get_changelist_instance(request)
@skipUnlessDBFeature("supports_transactions")
def test_list_editable_atomicity(self):
a = Swallow.objects.create(origin="Swallow A", load=4, speed=1)
b = Swallow.objects.create(origin="Swallow B", load=2, speed=2)
self.client.force_login(self.superuser)
changelist_url = reverse("admin:admin_changelist_swallow_changelist")
data = {
"form-TOTAL_FORMS": "2",
"form-INITIAL_FORMS": "2",
"form-MIN_NUM_FORMS": "0",
"form-MAX_NUM_FORMS": "1000",
"form-0-uuid": str(a.pk),
"form-1-uuid": str(b.pk),
"form-0-load": "9.0",
"form-0-speed": "3.0",
"form-1-load": "5.0",
"form-1-speed": "1.0",
"_save": "Save",
}
with mock.patch(
"django.contrib.admin.ModelAdmin.log_change", side_effect=DatabaseError
):
with self.assertRaises(DatabaseError):
self.client.post(changelist_url, data)
# Original values are preserved.
a.refresh_from_db()
self.assertEqual(a.load, 4)
self.assertEqual(a.speed, 1)
b.refresh_from_db()
self.assertEqual(b.load, 2)
self.assertEqual(b.speed, 2)
with mock.patch(
"django.contrib.admin.ModelAdmin.log_change",
side_effect=[None, DatabaseError],
):
with self.assertRaises(DatabaseError):
self.client.post(changelist_url, data)
# Original values are preserved.
a.refresh_from_db()
self.assertEqual(a.load, 4)
self.assertEqual(a.speed, 1)
b.refresh_from_db()
self.assertEqual(b.load, 2)
self.assertEqual(b.speed, 2)
def test_custom_paginator(self):
new_parent = Parent.objects.create(name="parent")
for i in range(1, 201):
Child.objects.create(name="name %s" % i, parent=new_parent)
request = self.factory.get("/child/")
request.user = self.superuser
m = CustomPaginationAdmin(Child, custom_site)
cl = m.get_changelist_instance(request)
cl.get_results(request)
self.assertIsInstance(cl.paginator, CustomPaginator)
def test_no_duplicates_for_m2m_in_list_filter(self):
"""
Regression test for #13902: When using a ManyToMany in list_filter,
results shouldn't appear more than once. Basic ManyToMany.
"""
blues = Genre.objects.create(name="Blues")
band = Band.objects.create(name="B.B. King Review", nr_of_members=11)
band.genres.add(blues)
band.genres.add(blues)
m = BandAdmin(Band, custom_site)
request = self.factory.get("/band/", data={"genres": blues.pk})
request.user = self.superuser
cl = m.get_changelist_instance(request)
cl.get_results(request)
# There's only one Group instance
self.assertEqual(cl.result_count, 1)
# Queryset must be deletable.
self.assertIs(cl.queryset.query.distinct, False)
cl.queryset.delete()
self.assertEqual(cl.queryset.count(), 0)
def test_no_duplicates_for_through_m2m_in_list_filter(self):
"""
Regression test for #13902: When using a ManyToMany in list_filter,
results shouldn't appear more than once. With an intermediate model.
"""
lead = Musician.objects.create(name="Vox")
band = Group.objects.create(name="The Hype")
Membership.objects.create(group=band, music=lead, role="lead voice")
Membership.objects.create(group=band, music=lead, role="bass player")
m = GroupAdmin(Group, custom_site)
request = self.factory.get("/group/", data={"members": lead.pk})
request.user = self.superuser
cl = m.get_changelist_instance(request)
cl.get_results(request)
# There's only one Group instance
self.assertEqual(cl.result_count, 1)
# Queryset must be deletable.
self.assertIs(cl.queryset.query.distinct, False)
cl.queryset.delete()
self.assertEqual(cl.queryset.count(), 0)
def test_no_duplicates_for_through_m2m_at_second_level_in_list_filter(self):
"""
When using a ManyToMany in list_filter at the second level behind a
ForeignKey, results shouldn't appear more than once.
"""
lead = Musician.objects.create(name="Vox")
band = Group.objects.create(name="The Hype")
Concert.objects.create(name="Woodstock", group=band)
Membership.objects.create(group=band, music=lead, role="lead voice")
Membership.objects.create(group=band, music=lead, role="bass player")
m = ConcertAdmin(Concert, custom_site)
request = self.factory.get("/concert/", data={"group__members": lead.pk})
request.user = self.superuser
cl = m.get_changelist_instance(request)
cl.get_results(request)
# There's only one Concert instance
self.assertEqual(cl.result_count, 1)
# Queryset must be deletable.
self.assertIs(cl.queryset.query.distinct, False)
cl.queryset.delete()
self.assertEqual(cl.queryset.count(), 0)
def test_no_duplicates_for_inherited_m2m_in_list_filter(self):
"""
Regression test for #13902: When using a ManyToMany in list_filter,
results shouldn't appear more than once. Model managed in the
admin inherits from the one that defines the relationship.
"""
lead = Musician.objects.create(name="John")
four = Quartet.objects.create(name="The Beatles")
Membership.objects.create(group=four, music=lead, role="lead voice")
Membership.objects.create(group=four, music=lead, role="guitar player")
m = QuartetAdmin(Quartet, custom_site)
request = self.factory.get("/quartet/", data={"members": lead.pk})
request.user = self.superuser
cl = m.get_changelist_instance(request)
cl.get_results(request)
# There's only one Quartet instance
self.assertEqual(cl.result_count, 1)
# Queryset must be deletable.
self.assertIs(cl.queryset.query.distinct, False)
cl.queryset.delete()
self.assertEqual(cl.queryset.count(), 0)
def test_no_duplicates_for_m2m_to_inherited_in_list_filter(self):
"""
Regression test for #13902: When using a ManyToMany in list_filter,
results shouldn't appear more than once. Target of the relationship
inherits from another.
"""
lead = ChordsMusician.objects.create(name="Player A")
three = ChordsBand.objects.create(name="The Chords Trio")
Invitation.objects.create(band=three, player=lead, instrument="guitar")
Invitation.objects.create(band=three, player=lead, instrument="bass")
m = ChordsBandAdmin(ChordsBand, custom_site)
request = self.factory.get("/chordsband/", data={"members": lead.pk})
request.user = self.superuser
cl = m.get_changelist_instance(request)
cl.get_results(request)
# There's only one ChordsBand instance
self.assertEqual(cl.result_count, 1)
# Queryset must be deletable.
self.assertIs(cl.queryset.query.distinct, False)
cl.queryset.delete()
self.assertEqual(cl.queryset.count(), 0)
def test_no_duplicates_for_non_unique_related_object_in_list_filter(self):
"""
Regressions tests for #15819: If a field listed in list_filters is a
non-unique related object, results shouldn't appear more than once.
"""
parent = Parent.objects.create(name="Mary")
# Two children with the same name
Child.objects.create(parent=parent, name="Daniel")
Child.objects.create(parent=parent, name="Daniel")
m = ParentAdmin(Parent, custom_site)
request = self.factory.get("/parent/", data={"child__name": "Daniel"})
request.user = self.superuser
cl = m.get_changelist_instance(request)
# Exists() is applied.
self.assertEqual(cl.queryset.count(), 1)
# Queryset must be deletable.
self.assertIs(cl.queryset.query.distinct, False)
cl.queryset.delete()
self.assertEqual(cl.queryset.count(), 0)
def test_changelist_search_form_validation(self):
m = ConcertAdmin(Concert, custom_site)
tests = [
({SEARCH_VAR: "\x00"}, "Null characters are not allowed."),
({SEARCH_VAR: "some\x00thing"}, "Null characters are not allowed."),
]
for case, error in tests:
with self.subTest(case=case):
request = self.factory.get("/concert/", case)
request.user = self.superuser
request._messages = CookieStorage(request)
m.get_changelist_instance(request)
messages = [m.message for m in request._messages]
self.assertEqual(1, len(messages))
self.assertEqual(error, messages[0])
def test_no_duplicates_for_non_unique_related_object_in_search_fields(self):
"""
Regressions tests for #15819: If a field listed in search_fields
is a non-unique related object, Exists() must be applied.
"""
parent = Parent.objects.create(name="Mary")
Child.objects.create(parent=parent, name="Danielle")
Child.objects.create(parent=parent, name="Daniel")
m = ParentAdmin(Parent, custom_site)
request = self.factory.get("/parent/", data={SEARCH_VAR: "daniel"})
request.user = self.superuser
cl = m.get_changelist_instance(request)
# Exists() is applied.
self.assertEqual(cl.queryset.count(), 1)
# Queryset must be deletable.
self.assertIs(cl.queryset.query.distinct, False)
cl.queryset.delete()
self.assertEqual(cl.queryset.count(), 0)
def test_no_duplicates_for_many_to_many_at_second_level_in_search_fields(self):
"""
When using a ManyToMany in search_fields at the second level behind a
ForeignKey, Exists() must be applied and results shouldn't appear more
than once.
"""
lead = Musician.objects.create(name="Vox")
band = Group.objects.create(name="The Hype")
Concert.objects.create(name="Woodstock", group=band)
Membership.objects.create(group=band, music=lead, role="lead voice")
Membership.objects.create(group=band, music=lead, role="bass player")
m = ConcertAdmin(Concert, custom_site)
request = self.factory.get("/concert/", data={SEARCH_VAR: "vox"})
request.user = self.superuser
cl = m.get_changelist_instance(request)
# There's only one Concert instance
self.assertEqual(cl.queryset.count(), 1)
# Queryset must be deletable.
self.assertIs(cl.queryset.query.distinct, False)
cl.queryset.delete()
self.assertEqual(cl.queryset.count(), 0)
def test_multiple_search_fields(self):
"""
All rows containing each of the searched words are returned, where each
word must be in one of search_fields.
"""
band_duo = Group.objects.create(name="Duo")
band_hype = Group.objects.create(name="The Hype")
mary = Musician.objects.create(name="Mary Halvorson")
jonathan = Musician.objects.create(name="Jonathan Finlayson")
band_duo.members.set([mary, jonathan])
Concert.objects.create(name="Tiny desk concert", group=band_duo)
Concert.objects.create(name="Woodstock concert", group=band_hype)
# FK lookup.
concert_model_admin = ConcertAdmin(Concert, custom_site)
concert_model_admin.search_fields = ["group__name", "name"]
# Reverse FK lookup.
group_model_admin = GroupAdmin(Group, custom_site)
group_model_admin.search_fields = ["name", "concert__name", "members__name"]
for search_string, result_count in (
("Duo Concert", 1),
("Tiny Desk Concert", 1),
("Concert", 2),
("Other Concert", 0),
("Duo Woodstock", 0),
):
with self.subTest(search_string=search_string):
# FK lookup.
request = self.factory.get(
"/concert/", data={SEARCH_VAR: search_string}
)
request.user = self.superuser
concert_changelist = concert_model_admin.get_changelist_instance(
request
)
self.assertEqual(concert_changelist.queryset.count(), result_count)
# Reverse FK lookup.
request = self.factory.get("/group/", data={SEARCH_VAR: search_string})
request.user = self.superuser
group_changelist = group_model_admin.get_changelist_instance(request)
self.assertEqual(group_changelist.queryset.count(), result_count)
# Many-to-many lookup.
for search_string, result_count in (
("Finlayson Duo Tiny", 1),
("Finlayson", 1),
("Finlayson Hype", 0),
("Jonathan Finlayson Duo", 1),
("Mary Jonathan Duo", 0),
("Oscar Finlayson Duo", 0),
):
with self.subTest(search_string=search_string):
request = self.factory.get("/group/", data={SEARCH_VAR: search_string})
request.user = self.superuser
group_changelist = group_model_admin.get_changelist_instance(request)
self.assertEqual(group_changelist.queryset.count(), result_count)
def test_pk_in_search_fields(self):
band = Group.objects.create(name="The Hype")
Concert.objects.create(name="Woodstock", group=band)
m = ConcertAdmin(Concert, custom_site)
m.search_fields = ["group__pk"]
request = self.factory.get("/concert/", data={SEARCH_VAR: band.pk})
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertEqual(cl.queryset.count(), 1)
request = self.factory.get("/concert/", data={SEARCH_VAR: band.pk + 5})
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertEqual(cl.queryset.count(), 0)
def test_builtin_lookup_in_search_fields(self):
band = Group.objects.create(name="The Hype")
concert = Concert.objects.create(name="Woodstock", group=band)
m = ConcertAdmin(Concert, custom_site)
m.search_fields = ["name__iexact"]
request = self.factory.get("/", data={SEARCH_VAR: "woodstock"})
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertCountEqual(cl.queryset, [concert])
request = self.factory.get("/", data={SEARCH_VAR: "wood"})
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertCountEqual(cl.queryset, [])
def test_custom_lookup_in_search_fields(self):
band = Group.objects.create(name="The Hype")
concert = Concert.objects.create(name="Woodstock", group=band)
m = ConcertAdmin(Concert, custom_site)
m.search_fields = ["group__name__cc"]
with register_lookup(Field, Contains, lookup_name="cc"):
request = self.factory.get("/", data={SEARCH_VAR: "Hype"})
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertCountEqual(cl.queryset, [concert])
request = self.factory.get("/", data={SEARCH_VAR: "Woodstock"})
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertCountEqual(cl.queryset, [])
def test_spanning_relations_with_custom_lookup_in_search_fields(self):
hype = Group.objects.create(name="The Hype")
concert = Concert.objects.create(name="Woodstock", group=hype)
vox = Musician.objects.create(name="Vox", age=20)
Membership.objects.create(music=vox, group=hype)
# Register a custom lookup on IntegerField to ensure that field
# traversing logic in ModelAdmin.get_search_results() works.
with register_lookup(IntegerField, Exact, lookup_name="exactly"):
m = ConcertAdmin(Concert, custom_site)
m.search_fields = ["group__members__age__exactly"]
request = self.factory.get("/", data={SEARCH_VAR: "20"})
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertCountEqual(cl.queryset, [concert])
request = self.factory.get("/", data={SEARCH_VAR: "21"})
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertCountEqual(cl.queryset, [])
def test_custom_lookup_with_pk_shortcut(self):
self.assertEqual(CharPK._meta.pk.name, "char_pk") # Not equal to 'pk'.
m = admin.ModelAdmin(CustomIdUser, custom_site)
abc = CharPK.objects.create(char_pk="abc")
abcd = CharPK.objects.create(char_pk="abcd")
m = admin.ModelAdmin(CharPK, custom_site)
m.search_fields = ["pk__exact"]
request = self.factory.get("/", data={SEARCH_VAR: "abc"})
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertCountEqual(cl.queryset, [abc])
request = self.factory.get("/", data={SEARCH_VAR: "abcd"})
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertCountEqual(cl.queryset, [abcd])
def test_no_exists_for_m2m_in_list_filter_without_params(self):
"""
If a ManyToManyField is in list_filter but isn't in any lookup params,
the changelist's query shouldn't have Exists().
"""
m = BandAdmin(Band, custom_site)
for lookup_params in ({}, {"name": "test"}):
request = self.factory.get("/band/", lookup_params)
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertNotIn(" EXISTS", str(cl.queryset.query))
# A ManyToManyField in params does have Exists() applied.
request = self.factory.get("/band/", {"genres": "0"})
request.user = self.superuser
cl = m.get_changelist_instance(request)
self.assertIn(" EXISTS", str(cl.queryset.query))
def test_pagination(self):
"""
Regression tests for #12893: Pagination in admins changelist doesn't
use queryset set by modeladmin.
"""
parent = Parent.objects.create(name="anything")
for i in range(1, 31):
Child.objects.create(name="name %s" % i, parent=parent)
Child.objects.create(name="filtered %s" % i, parent=parent)
request = self.factory.get("/child/")
request.user = self.superuser
# Test default queryset
m = ChildAdmin(Child, custom_site)
cl = m.get_changelist_instance(request)
self.assertEqual(cl.queryset.count(), 60)
self.assertEqual(cl.paginator.count, 60)
self.assertEqual(list(cl.paginator.page_range), [1, 2, 3, 4, 5, 6])
# Test custom queryset
m = FilteredChildAdmin(Child, custom_site)
cl = m.get_changelist_instance(request)
self.assertEqual(cl.queryset.count(), 30)
self.assertEqual(cl.paginator.count, 30)
self.assertEqual(list(cl.paginator.page_range), [1, 2, 3])
def test_computed_list_display_localization(self):
"""
Regression test for #13196: output of functions should be localized
in the changelist.
"""
self.client.force_login(self.superuser)
event = Event.objects.create(date=datetime.date.today())
response = self.client.get(reverse("admin:admin_changelist_event_changelist"))
self.assertContains(response, formats.localize(event.date))
self.assertNotContains(response, str(event.date))
def test_dynamic_list_display(self):
"""
Regression tests for #14206: dynamic list_display support.
"""
parent = Parent.objects.create(name="parent")
for i in range(10):
Child.objects.create(name="child %s" % i, parent=parent)
user_noparents = self._create_superuser("noparents")
user_parents = self._create_superuser("parents")
# Test with user 'noparents'
m = custom_site._registry[Child]
request = self._mocked_authenticated_request("/child/", user_noparents)
response = m.changelist_view(request)
self.assertNotContains(response, "Parent object")
list_display = m.get_list_display(request)
list_display_links = m.get_list_display_links(request, list_display)
self.assertEqual(list_display, ["name", "age"])
self.assertEqual(list_display_links, ["name"])
# Test with user 'parents'
m = DynamicListDisplayChildAdmin(Child, custom_site)
request = self._mocked_authenticated_request("/child/", user_parents)
response = m.changelist_view(request)
self.assertContains(response, "Parent object")
custom_site.unregister(Child)
list_display = m.get_list_display(request)
list_display_links = m.get_list_display_links(request, list_display)
self.assertEqual(list_display, ("parent", "name", "age"))
self.assertEqual(list_display_links, ["parent"])
# Test default implementation
custom_site.register(Child, ChildAdmin)
m = custom_site._registry[Child]
request = self._mocked_authenticated_request("/child/", user_noparents)
response = m.changelist_view(request)
self.assertContains(response, "Parent object")
def test_show_all(self):
parent = Parent.objects.create(name="anything")
for i in range(1, 31):
Child.objects.create(name="name %s" % i, parent=parent)
Child.objects.create(name="filtered %s" % i, parent=parent)
# Add "show all" parameter to request
request = self.factory.get("/child/", data={ALL_VAR: ""})
request.user = self.superuser
# Test valid "show all" request (number of total objects is under max)
m = ChildAdmin(Child, custom_site)
m.list_max_show_all = 200
# 200 is the max we'll pass to ChangeList
cl = m.get_changelist_instance(request)
cl.get_results(request)
self.assertEqual(len(cl.result_list), 60)
# Test invalid "show all" request (number of total objects over max)
# falls back to paginated pages
m = ChildAdmin(Child, custom_site)
m.list_max_show_all = 30
# 30 is the max we'll pass to ChangeList for this test
cl = m.get_changelist_instance(request)
cl.get_results(request)
self.assertEqual(len(cl.result_list), 10)
def test_dynamic_list_display_links(self):
"""
Regression tests for #16257: dynamic list_display_links support.
"""
parent = Parent.objects.create(name="parent")
for i in range(1, 10):
Child.objects.create(id=i, name="child %s" % i, parent=parent, age=i)
m = DynamicListDisplayLinksChildAdmin(Child, custom_site)
superuser = self._create_superuser("superuser")
request = self._mocked_authenticated_request("/child/", superuser)
response = m.changelist_view(request)
for i in range(1, 10):
link = reverse("admin:admin_changelist_child_change", args=(i,))
self.assertContains(response, '<a href="%s">%s</a>' % (link, i))
list_display = m.get_list_display(request)
list_display_links = m.get_list_display_links(request, list_display)
self.assertEqual(list_display, ("parent", "name", "age"))
self.assertEqual(list_display_links, ["age"])
def test_no_list_display_links(self):
"""#15185 -- Allow no links from the 'change list' view grid."""
p = Parent.objects.create(name="parent")
m = NoListDisplayLinksParentAdmin(Parent, custom_site)
superuser = self._create_superuser("superuser")
request = self._mocked_authenticated_request("/parent/", superuser)
response = m.changelist_view(request)
link = reverse("admin:admin_changelist_parent_change", args=(p.pk,))
self.assertNotContains(response, '<a href="%s">' % link)
def test_clear_all_filters_link(self):
self.client.force_login(self.superuser)
url = reverse("admin:auth_user_changelist")
response = self.client.get(url)
self.assertNotContains(response, "✖ Clear all filters")
link = '<a href="%s">✖ Clear all filters</a>'
for data, href in (
({"is_staff__exact": "0"}, "?"),
(
{"is_staff__exact": "0", "username__startswith": "test"},
"?username__startswith=test",
),
(
{"is_staff__exact": "0", SEARCH_VAR: "test"},
"?%s=test" % SEARCH_VAR,
),
(
{"is_staff__exact": "0", IS_POPUP_VAR: "id"},
"?%s=id" % IS_POPUP_VAR,
),
):
with self.subTest(data=data):
response = self.client.get(url, data=data)
self.assertContains(response, link % href)
def test_clear_all_filters_link_callable_filter(self):
self.client.force_login(self.superuser)
url = reverse("admin:admin_changelist_band_changelist")
response = self.client.get(url)
self.assertNotContains(response, "✖ Clear all filters")
link = '<a href="%s">✖ Clear all filters</a>'
for data, href in (
({"nr_of_members_partition": "5"}, "?"),
(
{"nr_of_members_partition": "more", "name__startswith": "test"},
"?name__startswith=test",
),
(
{"nr_of_members_partition": "5", IS_POPUP_VAR: "id"},
"?%s=id" % IS_POPUP_VAR,
),
):
with self.subTest(data=data):
response = self.client.get(url, data=data)
self.assertContains(response, link % href)
def test_no_clear_all_filters_link(self):
self.client.force_login(self.superuser)
url = reverse("admin:auth_user_changelist")
link = ">✖ Clear all filters</a>"
for data in (
{SEARCH_VAR: "test"},
{ORDER_VAR: "-1"},
{TO_FIELD_VAR: "id"},
{PAGE_VAR: "1"},
{IS_POPUP_VAR: "1"},
{"username__startswith": "test"},
):
with self.subTest(data=data):
response = self.client.get(url, data=data)
self.assertNotContains(response, link)
def test_tuple_list_display(self):
swallow = Swallow.objects.create(origin="Africa", load="12.34", speed="22.2")
swallow2 = Swallow.objects.create(origin="Africa", load="12.34", speed="22.2")
swallow_o2o = SwallowOneToOne.objects.create(swallow=swallow2)
model_admin = SwallowAdmin(Swallow, custom_site)
superuser = self._create_superuser("superuser")
request = self._mocked_authenticated_request("/swallow/", superuser)
response = model_admin.changelist_view(request)
# just want to ensure it doesn't blow up during rendering
self.assertContains(response, str(swallow.origin))
self.assertContains(response, str(swallow.load))
self.assertContains(response, str(swallow.speed))
# Reverse one-to-one relations should work.
self.assertContains(response, '<td class="field-swallowonetoone">-</td>')
self.assertContains(
response, '<td class="field-swallowonetoone">%s</td>' % swallow_o2o
)
def test_multiuser_edit(self):
"""
Simultaneous edits of list_editable fields on the changelist by
different users must not result in one user's edits creating a new
object instead of modifying the correct existing object (#11313).
"""
# To replicate this issue, simulate the following steps:
# 1. User1 opens an admin changelist with list_editable fields.
# 2. User2 edits object "Foo" such that it moves to another page in
# the pagination order and saves.
# 3. User1 edits object "Foo" and saves.
# 4. The edit made by User1 does not get applied to object "Foo" but
# instead is used to create a new object (bug).
# For this test, order the changelist by the 'speed' attribute and
# display 3 objects per page (SwallowAdmin.list_per_page = 3).
# Setup the test to reflect the DB state after step 2 where User2 has
# edited the first swallow object's speed from '4' to '1'.
a = Swallow.objects.create(origin="Swallow A", load=4, speed=1)
b = Swallow.objects.create(origin="Swallow B", load=2, speed=2)
c = Swallow.objects.create(origin="Swallow C", load=5, speed=5)
d = Swallow.objects.create(origin="Swallow D", load=9, speed=9)
superuser = self._create_superuser("superuser")
self.client.force_login(superuser)
changelist_url = reverse("admin:admin_changelist_swallow_changelist")
# Send the POST from User1 for step 3. It's still using the changelist
# ordering from before User2's edits in step 2.
data = {
"form-TOTAL_FORMS": "3",
"form-INITIAL_FORMS": "3",
"form-MIN_NUM_FORMS": "0",
"form-MAX_NUM_FORMS": "1000",
"form-0-uuid": str(d.pk),
"form-1-uuid": str(c.pk),
"form-2-uuid": str(a.pk),
"form-0-load": "9.0",
"form-0-speed": "9.0",
"form-1-load": "5.0",
"form-1-speed": "5.0",
"form-2-load": "5.0",
"form-2-speed": "4.0",
"_save": "Save",
}
response = self.client.post(
changelist_url, data, follow=True, extra={"o": "-2"}
)
# The object User1 edited in step 3 is displayed on the changelist and
# has the correct edits applied.
self.assertContains(response, "1 swallow was changed successfully.")
self.assertContains(response, a.origin)
a.refresh_from_db()
self.assertEqual(a.load, float(data["form-2-load"]))
self.assertEqual(a.speed, float(data["form-2-speed"]))
b.refresh_from_db()
self.assertEqual(b.load, 2)
self.assertEqual(b.speed, 2)
c.refresh_from_db()
self.assertEqual(c.load, float(data["form-1-load"]))
self.assertEqual(c.speed, float(data["form-1-speed"]))
d.refresh_from_db()
self.assertEqual(d.load, float(data["form-0-load"]))
self.assertEqual(d.speed, float(data["form-0-speed"]))
# No new swallows were created.
self.assertEqual(len(Swallow.objects.all()), 4)
def test_get_edited_object_ids(self):
a = Swallow.objects.create(origin="Swallow A", load=4, speed=1)
b = Swallow.objects.create(origin="Swallow B", load=2, speed=2)
c = Swallow.objects.create(origin="Swallow C", load=5, speed=5)
superuser = self._create_superuser("superuser")
self.client.force_login(superuser)
changelist_url = reverse("admin:admin_changelist_swallow_changelist")
m = SwallowAdmin(Swallow, custom_site)
data = {
"form-TOTAL_FORMS": "3",
"form-INITIAL_FORMS": "3",
"form-MIN_NUM_FORMS": "0",
"form-MAX_NUM_FORMS": "1000",
"form-0-uuid": str(a.pk),
"form-1-uuid": str(b.pk),
"form-2-uuid": str(c.pk),
"form-0-load": "9.0",
"form-0-speed": "9.0",
"form-1-load": "5.0",
"form-1-speed": "5.0",
"form-2-load": "5.0",
"form-2-speed": "4.0",
"_save": "Save",
}
request = self.factory.post(changelist_url, data=data)
pks = m._get_edited_object_pks(request, prefix="form")
self.assertEqual(sorted(pks), sorted([str(a.pk), str(b.pk), str(c.pk)]))
def test_get_list_editable_queryset(self):
a = Swallow.objects.create(origin="Swallow A", load=4, speed=1)
Swallow.objects.create(origin="Swallow B", load=2, speed=2)
data = {
"form-TOTAL_FORMS": "2",
"form-INITIAL_FORMS": "2",
"form-MIN_NUM_FORMS": "0",
"form-MAX_NUM_FORMS": "1000",
"form-0-uuid": str(a.pk),
"form-0-load": "10",
"_save": "Save",
}
superuser = self._create_superuser("superuser")
self.client.force_login(superuser)
changelist_url = reverse("admin:admin_changelist_swallow_changelist")
m = SwallowAdmin(Swallow, custom_site)
request = self.factory.post(changelist_url, data=data)
queryset = m._get_list_editable_queryset(request, prefix="form")
self.assertEqual(queryset.count(), 1)
data["form-0-uuid"] = "INVALD_PRIMARY_KEY"
# The unfiltered queryset is returned if there's invalid data.
request = self.factory.post(changelist_url, data=data)
queryset = m._get_list_editable_queryset(request, prefix="form")
self.assertEqual(queryset.count(), 2)
def test_get_list_editable_queryset_with_regex_chars_in_prefix(self):
a = Swallow.objects.create(origin="Swallow A", load=4, speed=1)
Swallow.objects.create(origin="Swallow B", load=2, speed=2)
data = {
"form$-TOTAL_FORMS": "2",
"form$-INITIAL_FORMS": "2",
"form$-MIN_NUM_FORMS": "0",
"form$-MAX_NUM_FORMS": "1000",
"form$-0-uuid": str(a.pk),
"form$-0-load": "10",
"_save": "Save",
}
superuser = self._create_superuser("superuser")
self.client.force_login(superuser)
changelist_url = reverse("admin:admin_changelist_swallow_changelist")
m = SwallowAdmin(Swallow, custom_site)
request = self.factory.post(changelist_url, data=data)
queryset = m._get_list_editable_queryset(request, prefix="form$")
self.assertEqual(queryset.count(), 1)
def test_changelist_view_list_editable_changed_objects_uses_filter(self):
"""list_editable edits use a filtered queryset to limit memory usage."""
a = Swallow.objects.create(origin="Swallow A", load=4, speed=1)
Swallow.objects.create(origin="Swallow B", load=2, speed=2)
data = {
"form-TOTAL_FORMS": "2",
"form-INITIAL_FORMS": "2",
"form-MIN_NUM_FORMS": "0",
"form-MAX_NUM_FORMS": "1000",
"form-0-uuid": str(a.pk),
"form-0-load": "10",
"_save": "Save",
}
superuser = self._create_superuser("superuser")
self.client.force_login(superuser)
changelist_url = reverse("admin:admin_changelist_swallow_changelist")
with CaptureQueriesContext(connection) as context:
response = self.client.post(changelist_url, data=data)
self.assertEqual(response.status_code, 200)
self.assertIn("WHERE", context.captured_queries[4]["sql"])
self.assertIn("IN", context.captured_queries[4]["sql"])
# Check only the first few characters since the UUID may have dashes.
self.assertIn(str(a.pk)[:8], context.captured_queries[4]["sql"])
def test_deterministic_order_for_unordered_model(self):
"""
The primary key is used in the ordering of the changelist's results to
guarantee a deterministic order, even when the model doesn't have any
default ordering defined (#17198).
"""
superuser = self._create_superuser("superuser")
for counter in range(1, 51):
UnorderedObject.objects.create(id=counter, bool=True)
class UnorderedObjectAdmin(admin.ModelAdmin):
list_per_page = 10
def check_results_order(ascending=False):
custom_site.register(UnorderedObject, UnorderedObjectAdmin)
model_admin = UnorderedObjectAdmin(UnorderedObject, custom_site)
counter = 0 if ascending else 51
for page in range(1, 6):
request = self._mocked_authenticated_request(
"/unorderedobject/?p=%s" % page, superuser
)
response = model_admin.changelist_view(request)
for result in response.context_data["cl"].result_list:
counter += 1 if ascending else -1
self.assertEqual(result.id, counter)
custom_site.unregister(UnorderedObject)
# When no order is defined at all, everything is ordered by '-pk'.
check_results_order()
# When an order field is defined but multiple records have the same
# value for that field, make sure everything gets ordered by -pk as well.
UnorderedObjectAdmin.ordering = ["bool"]
check_results_order()
# When order fields are defined, including the pk itself, use them.
UnorderedObjectAdmin.ordering = ["bool", "-pk"]
check_results_order()
UnorderedObjectAdmin.ordering = ["bool", "pk"]
check_results_order(ascending=True)
UnorderedObjectAdmin.ordering = ["-id", "bool"]
check_results_order()
UnorderedObjectAdmin.ordering = ["id", "bool"]
check_results_order(ascending=True)
def test_deterministic_order_for_model_ordered_by_its_manager(self):
"""
The primary key is used in the ordering of the changelist's results to
guarantee a deterministic order, even when the model has a manager that
defines a default ordering (#17198).
"""
superuser = self._create_superuser("superuser")
for counter in range(1, 51):
OrderedObject.objects.create(id=counter, bool=True, number=counter)
class OrderedObjectAdmin(admin.ModelAdmin):
list_per_page = 10
def check_results_order(ascending=False):
custom_site.register(OrderedObject, OrderedObjectAdmin)
model_admin = OrderedObjectAdmin(OrderedObject, custom_site)
counter = 0 if ascending else 51
for page in range(1, 6):
request = self._mocked_authenticated_request(
"/orderedobject/?p=%s" % page, superuser
)
response = model_admin.changelist_view(request)
for result in response.context_data["cl"].result_list:
counter += 1 if ascending else -1
self.assertEqual(result.id, counter)
custom_site.unregister(OrderedObject)
# When no order is defined at all, use the model's default ordering
# (i.e. 'number').
check_results_order(ascending=True)
# When an order field is defined but multiple records have the same
# value for that field, make sure everything gets ordered by -pk as well.
OrderedObjectAdmin.ordering = ["bool"]
check_results_order()
# When order fields are defined, including the pk itself, use them.
OrderedObjectAdmin.ordering = ["bool", "-pk"]
check_results_order()
OrderedObjectAdmin.ordering = ["bool", "pk"]
check_results_order(ascending=True)
OrderedObjectAdmin.ordering = ["-id", "bool"]
check_results_order()
OrderedObjectAdmin.ordering = ["id", "bool"]
check_results_order(ascending=True)
@isolate_apps("admin_changelist")
def test_total_ordering_optimization(self):
class Related(models.Model):
unique_field = models.BooleanField(unique=True)
class Meta:
ordering = ("unique_field",)
class Model(models.Model):
unique_field = models.BooleanField(unique=True)
unique_nullable_field = models.BooleanField(unique=True, null=True)
related = models.ForeignKey(Related, models.CASCADE)
other_related = models.ForeignKey(Related, models.CASCADE)
related_unique = models.OneToOneField(Related, models.CASCADE)
field = models.BooleanField()
other_field = models.BooleanField()
null_field = models.BooleanField(null=True)
class Meta:
unique_together = {
("field", "other_field"),
("field", "null_field"),
("related", "other_related_id"),
}
class ModelAdmin(admin.ModelAdmin):
def get_queryset(self, request):
return Model.objects.none()
request = self._mocked_authenticated_request("/", self.superuser)
site = admin.AdminSite(name="admin")
model_admin = ModelAdmin(Model, site)
change_list = model_admin.get_changelist_instance(request)
tests = (
([], ["-pk"]),
# Unique non-nullable field.
(["unique_field"], ["unique_field"]),
(["-unique_field"], ["-unique_field"]),
# Unique nullable field.
(["unique_nullable_field"], ["unique_nullable_field", "-pk"]),
# Field.
(["field"], ["field", "-pk"]),
# Related field introspection is not implemented.
(["related__unique_field"], ["related__unique_field", "-pk"]),
# Related attname unique.
(["related_unique_id"], ["related_unique_id"]),
# Related ordering introspection is not implemented.
(["related_unique"], ["related_unique", "-pk"]),
# Composite unique.
(["field", "-other_field"], ["field", "-other_field"]),
# Composite unique nullable.
(["-field", "null_field"], ["-field", "null_field", "-pk"]),
# Composite unique and nullable.
(
["-field", "null_field", "other_field"],
["-field", "null_field", "other_field"],
),
# Composite unique attnames.
(["related_id", "-other_related_id"], ["related_id", "-other_related_id"]),
# Composite unique names.
(["related", "-other_related_id"], ["related", "-other_related_id", "-pk"]),
)
# F() objects composite unique.
total_ordering = [F("field"), F("other_field").desc(nulls_last=True)]
# F() objects composite unique nullable.
non_total_ordering = [F("field"), F("null_field").desc(nulls_last=True)]
tests += (
(total_ordering, total_ordering),
(non_total_ordering, non_total_ordering + ["-pk"]),
)
for ordering, expected in tests:
with self.subTest(ordering=ordering):
self.assertEqual(
change_list._get_deterministic_ordering(ordering), expected
)
@isolate_apps("admin_changelist")
def test_total_ordering_optimization_meta_constraints(self):
class Related(models.Model):
unique_field = models.BooleanField(unique=True)
class Meta:
ordering = ("unique_field",)
class Model(models.Model):
field_1 = models.BooleanField()
field_2 = models.BooleanField()
field_3 = models.BooleanField()
field_4 = models.BooleanField()
field_5 = models.BooleanField()
field_6 = models.BooleanField()
nullable_1 = models.BooleanField(null=True)
nullable_2 = models.BooleanField(null=True)
related_1 = models.ForeignKey(Related, models.CASCADE)
related_2 = models.ForeignKey(Related, models.CASCADE)
related_3 = models.ForeignKey(Related, models.CASCADE)
related_4 = models.ForeignKey(Related, models.CASCADE)
class Meta:
constraints = [
*[
models.UniqueConstraint(fields=fields, name="".join(fields))
for fields in (
["field_1"],
["nullable_1"],
["related_1"],
["related_2_id"],
["field_2", "field_3"],
["field_2", "nullable_2"],
["field_2", "related_3"],
["field_3", "related_4_id"],
)
],
models.CheckConstraint(check=models.Q(id__gt=0), name="foo"),
models.UniqueConstraint(
fields=["field_5"],
condition=models.Q(id__gt=10),
name="total_ordering_1",
),
models.UniqueConstraint(
fields=["field_6"],
condition=models.Q(),
name="total_ordering",
),
]
class ModelAdmin(admin.ModelAdmin):
def get_queryset(self, request):
return Model.objects.none()
request = self._mocked_authenticated_request("/", self.superuser)
site = admin.AdminSite(name="admin")
model_admin = ModelAdmin(Model, site)
change_list = model_admin.get_changelist_instance(request)
tests = (
# Unique non-nullable field.
(["field_1"], ["field_1"]),
# Unique nullable field.
(["nullable_1"], ["nullable_1", "-pk"]),
# Related attname unique.
(["related_1_id"], ["related_1_id"]),
(["related_2_id"], ["related_2_id"]),
# Related ordering introspection is not implemented.
(["related_1"], ["related_1", "-pk"]),
# Composite unique.
(["-field_2", "field_3"], ["-field_2", "field_3"]),
# Composite unique nullable.
(["field_2", "-nullable_2"], ["field_2", "-nullable_2", "-pk"]),
# Composite unique and nullable.
(
["field_2", "-nullable_2", "field_3"],
["field_2", "-nullable_2", "field_3"],
),
# Composite field and related field name.
(["field_2", "-related_3"], ["field_2", "-related_3", "-pk"]),
(["field_3", "related_4"], ["field_3", "related_4", "-pk"]),
# Composite field and related field attname.
(["field_2", "related_3_id"], ["field_2", "related_3_id"]),
(["field_3", "-related_4_id"], ["field_3", "-related_4_id"]),
# Partial unique constraint is ignored.
(["field_5"], ["field_5", "-pk"]),
# Unique constraint with an empty condition.
(["field_6"], ["field_6"]),
)
for ordering, expected in tests:
with self.subTest(ordering=ordering):
self.assertEqual(
change_list._get_deterministic_ordering(ordering), expected
)
def test_dynamic_list_filter(self):
"""
Regression tests for ticket #17646: dynamic list_filter support.
"""
parent = Parent.objects.create(name="parent")
for i in range(10):
Child.objects.create(name="child %s" % i, parent=parent)
user_noparents = self._create_superuser("noparents")
user_parents = self._create_superuser("parents")
# Test with user 'noparents'
m = DynamicListFilterChildAdmin(Child, custom_site)
request = self._mocked_authenticated_request("/child/", user_noparents)
response = m.changelist_view(request)
self.assertEqual(response.context_data["cl"].list_filter, ["name", "age"])
# Test with user 'parents'
m = DynamicListFilterChildAdmin(Child, custom_site)
request = self._mocked_authenticated_request("/child/", user_parents)
response = m.changelist_view(request)
self.assertEqual(
response.context_data["cl"].list_filter, ("parent", "name", "age")
)
def test_dynamic_search_fields(self):
child = self._create_superuser("child")
m = DynamicSearchFieldsChildAdmin(Child, custom_site)
request = self._mocked_authenticated_request("/child/", child)
response = m.changelist_view(request)
self.assertEqual(response.context_data["cl"].search_fields, ("name", "age"))
def test_pagination_page_range(self):
"""
Regression tests for ticket #15653: ensure the number of pages
generated for changelist views are correct.
"""
# instantiating and setting up ChangeList object
m = GroupAdmin(Group, custom_site)
request = self.factory.get("/group/")
request.user = self.superuser
cl = m.get_changelist_instance(request)
cl.list_per_page = 10
ELLIPSIS = cl.paginator.ELLIPSIS
for number, pages, expected in [
(1, 1, []),
(1, 2, [1, 2]),
(6, 11, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]),
(6, 12, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),
(6, 13, [1, 2, 3, 4, 5, 6, 7, 8, 9, ELLIPSIS, 12, 13]),
(7, 12, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),
(7, 13, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]),
(7, 14, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ELLIPSIS, 13, 14]),
(8, 13, [1, 2, ELLIPSIS, 5, 6, 7, 8, 9, 10, 11, 12, 13]),
(8, 14, [1, 2, ELLIPSIS, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),
(8, 15, [1, 2, ELLIPSIS, 5, 6, 7, 8, 9, 10, 11, ELLIPSIS, 14, 15]),
]:
with self.subTest(number=number, pages=pages):
# assuming exactly `pages * cl.list_per_page` objects
Group.objects.all().delete()
for i in range(pages * cl.list_per_page):
Group.objects.create(name="test band")
# setting page number and calculating page range
cl.page_num = number
cl.get_results(request)
self.assertEqual(list(pagination(cl)["page_range"]), expected)
def test_object_tools_displayed_no_add_permission(self):
"""
When ModelAdmin.has_add_permission() returns False, the object-tools
block is still shown.
"""
superuser = self._create_superuser("superuser")
m = EventAdmin(Event, custom_site)
request = self._mocked_authenticated_request("/event/", superuser)
self.assertFalse(m.has_add_permission(request))
response = m.changelist_view(request)
self.assertIn('<ul class="object-tools">', response.rendered_content)
# The "Add" button inside the object-tools shouldn't appear.
self.assertNotIn("Add ", response.rendered_content)
def test_search_help_text(self):
superuser = self._create_superuser("superuser")
m = BandAdmin(Band, custom_site)
# search_fields without search_help_text.
m.search_fields = ["name"]
request = self._mocked_authenticated_request("/band/", superuser)
response = m.changelist_view(request)
self.assertIsNone(response.context_data["cl"].search_help_text)
self.assertNotContains(response, '<div class="help id="searchbar_helptext">')
# search_fields with search_help_text.
m.search_help_text = "Search help text"
request = self._mocked_authenticated_request("/band/", superuser)
response = m.changelist_view(request)
self.assertEqual(
response.context_data["cl"].search_help_text, "Search help text"
)
self.assertContains(
response, '<div class="help" id="searchbar_helptext">Search help text</div>'
)
self.assertContains(
response,
'<input type="text" size="40" name="q" value="" id="searchbar" '
'aria-describedby="searchbar_helptext">',
)
class GetAdminLogTests(TestCase):
def test_custom_user_pk_not_named_id(self):
"""
{% get_admin_log %} works if the user model's primary key isn't named
'id'.
"""
context = Context({"user": CustomIdUser()})
template = Template(
"{% load log %}{% get_admin_log 10 as admin_log for_user user %}"
)
# This template tag just logs.
self.assertEqual(template.render(context), "")
def test_no_user(self):
"""{% get_admin_log %} works without specifying a user."""
user = User(username="jondoe", password="secret", email="[email protected]")
user.save()
ct = ContentType.objects.get_for_model(User)
LogEntry.objects.log_action(user.pk, ct.pk, user.pk, repr(user), 1)
t = Template(
"{% load log %}"
"{% get_admin_log 100 as admin_log %}"
"{% for entry in admin_log %}"
"{{ entry|safe }}"
"{% endfor %}"
)
self.assertEqual(t.render(Context({})), "Added “<User: jondoe>”.")
def test_missing_args(self):
msg = "'get_admin_log' statements require two arguments"
with self.assertRaisesMessage(TemplateSyntaxError, msg):
Template("{% load log %}{% get_admin_log 10 as %}")
def test_non_integer_limit(self):
msg = "First argument to 'get_admin_log' must be an integer"
with self.assertRaisesMessage(TemplateSyntaxError, msg):
Template(
'{% load log %}{% get_admin_log "10" as admin_log for_user user %}'
)
def test_without_as(self):
msg = "Second argument to 'get_admin_log' must be 'as'"
with self.assertRaisesMessage(TemplateSyntaxError, msg):
Template("{% load log %}{% get_admin_log 10 ad admin_log for_user user %}")
def test_without_for_user(self):
msg = "Fourth argument to 'get_admin_log' must be 'for_user'"
with self.assertRaisesMessage(TemplateSyntaxError, msg):
Template("{% load log %}{% get_admin_log 10 as admin_log foruser user %}")
@override_settings(ROOT_URLCONF="admin_changelist.urls")
class SeleniumTests(AdminSeleniumTestCase):
available_apps = ["admin_changelist"] + AdminSeleniumTestCase.available_apps
def setUp(self):
User.objects.create_superuser(username="super", password="secret", email=None)
def test_add_row_selection(self):
"""
The status line for selected rows gets updated correctly (#22038).
"""
from selenium.webdriver.common.by import By
self.admin_login(username="super", password="secret")
self.selenium.get(self.live_server_url + reverse("admin:auth_user_changelist"))
form_id = "#changelist-form"
# Test amount of rows in the Changelist
rows = self.selenium.find_elements(
By.CSS_SELECTOR, "%s #result_list tbody tr" % form_id
)
self.assertEqual(len(rows), 1)
row = rows[0]
selection_indicator = self.selenium.find_element(
By.CSS_SELECTOR, "%s .action-counter" % form_id
)
all_selector = self.selenium.find_element(By.ID, "action-toggle")
row_selector = self.selenium.find_element(
By.CSS_SELECTOR,
"%s #result_list tbody tr:first-child .action-select" % form_id,
)
# Test current selection
self.assertEqual(selection_indicator.text, "0 of 1 selected")
self.assertIs(all_selector.get_property("checked"), False)
self.assertEqual(row.get_attribute("class"), "")
# Select a row and check again
row_selector.click()
self.assertEqual(selection_indicator.text, "1 of 1 selected")
self.assertIs(all_selector.get_property("checked"), True)
self.assertEqual(row.get_attribute("class"), "selected")
# Deselect a row and check again
row_selector.click()
self.assertEqual(selection_indicator.text, "0 of 1 selected")
self.assertIs(all_selector.get_property("checked"), False)
self.assertEqual(row.get_attribute("class"), "")
def test_modifier_allows_multiple_section(self):
"""
Selecting a row and then selecting another row whilst holding shift
should select all rows in-between.
"""
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
Parent.objects.bulk_create([Parent(name="parent%d" % i) for i in range(5)])
self.admin_login(username="super", password="secret")
self.selenium.get(
self.live_server_url + reverse("admin:admin_changelist_parent_changelist")
)
checkboxes = self.selenium.find_elements(
By.CSS_SELECTOR, "tr input.action-select"
)
self.assertEqual(len(checkboxes), 5)
for c in checkboxes:
self.assertIs(c.get_property("checked"), False)
# Check first row. Hold-shift and check next-to-last row.
checkboxes[0].click()
ActionChains(self.selenium).key_down(Keys.SHIFT).click(checkboxes[-2]).key_up(
Keys.SHIFT
).perform()
for c in checkboxes[:-2]:
self.assertIs(c.get_property("checked"), True)
self.assertIs(checkboxes[-1].get_property("checked"), False)
def test_select_all_across_pages(self):
from selenium.webdriver.common.by import By
Parent.objects.bulk_create([Parent(name="parent%d" % i) for i in range(101)])
self.admin_login(username="super", password="secret")
self.selenium.get(
self.live_server_url + reverse("admin:admin_changelist_parent_changelist")
)
selection_indicator = self.selenium.find_element(
By.CSS_SELECTOR, ".action-counter"
)
select_all_indicator = self.selenium.find_element(
By.CSS_SELECTOR, ".actions .all"
)
question = self.selenium.find_element(By.CSS_SELECTOR, ".actions > .question")
clear = self.selenium.find_element(By.CSS_SELECTOR, ".actions > .clear")
select_all = self.selenium.find_element(By.ID, "action-toggle")
select_across = self.selenium.find_elements(By.NAME, "select_across")
self.assertIs(question.is_displayed(), False)
self.assertIs(clear.is_displayed(), False)
self.assertIs(select_all.get_property("checked"), False)
for hidden_input in select_across:
self.assertEqual(hidden_input.get_property("value"), "0")
self.assertIs(selection_indicator.is_displayed(), True)
self.assertEqual(selection_indicator.text, "0 of 100 selected")
self.assertIs(select_all_indicator.is_displayed(), False)
select_all.click()
self.assertIs(question.is_displayed(), True)
self.assertIs(clear.is_displayed(), False)
self.assertIs(select_all.get_property("checked"), True)
for hidden_input in select_across:
self.assertEqual(hidden_input.get_property("value"), "0")
self.assertIs(selection_indicator.is_displayed(), True)
self.assertEqual(selection_indicator.text, "100 of 100 selected")
self.assertIs(select_all_indicator.is_displayed(), False)
question.click()
self.assertIs(question.is_displayed(), False)
self.assertIs(clear.is_displayed(), True)
self.assertIs(select_all.get_property("checked"), True)
for hidden_input in select_across:
self.assertEqual(hidden_input.get_property("value"), "1")
self.assertIs(selection_indicator.is_displayed(), False)
self.assertIs(select_all_indicator.is_displayed(), True)
clear.click()
self.assertIs(question.is_displayed(), False)
self.assertIs(clear.is_displayed(), False)
self.assertIs(select_all.get_property("checked"), False)
for hidden_input in select_across:
self.assertEqual(hidden_input.get_property("value"), "0")
self.assertIs(selection_indicator.is_displayed(), True)
self.assertEqual(selection_indicator.text, "0 of 100 selected")
self.assertIs(select_all_indicator.is_displayed(), False)
def test_actions_warn_on_pending_edits(self):
from selenium.webdriver.common.by import By
Parent.objects.create(name="foo")
self.admin_login(username="super", password="secret")
self.selenium.get(
self.live_server_url + reverse("admin:admin_changelist_parent_changelist")
)
name_input = self.selenium.find_element(By.ID, "id_form-0-name")
name_input.clear()
name_input.send_keys("bar")
self.selenium.find_element(By.ID, "action-toggle").click()
self.selenium.find_element(By.NAME, "index").click() # Go
alert = self.selenium.switch_to.alert
try:
self.assertEqual(
alert.text,
"You have unsaved changes on individual editable fields. If you "
"run an action, your unsaved changes will be lost.",
)
finally:
alert.dismiss()
def test_save_with_changes_warns_on_pending_action(self):
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
Parent.objects.create(name="parent")
self.admin_login(username="super", password="secret")
self.selenium.get(
self.live_server_url + reverse("admin:admin_changelist_parent_changelist")
)
name_input = self.selenium.find_element(By.ID, "id_form-0-name")
name_input.clear()
name_input.send_keys("other name")
Select(self.selenium.find_element(By.NAME, "action")).select_by_value(
"delete_selected"
)
self.selenium.find_element(By.NAME, "_save").click()
alert = self.selenium.switch_to.alert
try:
self.assertEqual(
alert.text,
"You have selected an action, but you haven’t saved your "
"changes to individual fields yet. Please click OK to save. "
"You’ll need to re-run the action.",
)
finally:
alert.dismiss()
def test_save_without_changes_warns_on_pending_action(self):
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
Parent.objects.create(name="parent")
self.admin_login(username="super", password="secret")
self.selenium.get(
self.live_server_url + reverse("admin:admin_changelist_parent_changelist")
)
Select(self.selenium.find_element(By.NAME, "action")).select_by_value(
"delete_selected"
)
self.selenium.find_element(By.NAME, "_save").click()
alert = self.selenium.switch_to.alert
try:
self.assertEqual(
alert.text,
"You have selected an action, and you haven’t made any "
"changes on individual fields. You’re probably looking for "
"the Go button rather than the Save button.",
)
finally:
alert.dismiss()
def test_collapse_filters(self):
from selenium.webdriver.common.by import By
self.admin_login(username="super", password="secret")
self.selenium.get(self.live_server_url + reverse("admin:auth_user_changelist"))
# The UserAdmin has 3 field filters by default: "staff status",
# "superuser status", and "active".
details = self.selenium.find_elements(By.CSS_SELECTOR, "details")
# All filters are opened at first.
for detail in details:
self.assertTrue(detail.get_attribute("open"))
# Collapse "staff' and "superuser" filters.
for detail in details[:2]:
summary = detail.find_element(By.CSS_SELECTOR, "summary")
summary.click()
self.assertFalse(detail.get_attribute("open"))
# Filters are in the same state after refresh.
self.selenium.refresh()
self.assertFalse(
self.selenium.find_element(
By.CSS_SELECTOR, "[data-filter-title='staff status']"
).get_attribute("open")
)
self.assertFalse(
self.selenium.find_element(
By.CSS_SELECTOR, "[data-filter-title='superuser status']"
).get_attribute("open")
)
self.assertTrue(
self.selenium.find_element(
By.CSS_SELECTOR, "[data-filter-title='active']"
).get_attribute("open")
)
# Collapse a filter on another view (Bands).
self.selenium.get(
self.live_server_url + reverse("admin:admin_changelist_band_changelist")
)
self.selenium.find_element(By.CSS_SELECTOR, "summary").click()
# Go to Users view and then, back again to Bands view.
self.selenium.get(self.live_server_url + reverse("admin:auth_user_changelist"))
self.selenium.get(
self.live_server_url + reverse("admin:admin_changelist_band_changelist")
)
# The filter remains in the same state.
self.assertFalse(
self.selenium.find_element(
By.CSS_SELECTOR,
"[data-filter-title='number of members']",
).get_attribute("open")
)
|
4380a55313b51f9eabe20e9bb8c9f21c730d5537c9680d0ddb7ff7b6e5f78ac4 | 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)
|
6e41b7670d4ed81c8703e029462a242a5d01537b51a54dbfd7451943a05c543a | import os
import signal
import subprocess
import sys
from pathlib import Path
from unittest import mock, skipUnless
from django.db import connection
from django.db.backends.postgresql.client import DatabaseClient
from django.test import SimpleTestCase
class PostgreSqlDbshellCommandTestCase(SimpleTestCase):
def settings_to_cmd_args_env(self, settings_dict, parameters=None):
if parameters is None:
parameters = []
return DatabaseClient.settings_to_cmd_args_env(settings_dict, parameters)
def test_basic(self):
self.assertEqual(
self.settings_to_cmd_args_env(
{
"NAME": "dbname",
"USER": "someuser",
"PASSWORD": "somepassword",
"HOST": "somehost",
"PORT": "444",
}
),
(
["psql", "-U", "someuser", "-h", "somehost", "-p", "444", "dbname"],
{"PGPASSWORD": "somepassword"},
),
)
def test_nopass(self):
self.assertEqual(
self.settings_to_cmd_args_env(
{
"NAME": "dbname",
"USER": "someuser",
"HOST": "somehost",
"PORT": "444",
}
),
(
["psql", "-U", "someuser", "-h", "somehost", "-p", "444", "dbname"],
None,
),
)
def test_ssl_certificate(self):
self.assertEqual(
self.settings_to_cmd_args_env(
{
"NAME": "dbname",
"USER": "someuser",
"HOST": "somehost",
"PORT": "444",
"OPTIONS": {
"sslmode": "verify-ca",
"sslrootcert": "root.crt",
"sslcert": "client.crt",
"sslkey": "client.key",
},
}
),
(
["psql", "-U", "someuser", "-h", "somehost", "-p", "444", "dbname"],
{
"PGSSLCERT": "client.crt",
"PGSSLKEY": "client.key",
"PGSSLMODE": "verify-ca",
"PGSSLROOTCERT": "root.crt",
},
),
)
def test_service(self):
self.assertEqual(
self.settings_to_cmd_args_env({"OPTIONS": {"service": "django_test"}}),
(["psql"], {"PGSERVICE": "django_test"}),
)
def test_passfile(self):
self.assertEqual(
self.settings_to_cmd_args_env(
{
"NAME": "dbname",
"USER": "someuser",
"HOST": "somehost",
"PORT": "444",
"OPTIONS": {
"passfile": "~/.custompgpass",
},
}
),
(
["psql", "-U", "someuser", "-h", "somehost", "-p", "444", "dbname"],
{"PGPASSFILE": "~/.custompgpass"},
),
)
self.assertEqual(
self.settings_to_cmd_args_env(
{
"OPTIONS": {
"service": "django_test",
"passfile": "~/.custompgpass",
},
}
),
(
["psql"],
{"PGSERVICE": "django_test", "PGPASSFILE": "~/.custompgpass"},
),
)
def test_column(self):
self.assertEqual(
self.settings_to_cmd_args_env(
{
"NAME": "dbname",
"USER": "some:user",
"PASSWORD": "some:password",
"HOST": "::1",
"PORT": "444",
}
),
(
["psql", "-U", "some:user", "-h", "::1", "-p", "444", "dbname"],
{"PGPASSWORD": "some:password"},
),
)
def test_accent(self):
username = "rôle"
password = "sésame"
self.assertEqual(
self.settings_to_cmd_args_env(
{
"NAME": "dbname",
"USER": username,
"PASSWORD": password,
"HOST": "somehost",
"PORT": "444",
}
),
(
["psql", "-U", username, "-h", "somehost", "-p", "444", "dbname"],
{"PGPASSWORD": password},
),
)
def test_parameters(self):
self.assertEqual(
self.settings_to_cmd_args_env({"NAME": "dbname"}, ["--help"]),
(["psql", "--help", "dbname"], None),
)
@skipUnless(connection.vendor == "postgresql", "Requires a PostgreSQL connection")
def test_sigint_handler(self):
"""SIGINT is ignored in Python and passed to psql to abort queries."""
def _mock_subprocess_run(*args, **kwargs):
handler = signal.getsignal(signal.SIGINT)
self.assertEqual(handler, signal.SIG_IGN)
sigint_handler = signal.getsignal(signal.SIGINT)
# The default handler isn't SIG_IGN.
self.assertNotEqual(sigint_handler, signal.SIG_IGN)
with mock.patch("subprocess.run", new=_mock_subprocess_run):
connection.client.runshell([])
# dbshell restores the original handler.
self.assertEqual(sigint_handler, signal.getsignal(signal.SIGINT))
def test_crash_password_does_not_leak(self):
# The password doesn't leak in an exception that results from a client
# crash.
args, env = self.settings_to_cmd_args_env({"PASSWORD": "somepassword"}, [])
if env:
env = {**os.environ, **env}
fake_client = Path(__file__).with_name("fake_client.py")
args[0:1] = [sys.executable, str(fake_client)]
with self.assertRaises(subprocess.CalledProcessError) as ctx:
subprocess.run(args, check=True, env=env)
self.assertNotIn("somepassword", str(ctx.exception))
|
10ac540260074f154b50749abef91efcf19be2ebddd4e4b56869c1c9b623b78c | from datetime import date
from decimal import Decimal
from unittest import mock
from django.db import connection, transaction
from django.db.models import (
Case,
Count,
DecimalField,
F,
FilteredRelation,
Q,
Sum,
When,
)
from django.test import TestCase
from django.test.testcases import skipUnlessDBFeature
from .models import (
Author,
Book,
BookDailySales,
Borrower,
Currency,
Editor,
ExchangeRate,
RentalSession,
Reservation,
Seller,
)
class FilteredRelationTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.author1 = Author.objects.create(name="Alice")
cls.author2 = Author.objects.create(name="Jane")
cls.editor_a = Editor.objects.create(name="a")
cls.editor_b = Editor.objects.create(name="b")
cls.book1 = Book.objects.create(
title="Poem by Alice",
editor=cls.editor_a,
author=cls.author1,
)
cls.book1.generic_author.set([cls.author2])
cls.book2 = Book.objects.create(
title="The book by Jane A",
editor=cls.editor_b,
author=cls.author2,
)
cls.book3 = Book.objects.create(
title="The book by Jane B",
editor=cls.editor_b,
author=cls.author2,
)
cls.book4 = Book.objects.create(
title="The book by Alice",
editor=cls.editor_a,
author=cls.author1,
)
cls.author1.favorite_books.add(cls.book2)
cls.author1.favorite_books.add(cls.book3)
def test_select_related(self):
qs = (
Author.objects.annotate(
book_join=FilteredRelation("book"),
)
.select_related("book_join__editor")
.order_by("pk", "book_join__pk")
)
with self.assertNumQueries(1):
self.assertQuerySetEqual(
qs,
[
(self.author1, self.book1, self.editor_a, self.author1),
(self.author1, self.book4, self.editor_a, self.author1),
(self.author2, self.book2, self.editor_b, self.author2),
(self.author2, self.book3, self.editor_b, self.author2),
],
lambda x: (x, x.book_join, x.book_join.editor, x.book_join.author),
)
def test_select_related_multiple(self):
qs = (
Book.objects.annotate(
author_join=FilteredRelation("author"),
editor_join=FilteredRelation("editor"),
)
.select_related("author_join", "editor_join")
.order_by("pk")
)
self.assertQuerySetEqual(
qs,
[
(self.book1, self.author1, self.editor_a),
(self.book2, self.author2, self.editor_b),
(self.book3, self.author2, self.editor_b),
(self.book4, self.author1, self.editor_a),
],
lambda x: (x, x.author_join, x.editor_join),
)
def test_select_related_with_empty_relation(self):
qs = (
Author.objects.annotate(
book_join=FilteredRelation("book", condition=Q(pk=-1)),
)
.select_related("book_join")
.order_by("pk")
)
self.assertSequenceEqual(qs, [self.author1, self.author2])
def test_select_related_foreign_key(self):
qs = (
Book.objects.annotate(
author_join=FilteredRelation("author"),
)
.select_related("author_join")
.order_by("pk")
)
with self.assertNumQueries(1):
self.assertQuerySetEqual(
qs,
[
(self.book1, self.author1),
(self.book2, self.author2),
(self.book3, self.author2),
(self.book4, self.author1),
],
lambda x: (x, x.author_join),
)
@skipUnlessDBFeature("has_select_for_update", "has_select_for_update_of")
def test_select_related_foreign_key_for_update_of(self):
with transaction.atomic():
qs = (
Book.objects.annotate(
author_join=FilteredRelation("author"),
)
.select_related("author_join")
.select_for_update(of=("self",))
.order_by("pk")
)
with self.assertNumQueries(1):
self.assertQuerySetEqual(
qs,
[
(self.book1, self.author1),
(self.book2, self.author2),
(self.book3, self.author2),
(self.book4, self.author1),
],
lambda x: (x, x.author_join),
)
def test_without_join(self):
self.assertCountEqual(
Author.objects.annotate(
book_alice=FilteredRelation(
"book", condition=Q(book__title__iexact="poem by alice")
),
),
[self.author1, self.author2],
)
def test_with_join(self):
self.assertSequenceEqual(
Author.objects.annotate(
book_alice=FilteredRelation(
"book", condition=Q(book__title__iexact="poem by alice")
),
).filter(book_alice__isnull=False),
[self.author1],
)
def test_with_exclude(self):
self.assertSequenceEqual(
Author.objects.annotate(
book_alice=FilteredRelation(
"book", condition=Q(book__title__iexact="poem by alice")
),
).exclude(book_alice__isnull=False),
[self.author2],
)
def test_with_join_and_complex_condition(self):
self.assertSequenceEqual(
Author.objects.annotate(
book_alice=FilteredRelation(
"book",
condition=Q(
Q(book__title__iexact="poem by alice")
| Q(book__state=Book.RENTED)
),
),
).filter(book_alice__isnull=False),
[self.author1],
)
def test_internal_queryset_alias_mapping(self):
queryset = Author.objects.annotate(
book_alice=FilteredRelation(
"book", condition=Q(book__title__iexact="poem by alice")
),
).filter(book_alice__isnull=False)
self.assertIn(
"INNER JOIN {} book_alice ON".format(
connection.ops.quote_name("filtered_relation_book")
),
str(queryset.query),
)
def test_multiple(self):
qs = (
Author.objects.annotate(
book_title_alice=FilteredRelation(
"book", condition=Q(book__title__contains="Alice")
),
book_title_jane=FilteredRelation(
"book", condition=Q(book__title__icontains="Jane")
),
)
.filter(name="Jane")
.values("book_title_alice__title", "book_title_jane__title")
)
empty = "" if connection.features.interprets_empty_strings_as_nulls else None
self.assertCountEqual(
qs,
[
{
"book_title_alice__title": empty,
"book_title_jane__title": "The book by Jane A",
},
{
"book_title_alice__title": empty,
"book_title_jane__title": "The book by Jane B",
},
],
)
def test_with_multiple_filter(self):
self.assertSequenceEqual(
Author.objects.annotate(
book_editor_a=FilteredRelation(
"book",
condition=Q(
book__title__icontains="book", book__editor_id=self.editor_a.pk
),
),
).filter(book_editor_a__isnull=False),
[self.author1],
)
def test_multiple_times(self):
self.assertSequenceEqual(
Author.objects.annotate(
book_title_alice=FilteredRelation(
"book", condition=Q(book__title__icontains="alice")
),
)
.filter(book_title_alice__isnull=False)
.filter(book_title_alice__isnull=False)
.distinct(),
[self.author1],
)
def test_exclude_relation_with_join(self):
self.assertSequenceEqual(
Author.objects.annotate(
book_alice=FilteredRelation(
"book", condition=~Q(book__title__icontains="alice")
),
)
.filter(book_alice__isnull=False)
.distinct(),
[self.author2],
)
def test_with_m2m(self):
qs = Author.objects.annotate(
favorite_books_written_by_jane=FilteredRelation(
"favorite_books",
condition=Q(favorite_books__in=[self.book2]),
),
).filter(favorite_books_written_by_jane__isnull=False)
self.assertSequenceEqual(qs, [self.author1])
def test_with_m2m_deep(self):
qs = Author.objects.annotate(
favorite_books_written_by_jane=FilteredRelation(
"favorite_books",
condition=Q(favorite_books__author=self.author2),
),
).filter(favorite_books_written_by_jane__title="The book by Jane B")
self.assertSequenceEqual(qs, [self.author1])
def test_with_m2m_multijoin(self):
qs = (
Author.objects.annotate(
favorite_books_written_by_jane=FilteredRelation(
"favorite_books",
condition=Q(favorite_books__author=self.author2),
)
)
.filter(favorite_books_written_by_jane__editor__name="b")
.distinct()
)
self.assertSequenceEqual(qs, [self.author1])
def test_values_list(self):
self.assertSequenceEqual(
Author.objects.annotate(
book_alice=FilteredRelation(
"book", condition=Q(book__title__iexact="poem by alice")
),
)
.filter(book_alice__isnull=False)
.values_list("book_alice__title", flat=True),
["Poem by Alice"],
)
def test_values(self):
self.assertSequenceEqual(
Author.objects.annotate(
book_alice=FilteredRelation(
"book", condition=Q(book__title__iexact="poem by alice")
),
)
.filter(book_alice__isnull=False)
.values(),
[
{
"id": self.author1.pk,
"name": "Alice",
"content_type_id": None,
"object_id": None,
}
],
)
def test_extra(self):
self.assertSequenceEqual(
Author.objects.annotate(
book_alice=FilteredRelation(
"book", condition=Q(book__title__iexact="poem by alice")
),
)
.filter(book_alice__isnull=False)
.extra(where=["1 = 1"]),
[self.author1],
)
@skipUnlessDBFeature("supports_select_union")
def test_union(self):
qs1 = Author.objects.annotate(
book_alice=FilteredRelation(
"book", condition=Q(book__title__iexact="poem by alice")
),
).filter(book_alice__isnull=False)
qs2 = Author.objects.annotate(
book_jane=FilteredRelation(
"book", condition=Q(book__title__iexact="the book by jane a")
),
).filter(book_jane__isnull=False)
self.assertSequenceEqual(qs1.union(qs2), [self.author1, self.author2])
@skipUnlessDBFeature("supports_select_intersection")
def test_intersection(self):
qs1 = Author.objects.annotate(
book_alice=FilteredRelation(
"book", condition=Q(book__title__iexact="poem by alice")
),
).filter(book_alice__isnull=False)
qs2 = Author.objects.annotate(
book_jane=FilteredRelation(
"book", condition=Q(book__title__iexact="the book by jane a")
),
).filter(book_jane__isnull=False)
self.assertSequenceEqual(qs1.intersection(qs2), [])
@skipUnlessDBFeature("supports_select_difference")
def test_difference(self):
qs1 = Author.objects.annotate(
book_alice=FilteredRelation(
"book", condition=Q(book__title__iexact="poem by alice")
),
).filter(book_alice__isnull=False)
qs2 = Author.objects.annotate(
book_jane=FilteredRelation(
"book", condition=Q(book__title__iexact="the book by jane a")
),
).filter(book_jane__isnull=False)
self.assertSequenceEqual(qs1.difference(qs2), [self.author1])
def test_select_for_update(self):
self.assertSequenceEqual(
Author.objects.annotate(
book_jane=FilteredRelation(
"book", condition=Q(book__title__iexact="the book by jane a")
),
)
.filter(book_jane__isnull=False)
.select_for_update(),
[self.author2],
)
def test_defer(self):
# One query for the list and one query for the deferred title.
with self.assertNumQueries(2):
self.assertQuerySetEqual(
Author.objects.annotate(
book_alice=FilteredRelation(
"book", condition=Q(book__title__iexact="poem by alice")
),
)
.filter(book_alice__isnull=False)
.select_related("book_alice")
.defer("book_alice__title"),
["Poem by Alice"],
lambda author: author.book_alice.title,
)
def test_only_not_supported(self):
msg = "only() is not supported with FilteredRelation."
with self.assertRaisesMessage(ValueError, msg):
Author.objects.annotate(
book_alice=FilteredRelation(
"book", condition=Q(book__title__iexact="poem by alice")
),
).filter(book_alice__isnull=False).select_related("book_alice").only(
"book_alice__state"
)
def test_as_subquery(self):
inner_qs = Author.objects.annotate(
book_alice=FilteredRelation(
"book", condition=Q(book__title__iexact="poem by alice")
),
).filter(book_alice__isnull=False)
qs = Author.objects.filter(id__in=inner_qs)
self.assertSequenceEqual(qs, [self.author1])
def test_nested_foreign_key(self):
qs = (
Author.objects.annotate(
book_editor_worked_with=FilteredRelation(
"book__editor",
condition=Q(book__title__icontains="book by"),
),
)
.filter(
book_editor_worked_with__isnull=False,
)
.select_related(
"book_editor_worked_with",
)
.order_by("pk", "book_editor_worked_with__pk")
)
with self.assertNumQueries(1):
self.assertQuerySetEqual(
qs,
[
(self.author1, self.editor_a),
(self.author2, self.editor_b),
(self.author2, self.editor_b),
],
lambda x: (x, x.book_editor_worked_with),
)
def test_nested_foreign_key_nested_field(self):
qs = (
Author.objects.annotate(
book_editor_worked_with=FilteredRelation(
"book__editor", condition=Q(book__title__icontains="book by")
),
)
.filter(
book_editor_worked_with__isnull=False,
)
.values(
"name",
"book_editor_worked_with__name",
)
.order_by("name", "book_editor_worked_with__name")
.distinct()
)
self.assertSequenceEqual(
qs,
[
{
"name": self.author1.name,
"book_editor_worked_with__name": self.editor_a.name,
},
{
"name": self.author2.name,
"book_editor_worked_with__name": self.editor_b.name,
},
],
)
def test_nested_foreign_key_filtered_base_object(self):
qs = (
Author.objects.annotate(
alice_editors=FilteredRelation(
"book__editor",
condition=Q(name="Alice"),
),
)
.values(
"name",
"alice_editors__pk",
)
.order_by("name", "alice_editors__name")
.distinct()
)
self.assertSequenceEqual(
qs,
[
{"name": self.author1.name, "alice_editors__pk": self.editor_a.pk},
{"name": self.author2.name, "alice_editors__pk": None},
],
)
def test_nested_m2m_filtered(self):
qs = (
Book.objects.annotate(
favorite_book=FilteredRelation(
"author__favorite_books",
condition=Q(author__favorite_books__title__icontains="book by"),
),
)
.values(
"title",
"favorite_book__pk",
)
.order_by("title", "favorite_book__title")
)
self.assertSequenceEqual(
qs,
[
{"title": self.book1.title, "favorite_book__pk": self.book2.pk},
{"title": self.book1.title, "favorite_book__pk": self.book3.pk},
{"title": self.book4.title, "favorite_book__pk": self.book2.pk},
{"title": self.book4.title, "favorite_book__pk": self.book3.pk},
{"title": self.book2.title, "favorite_book__pk": None},
{"title": self.book3.title, "favorite_book__pk": None},
],
)
def test_nested_chained_relations(self):
qs = (
Author.objects.annotate(
my_books=FilteredRelation(
"book",
condition=Q(book__title__icontains="book by"),
),
preferred_by_authors=FilteredRelation(
"my_books__preferred_by_authors",
condition=Q(my_books__preferred_by_authors__name="Alice"),
),
)
.annotate(
author=F("name"),
book_title=F("my_books__title"),
preferred_by_author_pk=F("preferred_by_authors"),
)
.order_by("author", "book_title", "preferred_by_author_pk")
)
self.assertQuerySetEqual(
qs,
[
("Alice", "The book by Alice", None),
("Jane", "The book by Jane A", self.author1.pk),
("Jane", "The book by Jane B", self.author1.pk),
],
lambda x: (x.author, x.book_title, x.preferred_by_author_pk),
)
def test_deep_nested_foreign_key(self):
qs = (
Book.objects.annotate(
author_favorite_book_editor=FilteredRelation(
"author__favorite_books__editor",
condition=Q(author__favorite_books__title__icontains="Jane A"),
),
)
.filter(
author_favorite_book_editor__isnull=False,
)
.select_related(
"author_favorite_book_editor",
)
.order_by("pk", "author_favorite_book_editor__pk")
)
with self.assertNumQueries(1):
self.assertQuerySetEqual(
qs,
[
(self.book1, self.editor_b),
(self.book4, self.editor_b),
],
lambda x: (x, x.author_favorite_book_editor),
)
def test_relation_name_lookup(self):
msg = (
"FilteredRelation's relation_name cannot contain lookups (got "
"'book__title__icontains')."
)
with self.assertRaisesMessage(ValueError, msg):
Author.objects.annotate(
book_title=FilteredRelation(
"book__title__icontains",
condition=Q(book__title="Poem by Alice"),
),
)
def test_condition_outside_relation_name(self):
msg = (
"FilteredRelation's condition doesn't support relations outside "
"the 'book__editor' (got 'book__author__name__icontains')."
)
with self.assertRaisesMessage(ValueError, msg):
Author.objects.annotate(
book_editor=FilteredRelation(
"book__editor",
condition=Q(book__author__name__icontains="book"),
),
)
def test_condition_deeper_relation_name(self):
msg = (
"FilteredRelation's condition doesn't support nested relations "
"deeper than the relation_name (got "
"'book__editor__name__icontains' for 'book')."
)
with self.assertRaisesMessage(ValueError, msg):
Author.objects.annotate(
book_editor=FilteredRelation(
"book",
condition=Q(book__editor__name__icontains="b"),
),
)
def test_with_empty_relation_name_error(self):
with self.assertRaisesMessage(ValueError, "relation_name cannot be empty."):
FilteredRelation("", condition=Q(blank=""))
def test_with_condition_as_expression_error(self):
msg = "condition argument must be a Q() instance."
expression = Case(
When(book__title__iexact="poem by alice", then=True),
default=False,
)
with self.assertRaisesMessage(ValueError, msg):
FilteredRelation("book", condition=expression)
def test_with_prefetch_related(self):
msg = "prefetch_related() is not supported with FilteredRelation."
qs = Author.objects.annotate(
book_title_contains_b=FilteredRelation(
"book", condition=Q(book__title__icontains="b")
),
).filter(
book_title_contains_b__isnull=False,
)
with self.assertRaisesMessage(ValueError, msg):
qs.prefetch_related("book_title_contains_b")
with self.assertRaisesMessage(ValueError, msg):
qs.prefetch_related("book_title_contains_b__editor")
def test_with_generic_foreign_key(self):
self.assertSequenceEqual(
Book.objects.annotate(
generic_authored_book=FilteredRelation(
"generic_author", condition=Q(generic_author__isnull=False)
),
).filter(generic_authored_book__isnull=False),
[self.book1],
)
def test_eq(self):
self.assertEqual(
FilteredRelation("book", condition=Q(book__title="b")), mock.ANY
)
class FilteredRelationAggregationTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.author1 = Author.objects.create(name="Alice")
cls.editor_a = Editor.objects.create(name="a")
cls.book1 = Book.objects.create(
title="Poem by Alice",
editor=cls.editor_a,
author=cls.author1,
)
cls.borrower1 = Borrower.objects.create(name="Jenny")
cls.borrower2 = Borrower.objects.create(name="Kevin")
# borrower 1 reserves, rents, and returns book1.
Reservation.objects.create(
borrower=cls.borrower1,
book=cls.book1,
state=Reservation.STOPPED,
)
RentalSession.objects.create(
borrower=cls.borrower1,
book=cls.book1,
state=RentalSession.STOPPED,
)
# borrower2 reserves, rents, and returns book1.
Reservation.objects.create(
borrower=cls.borrower2,
book=cls.book1,
state=Reservation.STOPPED,
)
RentalSession.objects.create(
borrower=cls.borrower2,
book=cls.book1,
state=RentalSession.STOPPED,
)
def test_aggregate(self):
"""
filtered_relation() not only improves performance but also creates
correct results when aggregating with multiple LEFT JOINs.
Books can be reserved then rented by a borrower. Each reservation and
rental session are recorded with Reservation and RentalSession models.
Every time a reservation or a rental session is over, their state is
changed to 'stopped'.
Goal: Count number of books that are either currently reserved or
rented by borrower1 or available.
"""
qs = (
Book.objects.annotate(
is_reserved_or_rented_by=Case(
When(
reservation__state=Reservation.NEW,
then=F("reservation__borrower__pk"),
),
When(
rental_session__state=RentalSession.NEW,
then=F("rental_session__borrower__pk"),
),
default=None,
)
)
.filter(
Q(is_reserved_or_rented_by=self.borrower1.pk) | Q(state=Book.AVAILABLE)
)
.distinct()
)
self.assertEqual(qs.count(), 1)
# If count is equal to 1, the same aggregation should return in the
# same result but it returns 4.
self.assertSequenceEqual(
qs.annotate(total=Count("pk")).values("total"), [{"total": 4}]
)
# With FilteredRelation, the result is as expected (1).
qs = (
Book.objects.annotate(
active_reservations=FilteredRelation(
"reservation",
condition=Q(
reservation__state=Reservation.NEW,
reservation__borrower=self.borrower1,
),
),
)
.annotate(
active_rental_sessions=FilteredRelation(
"rental_session",
condition=Q(
rental_session__state=RentalSession.NEW,
rental_session__borrower=self.borrower1,
),
),
)
.filter(
(
Q(active_reservations__isnull=False)
| Q(active_rental_sessions__isnull=False)
)
| Q(state=Book.AVAILABLE)
)
.distinct()
)
self.assertEqual(qs.count(), 1)
self.assertSequenceEqual(
qs.annotate(total=Count("pk")).values("total"), [{"total": 1}]
)
class FilteredRelationAnalyticalAggregationTests(TestCase):
@classmethod
def setUpTestData(cls):
author = Author.objects.create(name="Author")
editor = Editor.objects.create(name="Editor")
cls.book1 = Book.objects.create(
title="Poem by Alice",
editor=editor,
author=author,
)
cls.book2 = Book.objects.create(
title="The book by Jane A",
editor=editor,
author=author,
)
cls.book3 = Book.objects.create(
title="The book by Jane B",
editor=editor,
author=author,
)
cls.seller1 = Seller.objects.create(name="Seller 1")
cls.seller2 = Seller.objects.create(name="Seller 2")
cls.usd = Currency.objects.create(currency="USD")
cls.eur = Currency.objects.create(currency="EUR")
cls.sales_date1 = date(2020, 7, 6)
cls.sales_date2 = date(2020, 7, 7)
ExchangeRate.objects.bulk_create(
[
ExchangeRate(
rate_date=cls.sales_date1,
from_currency=cls.usd,
to_currency=cls.eur,
rate=0.40,
),
ExchangeRate(
rate_date=cls.sales_date1,
from_currency=cls.eur,
to_currency=cls.usd,
rate=1.60,
),
ExchangeRate(
rate_date=cls.sales_date2,
from_currency=cls.usd,
to_currency=cls.eur,
rate=0.50,
),
ExchangeRate(
rate_date=cls.sales_date2,
from_currency=cls.eur,
to_currency=cls.usd,
rate=1.50,
),
ExchangeRate(
rate_date=cls.sales_date2,
from_currency=cls.usd,
to_currency=cls.usd,
rate=1.00,
),
]
)
BookDailySales.objects.bulk_create(
[
BookDailySales(
book=cls.book1,
sale_date=cls.sales_date1,
currency=cls.usd,
sales=100.00,
seller=cls.seller1,
),
BookDailySales(
book=cls.book2,
sale_date=cls.sales_date1,
currency=cls.eur,
sales=200.00,
seller=cls.seller1,
),
BookDailySales(
book=cls.book1,
sale_date=cls.sales_date2,
currency=cls.usd,
sales=50.00,
seller=cls.seller2,
),
BookDailySales(
book=cls.book2,
sale_date=cls.sales_date2,
currency=cls.eur,
sales=100.00,
seller=cls.seller2,
),
]
)
def test_aggregate(self):
tests = [
Q(daily_sales__sale_date__gte=self.sales_date2),
~Q(daily_sales__seller=self.seller1),
]
for condition in tests:
with self.subTest(condition=condition):
qs = (
Book.objects.annotate(
recent_sales=FilteredRelation(
"daily_sales", condition=condition
),
recent_sales_rates=FilteredRelation(
"recent_sales__currency__rates_from",
condition=Q(
recent_sales__currency__rates_from__rate_date=F(
"recent_sales__sale_date"
),
recent_sales__currency__rates_from__to_currency=(
self.usd
),
),
),
)
.annotate(
sales_sum=Sum(
F("recent_sales__sales") * F("recent_sales_rates__rate"),
output_field=DecimalField(),
),
)
.values("title", "sales_sum")
.order_by(
F("sales_sum").desc(nulls_last=True),
)
)
self.assertSequenceEqual(
qs,
[
{"title": self.book2.title, "sales_sum": Decimal(150.00)},
{"title": self.book1.title, "sales_sum": Decimal(50.00)},
{"title": self.book3.title, "sales_sum": None},
],
)
|
615f7564843c7b7ee1c5a5ff53c4ee28a173d5337bf89a7fbed054b93c8ead42 | from django import forms
from django.contrib import admin
from django.contrib.admin.widgets import AutocompleteSelect
from django.forms import ModelChoiceField
from django.test import TestCase, override_settings
from django.utils import translation
from .models import Album, Band, ReleaseEvent, VideoStream
class AlbumForm(forms.ModelForm):
class Meta:
model = Album
fields = ["band", "featuring"]
widgets = {
"band": AutocompleteSelect(
Album._meta.get_field("band"),
admin.site,
attrs={"class": "my-class"},
),
"featuring": AutocompleteSelect(
Album._meta.get_field("featuring"),
admin.site,
),
}
class NotRequiredBandForm(forms.Form):
band = ModelChoiceField(
queryset=Album.objects.all(),
widget=AutocompleteSelect(
Album._meta.get_field("band").remote_field, admin.site
),
required=False,
)
class RequiredBandForm(forms.Form):
band = ModelChoiceField(
queryset=Album.objects.all(),
widget=AutocompleteSelect(
Album._meta.get_field("band").remote_field, admin.site
),
required=True,
)
class VideoStreamForm(forms.ModelForm):
class Meta:
model = VideoStream
fields = ["release_event"]
widgets = {
"release_event": AutocompleteSelect(
VideoStream._meta.get_field("release_event"),
admin.site,
),
}
@override_settings(ROOT_URLCONF="admin_widgets.urls")
class AutocompleteMixinTests(TestCase):
empty_option = '<option value=""></option>'
maxDiff = 1000
def test_build_attrs(self):
form = AlbumForm()
attrs = form["band"].field.widget.get_context(
name="my_field", value=None, attrs={}
)["widget"]["attrs"]
self.assertEqual(
attrs,
{
"class": "my-class admin-autocomplete",
"data-ajax--cache": "true",
"data-ajax--delay": 250,
"data-ajax--type": "GET",
"data-ajax--url": "/autocomplete/",
"data-theme": "admin-autocomplete",
"data-allow-clear": "false",
"data-app-label": "admin_widgets",
"data-field-name": "band",
"data-model-name": "album",
"data-placeholder": "",
"lang": "en",
},
)
def test_build_attrs_no_custom_class(self):
form = AlbumForm()
attrs = form["featuring"].field.widget.get_context(
name="name", value=None, attrs={}
)["widget"]["attrs"]
self.assertEqual(attrs["class"], "admin-autocomplete")
def test_build_attrs_not_required_field(self):
form = NotRequiredBandForm()
attrs = form["band"].field.widget.build_attrs({})
self.assertJSONEqual(attrs["data-allow-clear"], True)
def test_build_attrs_required_field(self):
form = RequiredBandForm()
attrs = form["band"].field.widget.build_attrs({})
self.assertJSONEqual(attrs["data-allow-clear"], False)
def test_get_url(self):
rel = Album._meta.get_field("band")
w = AutocompleteSelect(rel, admin.site)
url = w.get_url()
self.assertEqual(url, "/autocomplete/")
def test_render_options(self):
beatles = Band.objects.create(name="The Beatles", style="rock")
who = Band.objects.create(name="The Who", style="rock")
# With 'band', a ForeignKey.
form = AlbumForm(initial={"band": beatles.uuid})
output = form.as_table()
selected_option = (
'<option value="%s" selected>The Beatles</option>' % beatles.uuid
)
option = '<option value="%s">The Who</option>' % who.uuid
self.assertIn(selected_option, output)
self.assertNotIn(option, output)
# With 'featuring', a ManyToManyField.
form = AlbumForm(initial={"featuring": [beatles.pk, who.pk]})
output = form.as_table()
selected_option = (
'<option value="%s" selected>The Beatles</option>' % beatles.pk
)
option = '<option value="%s" selected>The Who</option>' % who.pk
self.assertIn(selected_option, output)
self.assertIn(option, output)
def test_render_options_required_field(self):
"""Empty option is present if the field isn't required."""
form = NotRequiredBandForm()
output = form.as_table()
self.assertIn(self.empty_option, output)
def test_render_options_not_required_field(self):
"""Empty option isn't present if the field isn't required."""
form = RequiredBandForm()
output = form.as_table()
self.assertNotIn(self.empty_option, output)
def test_render_options_fk_as_pk(self):
beatles = Band.objects.create(name="The Beatles", style="rock")
rubber_soul = Album.objects.create(name="Rubber Soul", band=beatles)
release_event = ReleaseEvent.objects.create(
name="Test Target", album=rubber_soul
)
form = VideoStreamForm(initial={"release_event": release_event.pk})
output = form.as_table()
selected_option = (
'<option value="%s" selected>Test Target</option>' % release_event.pk
)
self.assertIn(selected_option, output)
def test_media(self):
rel = Album._meta.get_field("band").remote_field
base_files = (
"admin/js/vendor/jquery/jquery.min.js",
"admin/js/vendor/select2/select2.full.min.js",
# Language file is inserted here.
"admin/js/jquery.init.js",
"admin/js/autocomplete.js",
)
languages = (
("de", "de"),
# Subsequent language codes are used when the language code is not
# supported.
("de-at", "de"),
("de-ch-1901", "de"),
("en-latn-us", "en"),
("nl-nl-x-informal", "nl"),
("zh-hans-HK", "zh-CN"),
# Language with code 00 does not exist.
("00", None),
# Language files are case sensitive.
("sr-cyrl", "sr-Cyrl"),
("zh-hans", "zh-CN"),
("zh-hant", "zh-TW"),
(None, None),
)
for lang, select_lang in languages:
with self.subTest(lang=lang):
if select_lang:
expected_files = (
base_files[:2]
+ (("admin/js/vendor/select2/i18n/%s.js" % select_lang),)
+ base_files[2:]
)
else:
expected_files = base_files
with translation.override(lang):
self.assertEqual(
AutocompleteSelect(rel, admin.site).media._js,
list(expected_files),
)
|
7a80910f73056cfe30d80c179f4825fa14c914ff91afbdbb9312029e109b90fd | # Unittests for fixtures.
import json
import os
import re
from io import StringIO
from pathlib import Path
from django.core import management, serializers
from django.core.exceptions import ImproperlyConfigured
from django.core.serializers.base import DeserializationError
from django.db import IntegrityError, transaction
from django.db.models import signals
from django.test import (
TestCase,
TransactionTestCase,
override_settings,
skipIfDBFeature,
skipUnlessDBFeature,
)
from .models import (
Absolute,
Animal,
Article,
Book,
Child,
Circle1,
Circle2,
Circle3,
ExternalDependency,
M2MCircular1ThroughAB,
M2MCircular1ThroughBC,
M2MCircular1ThroughCA,
M2MCircular2ThroughAB,
M2MComplexA,
M2MComplexB,
M2MComplexCircular1A,
M2MComplexCircular1B,
M2MComplexCircular1C,
M2MComplexCircular2A,
M2MComplexCircular2B,
M2MSimpleA,
M2MSimpleB,
M2MSimpleCircularA,
M2MSimpleCircularB,
M2MThroughAB,
NaturalKeyWithFKDependency,
NKChild,
Parent,
Person,
RefToNKChild,
Store,
Stuff,
Thingy,
Widget,
)
_cur_dir = os.path.dirname(os.path.abspath(__file__))
class TestFixtures(TestCase):
def animal_pre_save_check(self, signal, sender, instance, **kwargs):
self.pre_save_checks.append(
(
"Count = %s (%s)" % (instance.count, type(instance.count)),
"Weight = %s (%s)" % (instance.weight, type(instance.weight)),
)
)
def test_duplicate_pk(self):
"""
This is a regression test for ticket #3790.
"""
# Load a fixture that uses PK=1
management.call_command(
"loaddata",
"sequence",
verbosity=0,
)
# Create a new animal. Without a sequence reset, this new object
# will take a PK of 1 (on Postgres), and the save will fail.
animal = Animal(
name="Platypus",
latin_name="Ornithorhynchus anatinus",
count=2,
weight=2.2,
)
animal.save()
self.assertGreater(animal.id, 1)
def test_loaddata_not_found_fields_not_ignore(self):
"""
Test for ticket #9279 -- Error is raised for entries in
the serialized data for fields that have been removed
from the database when not ignored.
"""
with self.assertRaises(DeserializationError):
management.call_command(
"loaddata",
"sequence_extra",
verbosity=0,
)
def test_loaddata_not_found_fields_ignore(self):
"""
Test for ticket #9279 -- Ignores entries in
the serialized data for fields that have been removed
from the database.
"""
management.call_command(
"loaddata",
"sequence_extra",
ignore=True,
verbosity=0,
)
self.assertEqual(Animal.specimens.all()[0].name, "Lion")
def test_loaddata_not_found_fields_ignore_xml(self):
"""
Test for ticket #19998 -- Ignore entries in the XML serialized data
for fields that have been removed from the model definition.
"""
management.call_command(
"loaddata",
"sequence_extra_xml",
ignore=True,
verbosity=0,
)
self.assertEqual(Animal.specimens.all()[0].name, "Wolf")
@skipIfDBFeature("interprets_empty_strings_as_nulls")
def test_pretty_print_xml(self):
"""
Regression test for ticket #4558 -- pretty printing of XML fixtures
doesn't affect parsing of None values.
"""
# Load a pretty-printed XML fixture with Nulls.
management.call_command(
"loaddata",
"pretty.xml",
verbosity=0,
)
self.assertIsNone(Stuff.objects.all()[0].name)
self.assertIsNone(Stuff.objects.all()[0].owner)
@skipUnlessDBFeature("interprets_empty_strings_as_nulls")
def test_pretty_print_xml_empty_strings(self):
"""
Regression test for ticket #4558 -- pretty printing of XML fixtures
doesn't affect parsing of None values.
"""
# Load a pretty-printed XML fixture with Nulls.
management.call_command(
"loaddata",
"pretty.xml",
verbosity=0,
)
self.assertEqual(Stuff.objects.all()[0].name, "")
self.assertIsNone(Stuff.objects.all()[0].owner)
def test_absolute_path(self):
"""
Regression test for ticket #6436 --
os.path.join will throw away the initial parts of a path if it
encounters an absolute path.
This means that if a fixture is specified as an absolute path,
we need to make sure we don't discover the absolute path in every
fixture directory.
"""
load_absolute_path = os.path.join(
os.path.dirname(__file__), "fixtures", "absolute.json"
)
management.call_command(
"loaddata",
load_absolute_path,
verbosity=0,
)
self.assertEqual(Absolute.objects.count(), 1)
def test_relative_path(self, path=["fixtures", "absolute.json"]):
relative_path = os.path.join(*path)
cwd = os.getcwd()
try:
os.chdir(_cur_dir)
management.call_command(
"loaddata",
relative_path,
verbosity=0,
)
finally:
os.chdir(cwd)
self.assertEqual(Absolute.objects.count(), 1)
@override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, "fixtures_1")])
def test_relative_path_in_fixture_dirs(self):
self.test_relative_path(path=["inner", "absolute.json"])
def test_path_containing_dots(self):
management.call_command(
"loaddata",
"path.containing.dots.json",
verbosity=0,
)
self.assertEqual(Absolute.objects.count(), 1)
def test_unknown_format(self):
"""
Test for ticket #4371 -- Loading data of an unknown format should fail
Validate that error conditions are caught correctly
"""
msg = (
"Problem installing fixture 'bad_fix.ture1': unkn is not a known "
"serialization format."
)
with self.assertRaisesMessage(management.CommandError, msg):
management.call_command(
"loaddata",
"bad_fix.ture1.unkn",
verbosity=0,
)
@override_settings(SERIALIZATION_MODULES={"unkn": "unexistent.path"})
def test_unimportable_serializer(self):
"""
Failing serializer import raises the proper error
"""
with self.assertRaisesMessage(ImportError, "No module named 'unexistent'"):
management.call_command(
"loaddata",
"bad_fix.ture1.unkn",
verbosity=0,
)
def test_invalid_data(self):
"""
Test for ticket #4371 -- Loading a fixture file with invalid data
using explicit filename.
Test for ticket #18213 -- warning conditions are caught correctly
"""
msg = "No fixture data found for 'bad_fixture2'. (File format may be invalid.)"
with self.assertWarnsMessage(RuntimeWarning, msg):
management.call_command(
"loaddata",
"bad_fixture2.xml",
verbosity=0,
)
def test_invalid_data_no_ext(self):
"""
Test for ticket #4371 -- Loading a fixture file with invalid data
without file extension.
Test for ticket #18213 -- warning conditions are caught correctly
"""
msg = "No fixture data found for 'bad_fixture2'. (File format may be invalid.)"
with self.assertWarnsMessage(RuntimeWarning, msg):
management.call_command(
"loaddata",
"bad_fixture2",
verbosity=0,
)
def test_empty(self):
"""
Test for ticket #18213 -- Loading a fixture file with no data output a warning.
Previously empty fixture raises an error exception, see ticket #4371.
"""
msg = "No fixture data found for 'empty'. (File format may be invalid.)"
with self.assertWarnsMessage(RuntimeWarning, msg):
management.call_command(
"loaddata",
"empty",
verbosity=0,
)
def test_error_message(self):
"""
Regression for #9011 - error message is correct.
Change from error to warning for ticket #18213.
"""
msg = "No fixture data found for 'bad_fixture2'. (File format may be invalid.)"
with self.assertWarnsMessage(RuntimeWarning, msg):
management.call_command(
"loaddata",
"bad_fixture2",
"animal",
verbosity=0,
)
def test_pg_sequence_resetting_checks(self):
"""
Test for ticket #7565 -- PostgreSQL sequence resetting checks shouldn't
ascend to parent models when inheritance is used
(since they are treated individually).
"""
management.call_command(
"loaddata",
"model-inheritance.json",
verbosity=0,
)
self.assertEqual(Parent.objects.all()[0].id, 1)
self.assertEqual(Child.objects.all()[0].id, 1)
def test_close_connection_after_loaddata(self):
"""
Test for ticket #7572 -- MySQL has a problem if the same connection is
used to create tables, load data, and then query over that data.
To compensate, we close the connection after running loaddata.
This ensures that a new connection is opened when test queries are
issued.
"""
management.call_command(
"loaddata",
"big-fixture.json",
verbosity=0,
)
articles = Article.objects.exclude(id=9)
self.assertEqual(
list(articles.values_list("id", flat=True)), [1, 2, 3, 4, 5, 6, 7, 8]
)
# Just for good measure, run the same query again.
# Under the influence of ticket #7572, this will
# give a different result to the previous call.
self.assertEqual(
list(articles.values_list("id", flat=True)), [1, 2, 3, 4, 5, 6, 7, 8]
)
def test_field_value_coerce(self):
"""
Test for tickets #8298, #9942 - Field values should be coerced into the
correct type by the deserializer, not as part of the database write.
"""
self.pre_save_checks = []
signals.pre_save.connect(self.animal_pre_save_check)
try:
management.call_command(
"loaddata",
"animal.xml",
verbosity=0,
)
self.assertEqual(
self.pre_save_checks,
[("Count = 42 (<class 'int'>)", "Weight = 1.2 (<class 'float'>)")],
)
finally:
signals.pre_save.disconnect(self.animal_pre_save_check)
def test_dumpdata_uses_default_manager(self):
"""
Regression for #11286
Dumpdata honors the default manager. Dump the current contents of
the database as a JSON fixture
"""
management.call_command(
"loaddata",
"animal.xml",
verbosity=0,
)
management.call_command(
"loaddata",
"sequence.json",
verbosity=0,
)
animal = Animal(
name="Platypus",
latin_name="Ornithorhynchus anatinus",
count=2,
weight=2.2,
)
animal.save()
out = StringIO()
management.call_command(
"dumpdata",
"fixtures_regress.animal",
format="json",
stdout=out,
)
# Output order isn't guaranteed, so check for parts
data = out.getvalue()
# Get rid of artifacts like '000000002' to eliminate the differences
# between different Python versions.
data = re.sub("0{6,}[0-9]", "", data)
animals_data = sorted(
[
{
"pk": 1,
"model": "fixtures_regress.animal",
"fields": {
"count": 3,
"weight": 1.2,
"name": "Lion",
"latin_name": "Panthera leo",
},
},
{
"pk": 10,
"model": "fixtures_regress.animal",
"fields": {
"count": 42,
"weight": 1.2,
"name": "Emu",
"latin_name": "Dromaius novaehollandiae",
},
},
{
"pk": animal.pk,
"model": "fixtures_regress.animal",
"fields": {
"count": 2,
"weight": 2.2,
"name": "Platypus",
"latin_name": "Ornithorhynchus anatinus",
},
},
],
key=lambda x: x["pk"],
)
data = sorted(json.loads(data), key=lambda x: x["pk"])
self.maxDiff = 1024
self.assertEqual(data, animals_data)
def test_proxy_model_included(self):
"""
Regression for #11428 - Proxy models aren't included when you dumpdata
"""
out = StringIO()
# Create an instance of the concrete class
widget = Widget.objects.create(name="grommet")
management.call_command(
"dumpdata",
"fixtures_regress.widget",
"fixtures_regress.widgetproxy",
format="json",
stdout=out,
)
self.assertJSONEqual(
out.getvalue(),
'[{"pk": %d, "model": "fixtures_regress.widget", '
'"fields": {"name": "grommet"}}]' % widget.pk,
)
@skipUnlessDBFeature("supports_forward_references")
def test_loaddata_works_when_fixture_has_forward_refs(self):
"""
Forward references cause fixtures not to load in MySQL (InnoDB).
"""
management.call_command(
"loaddata",
"forward_ref.json",
verbosity=0,
)
self.assertEqual(Book.objects.all()[0].id, 1)
self.assertEqual(Person.objects.all()[0].id, 4)
def test_loaddata_raises_error_when_fixture_has_invalid_foreign_key(self):
"""
Data with nonexistent child key references raises error.
"""
with self.assertRaisesMessage(IntegrityError, "Problem installing fixture"):
management.call_command(
"loaddata",
"forward_ref_bad_data.json",
verbosity=0,
)
@skipUnlessDBFeature("supports_forward_references")
@override_settings(
FIXTURE_DIRS=[
os.path.join(_cur_dir, "fixtures_1"),
os.path.join(_cur_dir, "fixtures_2"),
]
)
def test_loaddata_forward_refs_split_fixtures(self):
"""
Regression for #17530 - should be able to cope with forward references
when the fixtures are not in the same files or directories.
"""
management.call_command(
"loaddata",
"forward_ref_1.json",
"forward_ref_2.json",
verbosity=0,
)
self.assertEqual(Book.objects.all()[0].id, 1)
self.assertEqual(Person.objects.all()[0].id, 4)
def test_loaddata_no_fixture_specified(self):
"""
Error is quickly reported when no fixtures is provided in the command
line.
"""
msg = (
"No database fixture specified. Please provide the path of at least one "
"fixture in the command line."
)
with self.assertRaisesMessage(management.CommandError, msg):
management.call_command(
"loaddata",
verbosity=0,
)
def test_ticket_20820(self):
"""
Regression for ticket #20820 -- loaddata on a model that inherits
from a model with a M2M shouldn't blow up.
"""
management.call_command(
"loaddata",
"special-article.json",
verbosity=0,
)
def test_ticket_22421(self):
"""
Regression for ticket #22421 -- loaddata on a model that inherits from
a grand-parent model with a M2M but via an abstract parent shouldn't
blow up.
"""
management.call_command(
"loaddata",
"feature.json",
verbosity=0,
)
def test_loaddata_with_m2m_to_self(self):
"""
Regression test for ticket #17946.
"""
management.call_command(
"loaddata",
"m2mtoself.json",
verbosity=0,
)
@override_settings(
FIXTURE_DIRS=[
os.path.join(_cur_dir, "fixtures_1"),
os.path.join(_cur_dir, "fixtures_1"),
]
)
def test_fixture_dirs_with_duplicates(self):
"""
settings.FIXTURE_DIRS cannot contain duplicates in order to avoid
repeated fixture loading.
"""
with self.assertRaisesMessage(
ImproperlyConfigured, "settings.FIXTURE_DIRS contains duplicates."
):
management.call_command("loaddata", "absolute.json", verbosity=0)
@override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, "fixtures")])
def test_fixture_dirs_with_default_fixture_path(self):
"""
settings.FIXTURE_DIRS cannot contain a default fixtures directory
for application (app/fixtures) in order to avoid repeated fixture loading.
"""
msg = (
"'%s' is a default fixture directory for the '%s' app "
"and cannot be listed in settings.FIXTURE_DIRS."
% (os.path.join(_cur_dir, "fixtures"), "fixtures_regress")
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
management.call_command("loaddata", "absolute.json", verbosity=0)
@override_settings(FIXTURE_DIRS=[Path(_cur_dir) / "fixtures"])
def test_fixture_dirs_with_default_fixture_path_as_pathlib(self):
"""
settings.FIXTURE_DIRS cannot contain a default fixtures directory
for application (app/fixtures) in order to avoid repeated fixture loading.
"""
msg = (
"'%s' is a default fixture directory for the '%s' app "
"and cannot be listed in settings.FIXTURE_DIRS."
% (os.path.join(_cur_dir, "fixtures"), "fixtures_regress")
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
management.call_command("loaddata", "absolute.json", verbosity=0)
@override_settings(
FIXTURE_DIRS=[
os.path.join(_cur_dir, "fixtures_1"),
os.path.join(_cur_dir, "fixtures_2"),
]
)
def test_loaddata_with_valid_fixture_dirs(self):
management.call_command(
"loaddata",
"absolute.json",
verbosity=0,
)
@override_settings(FIXTURE_DIRS=[Path(_cur_dir) / "fixtures_1"])
def test_fixtures_dir_pathlib(self):
management.call_command("loaddata", "inner/absolute.json", verbosity=0)
self.assertQuerySetEqual(Absolute.objects.all(), [1], transform=lambda o: o.pk)
class NaturalKeyFixtureTests(TestCase):
def test_nk_deserialize(self):
"""
Test for ticket #13030 - Python based parser version
natural keys deserialize with fk to inheriting model
"""
management.call_command(
"loaddata",
"model-inheritance.json",
verbosity=0,
)
management.call_command(
"loaddata",
"nk-inheritance.json",
verbosity=0,
)
self.assertEqual(NKChild.objects.get(pk=1).data, "apple")
self.assertEqual(RefToNKChild.objects.get(pk=1).nk_fk.data, "apple")
def test_nk_deserialize_xml(self):
"""
Test for ticket #13030 - XML version
natural keys deserialize with fk to inheriting model
"""
management.call_command(
"loaddata",
"model-inheritance.json",
verbosity=0,
)
management.call_command(
"loaddata",
"nk-inheritance.json",
verbosity=0,
)
management.call_command(
"loaddata",
"nk-inheritance2.xml",
verbosity=0,
)
self.assertEqual(NKChild.objects.get(pk=2).data, "banana")
self.assertEqual(RefToNKChild.objects.get(pk=2).nk_fk.data, "apple")
def test_nk_on_serialize(self):
"""
Natural key requirements are taken into account when serializing models.
"""
management.call_command(
"loaddata",
"forward_ref_lookup.json",
verbosity=0,
)
out = StringIO()
management.call_command(
"dumpdata",
"fixtures_regress.book",
"fixtures_regress.person",
"fixtures_regress.store",
verbosity=0,
format="json",
use_natural_foreign_keys=True,
use_natural_primary_keys=True,
stdout=out,
)
self.assertJSONEqual(
out.getvalue(),
"""
[{"fields": {"main": null, "name": "Amazon"},
"model": "fixtures_regress.store"},
{"fields": {"main": null, "name": "Borders"},
"model": "fixtures_regress.store"},
{"fields": {"name": "Neal Stephenson"}, "model": "fixtures_regress.person"},
{"pk": 1, "model": "fixtures_regress.book",
"fields": {"stores": [["Amazon"], ["Borders"]],
"name": "Cryptonomicon", "author": ["Neal Stephenson"]}}]
""",
)
def test_dependency_sorting(self):
"""
It doesn't matter what order you mention the models, Store *must* be
serialized before then Person, and both must be serialized before Book.
"""
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [Book, Person, Store])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_2(self):
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [Book, Store, Person])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_3(self):
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [Store, Book, Person])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_4(self):
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [Store, Person, Book])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_5(self):
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [Person, Book, Store])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_6(self):
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [Person, Store, Book])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_dangling(self):
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [Person, Circle1, Store, Book])]
)
self.assertEqual(sorted_deps, [Circle1, Store, Person, Book])
def test_dependency_sorting_tight_circular(self):
with self.assertRaisesMessage(
RuntimeError,
"Can't resolve dependencies for fixtures_regress.Circle1, "
"fixtures_regress.Circle2 in serialized app list.",
):
serializers.sort_dependencies(
[("fixtures_regress", [Person, Circle2, Circle1, Store, Book])]
)
def test_dependency_sorting_tight_circular_2(self):
with self.assertRaisesMessage(
RuntimeError,
"Can't resolve dependencies for fixtures_regress.Circle1, "
"fixtures_regress.Circle2 in serialized app list.",
):
serializers.sort_dependencies(
[("fixtures_regress", [Circle1, Book, Circle2])]
)
def test_dependency_self_referential(self):
with self.assertRaisesMessage(
RuntimeError,
"Can't resolve dependencies for fixtures_regress.Circle3 in "
"serialized app list.",
):
serializers.sort_dependencies([("fixtures_regress", [Book, Circle3])])
def test_dependency_sorting_long(self):
with self.assertRaisesMessage(
RuntimeError,
"Can't resolve dependencies for fixtures_regress.Circle1, "
"fixtures_regress.Circle2, fixtures_regress.Circle3 in serialized "
"app list.",
):
serializers.sort_dependencies(
[("fixtures_regress", [Person, Circle2, Circle1, Circle3, Store, Book])]
)
def test_dependency_sorting_normal(self):
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [Person, ExternalDependency, Book])]
)
self.assertEqual(sorted_deps, [Person, Book, ExternalDependency])
def test_normal_pk(self):
"""
Normal primary keys work on a model with natural key capabilities.
"""
management.call_command(
"loaddata",
"non_natural_1.json",
verbosity=0,
)
management.call_command(
"loaddata",
"forward_ref_lookup.json",
verbosity=0,
)
management.call_command(
"loaddata",
"non_natural_2.xml",
verbosity=0,
)
books = Book.objects.all()
self.assertQuerySetEqual(
books,
[
"<Book: Cryptonomicon by Neal Stephenson (available at Amazon, "
"Borders)>",
"<Book: Ender's Game by Orson Scott Card (available at Collins "
"Bookstore)>",
"<Book: Permutation City by Greg Egan (available at Angus and "
"Robertson)>",
],
transform=repr,
)
class NaturalKeyFixtureOnOtherDatabaseTests(TestCase):
databases = {"other"}
def test_natural_key_dependencies(self):
"""
Natural keys with foreing keys in dependencies works in a multiple
database setup.
"""
management.call_command(
"loaddata",
"nk_with_foreign_key.json",
database="other",
verbosity=0,
)
obj = NaturalKeyWithFKDependency.objects.using("other").get()
self.assertEqual(obj.name, "The Lord of the Rings")
self.assertEqual(obj.author.name, "J.R.R. Tolkien")
class M2MNaturalKeyFixtureTests(TestCase):
"""Tests for ticket #14426."""
def test_dependency_sorting_m2m_simple(self):
"""
M2M relations without explicit through models SHOULD count as dependencies
Regression test for bugs that could be caused by flawed fixes to
#14226, namely if M2M checks are removed from sort_dependencies
altogether.
"""
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [M2MSimpleA, M2MSimpleB])]
)
self.assertEqual(sorted_deps, [M2MSimpleB, M2MSimpleA])
def test_dependency_sorting_m2m_simple_circular(self):
"""
Resolving circular M2M relations without explicit through models should
fail loudly
"""
with self.assertRaisesMessage(
RuntimeError,
"Can't resolve dependencies for fixtures_regress.M2MSimpleCircularA, "
"fixtures_regress.M2MSimpleCircularB in serialized app list.",
):
serializers.sort_dependencies(
[("fixtures_regress", [M2MSimpleCircularA, M2MSimpleCircularB])]
)
def test_dependency_sorting_m2m_complex(self):
"""
M2M relations with explicit through models should NOT count as
dependencies. The through model itself will have dependencies, though.
"""
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [M2MComplexA, M2MComplexB, M2MThroughAB])]
)
# Order between M2MComplexA and M2MComplexB doesn't matter. The through
# model has dependencies to them though, so it should come last.
self.assertEqual(sorted_deps[-1], M2MThroughAB)
def test_dependency_sorting_m2m_complex_circular_1(self):
"""
Circular M2M relations with explicit through models should be serializable
"""
A, B, C, AtoB, BtoC, CtoA = (
M2MComplexCircular1A,
M2MComplexCircular1B,
M2MComplexCircular1C,
M2MCircular1ThroughAB,
M2MCircular1ThroughBC,
M2MCircular1ThroughCA,
)
sorted_deps = serializers.sort_dependencies(
[("fixtures_regress", [A, B, C, AtoB, BtoC, CtoA])]
)
# The dependency sorting should not result in an error, and the
# through model should have dependencies to the other models and as
# such come last in the list.
self.assertEqual(sorted_deps[:3], [A, B, C])
self.assertEqual(sorted_deps[3:], [AtoB, BtoC, CtoA])
def test_dependency_sorting_m2m_complex_circular_2(self):
"""
Circular M2M relations with explicit through models should be serializable
This test tests the circularity with explicit natural_key.dependencies
"""
sorted_deps = serializers.sort_dependencies(
[
(
"fixtures_regress",
[M2MComplexCircular2A, M2MComplexCircular2B, M2MCircular2ThroughAB],
)
]
)
self.assertEqual(sorted_deps[:2], [M2MComplexCircular2A, M2MComplexCircular2B])
self.assertEqual(sorted_deps[2:], [M2MCircular2ThroughAB])
def test_dump_and_load_m2m_simple(self):
"""
Test serializing and deserializing back models with simple M2M relations
"""
a = M2MSimpleA.objects.create(data="a")
b1 = M2MSimpleB.objects.create(data="b1")
b2 = M2MSimpleB.objects.create(data="b2")
a.b_set.add(b1)
a.b_set.add(b2)
out = StringIO()
management.call_command(
"dumpdata",
"fixtures_regress.M2MSimpleA",
"fixtures_regress.M2MSimpleB",
use_natural_foreign_keys=True,
stdout=out,
)
for model in [M2MSimpleA, M2MSimpleB]:
model.objects.all().delete()
objects = serializers.deserialize("json", out.getvalue())
for obj in objects:
obj.save()
new_a = M2MSimpleA.objects.get_by_natural_key("a")
self.assertCountEqual(new_a.b_set.all(), [b1, b2])
class TestTicket11101(TransactionTestCase):
available_apps = ["fixtures_regress"]
@skipUnlessDBFeature("supports_transactions")
def test_ticket_11101(self):
"""Fixtures can be rolled back (ticket #11101)."""
with transaction.atomic():
management.call_command(
"loaddata",
"thingy.json",
verbosity=0,
)
self.assertEqual(Thingy.objects.count(), 1)
transaction.set_rollback(True)
self.assertEqual(Thingy.objects.count(), 0)
class TestLoadFixtureFromOtherAppDirectory(TestCase):
"""
#23612 -- fixtures path should be normalized to allow referencing relative
paths on Windows.
"""
current_dir = os.path.abspath(os.path.dirname(__file__))
# relative_prefix is something like tests/fixtures_regress or
# fixtures_regress depending on how runtests.py is invoked.
# All path separators must be / in order to be a proper regression test on
# Windows, so replace as appropriate.
relative_prefix = os.path.relpath(current_dir, os.getcwd()).replace("\\", "/")
fixtures = [relative_prefix + "/fixtures/absolute.json"]
def test_fixtures_loaded(self):
count = Absolute.objects.count()
self.assertGreater(count, 0, "Fixtures not loaded properly.")
|
425416dcb9e704a41f877b8c3cf80bb9b047fb119623cc083bbd2a34dd287e3e | from django.core.exceptions import FieldError
from django.test import TestCase
from .models import (
Entry,
Line,
Post,
RegressionModelSplit,
SelfRefer,
SelfReferChild,
SelfReferChildSibling,
Tag,
TagCollection,
Worksheet,
)
class M2MRegressionTests(TestCase):
def test_multiple_m2m(self):
# Multiple m2m references to model must be distinguished when
# accessing the relations through an instance attribute.
s1 = SelfRefer.objects.create(name="s1")
s2 = SelfRefer.objects.create(name="s2")
s3 = SelfRefer.objects.create(name="s3")
s1.references.add(s2)
s1.related.add(s3)
e1 = Entry.objects.create(name="e1")
t1 = Tag.objects.create(name="t1")
t2 = Tag.objects.create(name="t2")
e1.topics.add(t1)
e1.related.add(t2)
self.assertSequenceEqual(s1.references.all(), [s2])
self.assertSequenceEqual(s1.related.all(), [s3])
self.assertSequenceEqual(e1.topics.all(), [t1])
self.assertSequenceEqual(e1.related.all(), [t2])
def test_internal_related_name_not_in_error_msg(self):
# The secret internal related names for self-referential many-to-many
# fields shouldn't appear in the list when an error is made.
msg = (
"Choices are: id, name, references, related, selfreferchild, "
"selfreferchildsibling"
)
with self.assertRaisesMessage(FieldError, msg):
SelfRefer.objects.filter(porcupine="fred")
def test_m2m_inheritance_symmetry(self):
# Test to ensure that the relationship between two inherited models
# with a self-referential m2m field maintains symmetry
sr_child = SelfReferChild(name="Hanna")
sr_child.save()
sr_sibling = SelfReferChildSibling(name="Beth")
sr_sibling.save()
sr_child.related.add(sr_sibling)
self.assertSequenceEqual(sr_child.related.all(), [sr_sibling.selfrefer_ptr])
self.assertSequenceEqual(sr_sibling.related.all(), [sr_child.selfrefer_ptr])
def test_m2m_pk_field_type(self):
# Regression for #11311 - The primary key for models in a m2m relation
# doesn't have to be an AutoField
w = Worksheet(id="abc")
w.save()
w.delete()
def test_create_copy_with_m2m(self):
t1 = Tag.objects.create(name="t1")
Entry.objects.create(name="e1")
entry = Entry.objects.first()
entry.topics.set([t1])
old_topics = entry.topics.all()
entry.pk = None
entry._state.adding = True
entry.save()
entry.topics.set(old_topics)
entry = Entry.objects.get(pk=entry.pk)
self.assertCountEqual(entry.topics.all(), old_topics)
self.assertSequenceEqual(entry.topics.all(), [t1])
def test_add_m2m_with_base_class(self):
# Regression for #11956 -- You can add an object to a m2m with the
# base class without causing integrity errors
t1 = Tag.objects.create(name="t1")
t2 = Tag.objects.create(name="t2")
c1 = TagCollection.objects.create(name="c1")
c1.tags.set([t1, t2])
c1 = TagCollection.objects.get(name="c1")
self.assertCountEqual(c1.tags.all(), [t1, t2])
self.assertCountEqual(t1.tag_collections.all(), [c1])
def test_manager_class_caching(self):
e1 = Entry.objects.create()
e2 = Entry.objects.create()
t1 = Tag.objects.create()
t2 = Tag.objects.create()
# Get same manager twice in a row:
self.assertIs(t1.entry_set.__class__, t1.entry_set.__class__)
self.assertIs(e1.topics.__class__, e1.topics.__class__)
# Get same manager for different instances
self.assertIs(e1.topics.__class__, e2.topics.__class__)
self.assertIs(t1.entry_set.__class__, t2.entry_set.__class__)
def test_m2m_abstract_split(self):
# Regression for #19236 - an abstract class with a 'split' method
# causes a TypeError in add_lazy_relation
m1 = RegressionModelSplit(name="1")
m1.save()
def test_assigning_invalid_data_to_m2m_doesnt_clear_existing_relations(self):
t1 = Tag.objects.create(name="t1")
t2 = Tag.objects.create(name="t2")
c1 = TagCollection.objects.create(name="c1")
c1.tags.set([t1, t2])
with self.assertRaisesMessage(TypeError, "'int' object is not iterable"):
c1.tags.set(7)
c1.refresh_from_db()
self.assertSequenceEqual(c1.tags.order_by("name"), [t1, t2])
def test_multiple_forwards_only_m2m(self):
# Regression for #24505 - Multiple ManyToManyFields to same "to"
# model with related_name set to '+'.
foo = Line.objects.create(name="foo")
bar = Line.objects.create(name="bar")
post = Post.objects.create()
post.primary_lines.add(foo)
post.secondary_lines.add(bar)
self.assertSequenceEqual(post.primary_lines.all(), [foo])
self.assertSequenceEqual(post.secondary_lines.all(), [bar])
|
23da0c21aac7418ea6d28afd65ad3f8d62f106ef14634c0037fb36865ee885e2 | from django.db import migrations, models
from ..fields import (
ArrayField,
BigIntegerRangeField,
CICharField,
CIEmailField,
CITextField,
DateRangeField,
DateTimeRangeField,
DecimalRangeField,
EnumField,
HStoreField,
IntegerRangeField,
SearchVectorField,
)
from ..models import TagField
class Migration(migrations.Migration):
dependencies = [
("postgres_tests", "0001_setup_extensions"),
]
operations = [
migrations.CreateModel(
name="CharArrayModel",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("field", ArrayField(models.CharField(max_length=10), size=None)),
],
options={
"required_db_vendor": "postgresql",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="DateTimeArrayModel",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("datetimes", ArrayField(models.DateTimeField(), size=None)),
("dates", ArrayField(models.DateField(), size=None)),
("times", ArrayField(models.TimeField(), size=None)),
],
options={
"required_db_vendor": "postgresql",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="HStoreModel",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("field", HStoreField(blank=True, null=True)),
("array_field", ArrayField(HStoreField(), null=True)),
],
options={
"required_db_vendor": "postgresql",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="OtherTypesArrayModel",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"ips",
ArrayField(models.GenericIPAddressField(), size=None, default=list),
),
("uuids", ArrayField(models.UUIDField(), size=None, default=list)),
(
"decimals",
ArrayField(
models.DecimalField(max_digits=5, decimal_places=2),
size=None,
default=list,
),
),
("tags", ArrayField(TagField(), blank=True, null=True, size=None)),
(
"json",
ArrayField(models.JSONField(default=dict), default=list, size=None),
),
("int_ranges", ArrayField(IntegerRangeField(), null=True, blank=True)),
(
"bigint_ranges",
ArrayField(BigIntegerRangeField(), null=True, blank=True),
),
],
options={
"required_db_vendor": "postgresql",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="IntegerArrayModel",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"field",
ArrayField(
models.IntegerField(), blank=True, default=list, size=None
),
),
],
options={
"required_db_vendor": "postgresql",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="NestedIntegerArrayModel",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"field",
ArrayField(ArrayField(models.IntegerField(), size=None), size=None),
),
],
options={
"required_db_vendor": "postgresql",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="NullableIntegerArrayModel",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"field",
ArrayField(models.IntegerField(), size=None, null=True, blank=True),
),
(
"field_nested",
ArrayField(
ArrayField(models.IntegerField(null=True), size=None),
size=None,
null=True,
),
),
("order", models.IntegerField(null=True)),
],
options={
"required_db_vendor": "postgresql",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="CharFieldModel",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("field", models.CharField(max_length=64)),
],
options=None,
bases=None,
),
migrations.CreateModel(
name="TextFieldModel",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("field", models.TextField()),
],
options=None,
bases=None,
),
migrations.CreateModel(
name="SmallAutoFieldModel",
fields=[
(
"id",
models.SmallAutoField(serialize=False, primary_key=True),
),
],
options=None,
),
migrations.CreateModel(
name="BigAutoFieldModel",
fields=[
(
"id",
models.BigAutoField(serialize=False, primary_key=True),
),
],
options=None,
),
migrations.CreateModel(
name="Scene",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("scene", models.TextField()),
("setting", models.CharField(max_length=255)),
],
options=None,
bases=None,
),
migrations.CreateModel(
name="Character",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("name", models.CharField(max_length=255)),
],
options=None,
bases=None,
),
# RemovedInDjango51Warning.
migrations.CreateModel(
name="CITestModel",
fields=[
(
"name",
CICharField(primary_key=True, serialize=False, max_length=255),
),
("email", CIEmailField()),
("description", CITextField()),
("array_field", ArrayField(CITextField(), null=True)),
],
options={
"required_db_vendor": "postgresql",
},
bases=None,
),
migrations.CreateModel(
name="Line",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"scene",
models.ForeignKey("postgres_tests.Scene", on_delete=models.CASCADE),
),
(
"character",
models.ForeignKey(
"postgres_tests.Character", on_delete=models.CASCADE
),
),
("dialogue", models.TextField(blank=True, null=True)),
("dialogue_search_vector", SearchVectorField(blank=True, null=True)),
(
"dialogue_config",
models.CharField(max_length=100, blank=True, null=True),
),
],
options={
"required_db_vendor": "postgresql",
},
bases=None,
),
migrations.CreateModel(
name="LineSavedSearch",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"line",
models.ForeignKey("postgres_tests.Line", on_delete=models.CASCADE),
),
("query", models.CharField(max_length=100)),
],
options={
"required_db_vendor": "postgresql",
},
),
migrations.CreateModel(
name="AggregateTestModel",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("boolean_field", models.BooleanField(null=True)),
("char_field", models.CharField(max_length=30, blank=True)),
("text_field", models.TextField(blank=True)),
("integer_field", models.IntegerField(null=True)),
("json_field", models.JSONField(null=True)),
],
options={
"required_db_vendor": "postgresql",
},
),
migrations.CreateModel(
name="StatTestModel",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("int1", models.IntegerField()),
("int2", models.IntegerField()),
(
"related_field",
models.ForeignKey(
"postgres_tests.AggregateTestModel",
models.SET_NULL,
null=True,
),
),
],
options={
"required_db_vendor": "postgresql",
},
),
migrations.CreateModel(
name="NowTestModel",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("when", models.DateTimeField(null=True, default=None)),
],
),
migrations.CreateModel(
name="UUIDTestModel",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("uuid", models.UUIDField(default=None, null=True)),
],
),
migrations.CreateModel(
name="RangesModel",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("ints", IntegerRangeField(null=True, blank=True)),
("bigints", BigIntegerRangeField(null=True, blank=True)),
("decimals", DecimalRangeField(null=True, blank=True)),
("timestamps", DateTimeRangeField(null=True, blank=True)),
("timestamps_inner", DateTimeRangeField(null=True, blank=True)),
(
"timestamps_closed_bounds",
DateTimeRangeField(null=True, blank=True, default_bounds="[]"),
),
("dates", DateRangeField(null=True, blank=True)),
("dates_inner", DateRangeField(null=True, blank=True)),
],
options={"required_db_vendor": "postgresql"},
bases=(models.Model,),
),
migrations.CreateModel(
name="RangeLookupsModel",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"parent",
models.ForeignKey(
"postgres_tests.RangesModel",
models.SET_NULL,
blank=True,
null=True,
),
),
("integer", models.IntegerField(blank=True, null=True)),
("big_integer", models.BigIntegerField(blank=True, null=True)),
("float", models.FloatField(blank=True, null=True)),
("timestamp", models.DateTimeField(blank=True, null=True)),
("date", models.DateField(blank=True, null=True)),
("small_integer", models.SmallIntegerField(blank=True, null=True)),
(
"decimal_field",
models.DecimalField(
max_digits=5, decimal_places=2, blank=True, null=True
),
),
],
options={
"required_db_vendor": "postgresql",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="ArrayEnumModel",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"array_of_enums",
ArrayField(EnumField(max_length=20), size=None),
),
],
options={
"required_db_vendor": "postgresql",
},
bases=(models.Model,),
),
migrations.CreateModel(
name="Room",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("number", models.IntegerField(unique=True)),
],
),
migrations.CreateModel(
name="HotelReservation",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("room", models.ForeignKey("postgres_tests.Room", models.CASCADE)),
("datespan", DateRangeField()),
("start", models.DateTimeField()),
("end", models.DateTimeField()),
("cancelled", models.BooleanField(default=False)),
("requirements", models.JSONField(blank=True, null=True)),
],
options={
"required_db_vendor": "postgresql",
},
),
]
|
4e8ac4eed189915b770067984e45bb8c02d301788cab6abc29568473611133ab | from django.core.files.uploadedfile import SimpleUploadedFile
from django.forms import ClearableFileInput, FileField, Form, MultiWidget
from .base import WidgetTest
class FakeFieldFile:
"""
Quacks like a FieldFile (has a .url and string representation), but
doesn't require us to care about storages etc.
"""
url = "something"
def __str__(self):
return self.url
class ClearableFileInputTest(WidgetTest):
widget = ClearableFileInput()
def test_clear_input_renders(self):
"""
A ClearableFileInput with is_required False and rendered with an
initial value that is a file renders a clear checkbox.
"""
self.check_html(
self.widget,
"myfile",
FakeFieldFile(),
html=(
"""
Currently: <a href="something">something</a>
<input type="checkbox" name="myfile-clear" id="myfile-clear_id">
<label for="myfile-clear_id">Clear</label><br>
Change: <input type="file" name="myfile">
"""
),
)
def test_html_escaped(self):
"""
A ClearableFileInput should escape name, filename, and URL
when rendering HTML (#15182).
"""
class StrangeFieldFile:
url = "something?chapter=1§=2©=3&lang=en"
def __str__(self):
return """something<div onclick="alert('oops')">.jpg"""
self.check_html(
ClearableFileInput(),
"my<div>file",
StrangeFieldFile(),
html=(
"""
Currently:
<a href="something?chapter=1&sect=2&copy=3&lang=en">
something<div onclick="alert('oops')">.jpg</a>
<input type="checkbox" name="my<div>file-clear"
id="my<div>file-clear_id">
<label for="my<div>file-clear_id">Clear</label><br>
Change: <input type="file" name="my<div>file">
"""
),
)
def test_clear_input_renders_only_if_not_required(self):
"""
A ClearableFileInput with is_required=True does not render a clear
checkbox.
"""
widget = ClearableFileInput()
widget.is_required = True
self.check_html(
widget,
"myfile",
FakeFieldFile(),
html=(
"""
Currently: <a href="something">something</a> <br>
Change: <input type="file" name="myfile">
"""
),
)
def test_clear_input_renders_only_if_initial(self):
"""
A ClearableFileInput instantiated with no initial value does not render
a clear checkbox.
"""
self.check_html(
self.widget, "myfile", None, html='<input type="file" name="myfile">'
)
def test_render_disabled(self):
self.check_html(
self.widget,
"myfile",
FakeFieldFile(),
attrs={"disabled": True},
html=(
'Currently: <a href="something">something</a>'
'<input type="checkbox" name="myfile-clear" '
'id="myfile-clear_id" disabled>'
'<label for="myfile-clear_id">Clear</label><br>'
'Change: <input type="file" name="myfile" disabled>'
),
)
def test_render_no_disabled(self):
class TestForm(Form):
clearable_file = FileField(
widget=self.widget, initial=FakeFieldFile(), required=False
)
form = TestForm()
with self.assertNoLogs("django.template", "DEBUG"):
form.render()
def test_render_as_subwidget(self):
"""A ClearableFileInput as a subwidget of MultiWidget."""
widget = MultiWidget(widgets=(self.widget,))
self.check_html(
widget,
"myfile",
[FakeFieldFile()],
html=(
"""
Currently: <a href="something">something</a>
<input type="checkbox" name="myfile_0-clear" id="myfile_0-clear_id">
<label for="myfile_0-clear_id">Clear</label><br>
Change: <input type="file" name="myfile_0">
"""
),
)
def test_clear_input_checked_returns_false(self):
"""
ClearableFileInput.value_from_datadict returns False if the clear
checkbox is checked, if not required.
"""
value = self.widget.value_from_datadict(
data={"myfile-clear": True},
files={},
name="myfile",
)
self.assertIs(value, False)
def test_clear_input_checked_returns_false_only_if_not_required(self):
"""
ClearableFileInput.value_from_datadict never returns False if the field
is required.
"""
widget = ClearableFileInput()
widget.is_required = True
field = SimpleUploadedFile("something.txt", b"content")
value = widget.value_from_datadict(
data={"myfile-clear": True},
files={"myfile": field},
name="myfile",
)
self.assertEqual(value, field)
def test_html_does_not_mask_exceptions(self):
"""
A ClearableFileInput should not mask exceptions produced while
checking that it has a value.
"""
class FailingURLFieldFile:
@property
def url(self):
raise ValueError("Canary")
def __str__(self):
return "value"
with self.assertRaisesMessage(ValueError, "Canary"):
self.widget.render("myfile", FailingURLFieldFile())
def test_url_as_property(self):
class URLFieldFile:
@property
def url(self):
return "https://www.python.org/"
def __str__(self):
return "value"
html = self.widget.render("myfile", URLFieldFile())
self.assertInHTML('<a href="https://www.python.org/">value</a>', html)
def test_return_false_if_url_does_not_exists(self):
class NoURLFieldFile:
def __str__(self):
return "value"
html = self.widget.render("myfile", NoURLFieldFile())
self.assertHTMLEqual(html, '<input name="myfile" type="file">')
def test_use_required_attribute(self):
# False when initial data exists. The file input is left blank by the
# user to keep the existing, initial value.
self.assertIs(self.widget.use_required_attribute(None), True)
self.assertIs(self.widget.use_required_attribute("resume.txt"), False)
def test_value_omitted_from_data(self):
widget = ClearableFileInput()
self.assertIs(widget.value_omitted_from_data({}, {}, "field"), True)
self.assertIs(
widget.value_omitted_from_data({}, {"field": "x"}, "field"), False
)
self.assertIs(
widget.value_omitted_from_data({"field-clear": "y"}, {}, "field"), False
)
def test_fieldset(self):
class TestForm(Form):
template_name = "forms_tests/use_fieldset.html"
field = FileField(widget=self.widget)
with_file = FileField(widget=self.widget, initial=FakeFieldFile())
clearable_file = FileField(
widget=self.widget, initial=FakeFieldFile(), required=False
)
form = TestForm()
self.assertIs(self.widget.use_fieldset, False)
self.assertHTMLEqual(
'<div><label for="id_field">Field:</label>'
'<input id="id_field" name="field" type="file" required></div>'
'<div><label for="id_with_file">With file:</label>Currently: '
'<a href="something">something</a><br>Change:<input type="file" '
'name="with_file" id="id_with_file"></div>'
'<div><label for="id_clearable_file">Clearable file:</label>'
'Currently: <a href="something">something</a><input '
'type="checkbox" name="clearable_file-clear" id="clearable_file-clear_id">'
'<label for="clearable_file-clear_id">Clear</label><br>Change:'
'<input type="file" name="clearable_file" id="id_clearable_file"></div>',
form.render(),
)
|
9c3279a0f05d00846125e5594b2cac6e5f06eb811d02022fc5c7a05fd64537fe | import datetime
from collections import Counter
from unittest import mock
from django.core.exceptions import ValidationError
from django.forms import (
BaseForm,
CharField,
DateField,
FileField,
Form,
IntegerField,
SplitDateTimeField,
formsets,
)
from django.forms.formsets import (
INITIAL_FORM_COUNT,
MAX_NUM_FORM_COUNT,
MIN_NUM_FORM_COUNT,
TOTAL_FORM_COUNT,
BaseFormSet,
ManagementForm,
all_valid,
formset_factory,
)
from django.forms.renderers import TemplatesSetting, get_default_renderer
from django.forms.utils import ErrorList
from django.forms.widgets import HiddenInput
from django.test import SimpleTestCase
from django.test.utils import isolate_lru_cache
from django.utils.deprecation import RemovedInDjango50Warning
from . import jinja2_tests
class Choice(Form):
choice = CharField()
votes = IntegerField()
ChoiceFormSet = formset_factory(Choice)
class ChoiceFormsetWithNonFormError(ChoiceFormSet):
def clean(self):
super().clean()
raise ValidationError("non-form error")
class FavoriteDrinkForm(Form):
name = CharField()
class BaseFavoriteDrinksFormSet(BaseFormSet):
def clean(self):
seen_drinks = []
for drink in self.cleaned_data:
if drink["name"] in seen_drinks:
raise ValidationError("You may only specify a drink once.")
seen_drinks.append(drink["name"])
# A FormSet that takes a list of favorite drinks and raises an error if
# there are any duplicates.
FavoriteDrinksFormSet = formset_factory(
FavoriteDrinkForm, formset=BaseFavoriteDrinksFormSet, extra=3
)
class CustomKwargForm(Form):
def __init__(self, *args, custom_kwarg, **kwargs):
self.custom_kwarg = custom_kwarg
super().__init__(*args, **kwargs)
class FormsFormsetTestCase(SimpleTestCase):
def make_choiceformset(
self,
formset_data=None,
formset_class=ChoiceFormSet,
total_forms=None,
initial_forms=0,
max_num_forms=0,
min_num_forms=0,
**kwargs,
):
"""
Make a ChoiceFormset from the given formset_data.
The data should be given as a list of (choice, votes) tuples.
"""
kwargs.setdefault("prefix", "choices")
kwargs.setdefault("auto_id", False)
if formset_data is None:
return formset_class(**kwargs)
if total_forms is None:
total_forms = len(formset_data)
def prefixed(*args):
args = (kwargs["prefix"],) + args
return "-".join(args)
data = {
prefixed("TOTAL_FORMS"): str(total_forms),
prefixed("INITIAL_FORMS"): str(initial_forms),
prefixed("MAX_NUM_FORMS"): str(max_num_forms),
prefixed("MIN_NUM_FORMS"): str(min_num_forms),
}
for i, (choice, votes) in enumerate(formset_data):
data[prefixed(str(i), "choice")] = choice
data[prefixed(str(i), "votes")] = votes
return formset_class(data, **kwargs)
def test_basic_formset(self):
"""
A FormSet constructor takes the same arguments as Form. Create a
FormSet for adding data. By default, it displays 1 blank form.
"""
formset = self.make_choiceformset()
self.assertHTMLEqual(
str(formset),
"""<input type="hidden" name="choices-TOTAL_FORMS" value="1">
<input type="hidden" name="choices-INITIAL_FORMS" value="0">
<input type="hidden" name="choices-MIN_NUM_FORMS" value="0">
<input type="hidden" name="choices-MAX_NUM_FORMS" value="1000">
<div>Choice:<input type="text" name="choices-0-choice"></div>
<div>Votes:<input type="number" name="choices-0-votes"></div>""",
)
# FormSet are treated similarly to Forms. FormSet has an is_valid()
# method, and a cleaned_data or errors attribute depending on whether
# all the forms passed validation. However, unlike a Form, cleaned_data
# and errors will be a list of dicts rather than a single dict.
formset = self.make_choiceformset([("Calexico", "100")])
self.assertTrue(formset.is_valid())
self.assertEqual(
[form.cleaned_data for form in formset.forms],
[{"votes": 100, "choice": "Calexico"}],
)
# If a FormSet wasn't passed any data, is_valid() and has_changed()
# return False.
formset = self.make_choiceformset()
self.assertFalse(formset.is_valid())
self.assertFalse(formset.has_changed())
def test_form_kwargs_formset(self):
"""
Custom kwargs set on the formset instance are passed to the
underlying forms.
"""
FormSet = formset_factory(CustomKwargForm, extra=2)
formset = FormSet(form_kwargs={"custom_kwarg": 1})
for form in formset:
self.assertTrue(hasattr(form, "custom_kwarg"))
self.assertEqual(form.custom_kwarg, 1)
def test_form_kwargs_formset_dynamic(self):
"""Form kwargs can be passed dynamically in a formset."""
class DynamicBaseFormSet(BaseFormSet):
def get_form_kwargs(self, index):
return {"custom_kwarg": index}
DynamicFormSet = formset_factory(
CustomKwargForm, formset=DynamicBaseFormSet, extra=2
)
formset = DynamicFormSet(form_kwargs={"custom_kwarg": "ignored"})
for i, form in enumerate(formset):
self.assertTrue(hasattr(form, "custom_kwarg"))
self.assertEqual(form.custom_kwarg, i)
def test_form_kwargs_empty_form(self):
FormSet = formset_factory(CustomKwargForm)
formset = FormSet(form_kwargs={"custom_kwarg": 1})
self.assertTrue(hasattr(formset.empty_form, "custom_kwarg"))
self.assertEqual(formset.empty_form.custom_kwarg, 1)
def test_empty_permitted_ignored_empty_form(self):
formset = ArticleFormSet(form_kwargs={"empty_permitted": False})
self.assertIs(formset.empty_form.empty_permitted, True)
def test_formset_validation(self):
# FormSet instances can also have an error attribute if validation failed for
# any of the forms.
formset = self.make_choiceformset([("Calexico", "")])
self.assertFalse(formset.is_valid())
self.assertEqual(formset.errors, [{"votes": ["This field is required."]}])
def test_formset_validation_count(self):
"""
A formset's ManagementForm is validated once per FormSet.is_valid()
call and each form of the formset is cleaned once.
"""
def make_method_counter(func):
"""Add a counter to func for the number of times it's called."""
counter = Counter()
counter.call_count = 0
def mocked_func(*args, **kwargs):
counter.call_count += 1
return func(*args, **kwargs)
return mocked_func, counter
mocked_is_valid, is_valid_counter = make_method_counter(
formsets.ManagementForm.is_valid
)
mocked_full_clean, full_clean_counter = make_method_counter(BaseForm.full_clean)
formset = self.make_choiceformset(
[("Calexico", "100"), ("Any1", "42"), ("Any2", "101")]
)
with mock.patch(
"django.forms.formsets.ManagementForm.is_valid", mocked_is_valid
), mock.patch("django.forms.forms.BaseForm.full_clean", mocked_full_clean):
self.assertTrue(formset.is_valid())
self.assertEqual(is_valid_counter.call_count, 1)
self.assertEqual(full_clean_counter.call_count, 4)
def test_formset_has_changed(self):
"""
FormSet.has_changed() is True if any data is passed to its forms, even
if the formset didn't validate.
"""
blank_formset = self.make_choiceformset([("", "")])
self.assertFalse(blank_formset.has_changed())
# invalid formset
invalid_formset = self.make_choiceformset([("Calexico", "")])
self.assertFalse(invalid_formset.is_valid())
self.assertTrue(invalid_formset.has_changed())
# valid formset
valid_formset = self.make_choiceformset([("Calexico", "100")])
self.assertTrue(valid_formset.is_valid())
self.assertTrue(valid_formset.has_changed())
def test_formset_initial_data(self):
"""
A FormSet can be prefilled with existing data by providing a list of
dicts to the `initial` argument. By default, an extra blank form is
included.
"""
formset = self.make_choiceformset(
initial=[{"choice": "Calexico", "votes": 100}]
)
self.assertHTMLEqual(
"\n".join(form.as_ul() for form in formset.forms),
'<li>Choice: <input type="text" name="choices-0-choice" value="Calexico">'
"</li>"
'<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>'
'<li>Choice: <input type="text" name="choices-1-choice"></li>'
'<li>Votes: <input type="number" name="choices-1-votes"></li>',
)
def test_blank_form_unfilled(self):
"""A form that's displayed as blank may be submitted as blank."""
formset = self.make_choiceformset(
[("Calexico", "100"), ("", "")], initial_forms=1
)
self.assertTrue(formset.is_valid())
self.assertEqual(
[form.cleaned_data for form in formset.forms],
[{"votes": 100, "choice": "Calexico"}, {}],
)
def test_second_form_partially_filled(self):
"""
If at least one field is filled out on a blank form, it will be
validated.
"""
formset = self.make_choiceformset(
[("Calexico", "100"), ("The Decemberists", "")], initial_forms=1
)
self.assertFalse(formset.is_valid())
self.assertEqual(formset.errors, [{}, {"votes": ["This field is required."]}])
def test_delete_prefilled_data(self):
"""
Deleting prefilled data is an error. Removing data from form fields
isn't the proper way to delete it.
"""
formset = self.make_choiceformset([("", ""), ("", "")], initial_forms=1)
self.assertFalse(formset.is_valid())
self.assertEqual(
formset.errors,
[
{
"votes": ["This field is required."],
"choice": ["This field is required."],
},
{},
],
)
def test_displaying_more_than_one_blank_form(self):
"""
More than 1 empty form can be displayed using formset_factory's
`extra` argument.
"""
ChoiceFormSet = formset_factory(Choice, extra=3)
formset = ChoiceFormSet(auto_id=False, prefix="choices")
self.assertHTMLEqual(
"\n".join(form.as_ul() for form in formset.forms),
"""<li>Choice: <input type="text" name="choices-0-choice"></li>
<li>Votes: <input type="number" name="choices-0-votes"></li>
<li>Choice: <input type="text" name="choices-1-choice"></li>
<li>Votes: <input type="number" name="choices-1-votes"></li>
<li>Choice: <input type="text" name="choices-2-choice"></li>
<li>Votes: <input type="number" name="choices-2-votes"></li>""",
)
# Since every form was displayed as blank, they are also accepted as
# blank. This may seem a little strange, but min_num is used to require
# a minimum number of forms to be completed.
data = {
"choices-TOTAL_FORMS": "3", # the number of forms rendered
"choices-INITIAL_FORMS": "0", # the number of forms with initial data
"choices-MIN_NUM_FORMS": "0", # min number of forms
"choices-MAX_NUM_FORMS": "0", # max number of forms
"choices-0-choice": "",
"choices-0-votes": "",
"choices-1-choice": "",
"choices-1-votes": "",
"choices-2-choice": "",
"choices-2-votes": "",
}
formset = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertTrue(formset.is_valid())
self.assertEqual([form.cleaned_data for form in formset.forms], [{}, {}, {}])
def test_min_num_displaying_more_than_one_blank_form(self):
"""
More than 1 empty form can also be displayed using formset_factory's
min_num argument. It will (essentially) increment the extra argument.
"""
ChoiceFormSet = formset_factory(Choice, extra=1, min_num=1)
formset = ChoiceFormSet(auto_id=False, prefix="choices")
# Min_num forms are required; extra forms can be empty.
self.assertFalse(formset.forms[0].empty_permitted)
self.assertTrue(formset.forms[1].empty_permitted)
self.assertHTMLEqual(
"\n".join(form.as_ul() for form in formset.forms),
"""<li>Choice: <input type="text" name="choices-0-choice"></li>
<li>Votes: <input type="number" name="choices-0-votes"></li>
<li>Choice: <input type="text" name="choices-1-choice"></li>
<li>Votes: <input type="number" name="choices-1-votes"></li>""",
)
def test_min_num_displaying_more_than_one_blank_form_with_zero_extra(self):
"""More than 1 empty form can be displayed using min_num."""
ChoiceFormSet = formset_factory(Choice, extra=0, min_num=3)
formset = ChoiceFormSet(auto_id=False, prefix="choices")
self.assertHTMLEqual(
"\n".join(form.as_ul() for form in formset.forms),
"""<li>Choice: <input type="text" name="choices-0-choice"></li>
<li>Votes: <input type="number" name="choices-0-votes"></li>
<li>Choice: <input type="text" name="choices-1-choice"></li>
<li>Votes: <input type="number" name="choices-1-votes"></li>
<li>Choice: <input type="text" name="choices-2-choice"></li>
<li>Votes: <input type="number" name="choices-2-votes"></li>""",
)
def test_single_form_completed(self):
"""Just one form may be completed."""
data = {
"choices-TOTAL_FORMS": "3", # the number of forms rendered
"choices-INITIAL_FORMS": "0", # the number of forms with initial data
"choices-MIN_NUM_FORMS": "0", # min number of forms
"choices-MAX_NUM_FORMS": "0", # max number of forms
"choices-0-choice": "Calexico",
"choices-0-votes": "100",
"choices-1-choice": "",
"choices-1-votes": "",
"choices-2-choice": "",
"choices-2-votes": "",
}
ChoiceFormSet = formset_factory(Choice, extra=3)
formset = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertTrue(formset.is_valid())
self.assertEqual(
[form.cleaned_data for form in formset.forms],
[{"votes": 100, "choice": "Calexico"}, {}, {}],
)
def test_formset_validate_max_flag(self):
"""
If validate_max is set and max_num is less than TOTAL_FORMS in the
data, a ValidationError is raised. MAX_NUM_FORMS in the data is
irrelevant here (it's output as a hint for the client but its value
in the returned data is not checked).
"""
data = {
"choices-TOTAL_FORMS": "2", # the number of forms rendered
"choices-INITIAL_FORMS": "0", # the number of forms with initial data
"choices-MIN_NUM_FORMS": "0", # min number of forms
"choices-MAX_NUM_FORMS": "2", # max number of forms - should be ignored
"choices-0-choice": "Zero",
"choices-0-votes": "0",
"choices-1-choice": "One",
"choices-1-votes": "1",
}
ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True)
formset = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertFalse(formset.is_valid())
self.assertEqual(formset.non_form_errors(), ["Please submit at most 1 form."])
self.assertEqual(
str(formset.non_form_errors()),
'<ul class="errorlist nonform"><li>Please submit at most 1 form.</li></ul>',
)
def test_formset_validate_max_flag_custom_error(self):
data = {
"choices-TOTAL_FORMS": "2",
"choices-INITIAL_FORMS": "0",
"choices-MIN_NUM_FORMS": "0",
"choices-MAX_NUM_FORMS": "2",
"choices-0-choice": "Zero",
"choices-0-votes": "0",
"choices-1-choice": "One",
"choices-1-votes": "1",
}
ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True)
formset = ChoiceFormSet(
data,
auto_id=False,
prefix="choices",
error_messages={
"too_many_forms": "Number of submitted forms should be at most %(num)d."
},
)
self.assertFalse(formset.is_valid())
self.assertEqual(
formset.non_form_errors(),
["Number of submitted forms should be at most 1."],
)
self.assertEqual(
str(formset.non_form_errors()),
'<ul class="errorlist nonform">'
"<li>Number of submitted forms should be at most 1.</li></ul>",
)
def test_formset_validate_min_flag(self):
"""
If validate_min is set and min_num is more than TOTAL_FORMS in the
data, a ValidationError is raised. MIN_NUM_FORMS in the data is
irrelevant here (it's output as a hint for the client but its value
in the returned data is not checked).
"""
data = {
"choices-TOTAL_FORMS": "2", # the number of forms rendered
"choices-INITIAL_FORMS": "0", # the number of forms with initial data
"choices-MIN_NUM_FORMS": "0", # min number of forms
"choices-MAX_NUM_FORMS": "0", # max number of forms - should be ignored
"choices-0-choice": "Zero",
"choices-0-votes": "0",
"choices-1-choice": "One",
"choices-1-votes": "1",
}
ChoiceFormSet = formset_factory(Choice, extra=1, min_num=3, validate_min=True)
formset = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertFalse(formset.is_valid())
self.assertEqual(formset.non_form_errors(), ["Please submit at least 3 forms."])
self.assertEqual(
str(formset.non_form_errors()),
'<ul class="errorlist nonform"><li>'
"Please submit at least 3 forms.</li></ul>",
)
def test_formset_validate_min_flag_custom_formatted_error(self):
data = {
"choices-TOTAL_FORMS": "2",
"choices-INITIAL_FORMS": "0",
"choices-MIN_NUM_FORMS": "0",
"choices-MAX_NUM_FORMS": "0",
"choices-0-choice": "Zero",
"choices-0-votes": "0",
"choices-1-choice": "One",
"choices-1-votes": "1",
}
ChoiceFormSet = formset_factory(Choice, extra=1, min_num=3, validate_min=True)
formset = ChoiceFormSet(
data,
auto_id=False,
prefix="choices",
error_messages={
"too_few_forms": "Number of submitted forms should be at least %(num)d."
},
)
self.assertFalse(formset.is_valid())
self.assertEqual(
formset.non_form_errors(),
["Number of submitted forms should be at least 3."],
)
self.assertEqual(
str(formset.non_form_errors()),
'<ul class="errorlist nonform">'
"<li>Number of submitted forms should be at least 3.</li></ul>",
)
def test_formset_validate_min_unchanged_forms(self):
"""
min_num validation doesn't consider unchanged forms with initial data
as "empty".
"""
initial = [
{"choice": "Zero", "votes": 0},
{"choice": "One", "votes": 0},
]
data = {
"choices-TOTAL_FORMS": "2",
"choices-INITIAL_FORMS": "2",
"choices-MIN_NUM_FORMS": "0",
"choices-MAX_NUM_FORMS": "2",
"choices-0-choice": "Zero",
"choices-0-votes": "0",
"choices-1-choice": "One",
"choices-1-votes": "1", # changed from initial
}
ChoiceFormSet = formset_factory(Choice, min_num=2, validate_min=True)
formset = ChoiceFormSet(data, auto_id=False, prefix="choices", initial=initial)
self.assertFalse(formset.forms[0].has_changed())
self.assertTrue(formset.forms[1].has_changed())
self.assertTrue(formset.is_valid())
def test_formset_validate_min_excludes_empty_forms(self):
data = {
"choices-TOTAL_FORMS": "2",
"choices-INITIAL_FORMS": "0",
}
ChoiceFormSet = formset_factory(
Choice, extra=2, min_num=1, validate_min=True, can_delete=True
)
formset = ChoiceFormSet(data, prefix="choices")
self.assertFalse(formset.has_changed())
self.assertFalse(formset.is_valid())
self.assertEqual(formset.non_form_errors(), ["Please submit at least 1 form."])
def test_second_form_partially_filled_2(self):
"""A partially completed form is invalid."""
data = {
"choices-TOTAL_FORMS": "3", # the number of forms rendered
"choices-INITIAL_FORMS": "0", # the number of forms with initial data
"choices-MIN_NUM_FORMS": "0", # min number of forms
"choices-MAX_NUM_FORMS": "0", # max number of forms
"choices-0-choice": "Calexico",
"choices-0-votes": "100",
"choices-1-choice": "The Decemberists",
"choices-1-votes": "", # missing value
"choices-2-choice": "",
"choices-2-votes": "",
}
ChoiceFormSet = formset_factory(Choice, extra=3)
formset = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertFalse(formset.is_valid())
self.assertEqual(
formset.errors, [{}, {"votes": ["This field is required."]}, {}]
)
def test_more_initial_data(self):
"""
The extra argument works when the formset is pre-filled with initial
data.
"""
initial = [{"choice": "Calexico", "votes": 100}]
ChoiceFormSet = formset_factory(Choice, extra=3)
formset = ChoiceFormSet(initial=initial, auto_id=False, prefix="choices")
self.assertHTMLEqual(
"\n".join(form.as_ul() for form in formset.forms),
'<li>Choice: <input type="text" name="choices-0-choice" value="Calexico">'
"</li>"
'<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>'
'<li>Choice: <input type="text" name="choices-1-choice"></li>'
'<li>Votes: <input type="number" name="choices-1-votes"></li>'
'<li>Choice: <input type="text" name="choices-2-choice"></li>'
'<li>Votes: <input type="number" name="choices-2-votes"></li>'
'<li>Choice: <input type="text" name="choices-3-choice"></li>'
'<li>Votes: <input type="number" name="choices-3-votes"></li>',
)
# Retrieving an empty form works. Tt shows up in the form list.
self.assertTrue(formset.empty_form.empty_permitted)
self.assertHTMLEqual(
formset.empty_form.as_ul(),
"""<li>Choice: <input type="text" name="choices-__prefix__-choice"></li>
<li>Votes: <input type="number" name="choices-__prefix__-votes"></li>""",
)
def test_formset_with_deletion(self):
"""
formset_factory's can_delete argument adds a boolean "delete" field to
each form. When that boolean field is True, the form will be in
formset.deleted_forms.
"""
ChoiceFormSet = formset_factory(Choice, can_delete=True)
initial = [
{"choice": "Calexico", "votes": 100},
{"choice": "Fergie", "votes": 900},
]
formset = ChoiceFormSet(initial=initial, auto_id=False, prefix="choices")
self.assertHTMLEqual(
"\n".join(form.as_ul() for form in formset.forms),
'<li>Choice: <input type="text" name="choices-0-choice" value="Calexico">'
"</li>"
'<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>'
'<li>Delete: <input type="checkbox" name="choices-0-DELETE"></li>'
'<li>Choice: <input type="text" name="choices-1-choice" value="Fergie">'
"</li>"
'<li>Votes: <input type="number" name="choices-1-votes" value="900"></li>'
'<li>Delete: <input type="checkbox" name="choices-1-DELETE"></li>'
'<li>Choice: <input type="text" name="choices-2-choice"></li>'
'<li>Votes: <input type="number" name="choices-2-votes"></li>'
'<li>Delete: <input type="checkbox" name="choices-2-DELETE"></li>',
)
# To delete something, set that form's special delete field to 'on'.
# Let's go ahead and delete Fergie.
data = {
"choices-TOTAL_FORMS": "3", # the number of forms rendered
"choices-INITIAL_FORMS": "2", # the number of forms with initial data
"choices-MIN_NUM_FORMS": "0", # min number of forms
"choices-MAX_NUM_FORMS": "0", # max number of forms
"choices-0-choice": "Calexico",
"choices-0-votes": "100",
"choices-0-DELETE": "",
"choices-1-choice": "Fergie",
"choices-1-votes": "900",
"choices-1-DELETE": "on",
"choices-2-choice": "",
"choices-2-votes": "",
"choices-2-DELETE": "",
}
formset = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertTrue(formset.is_valid())
self.assertEqual(
[form.cleaned_data for form in formset.forms],
[
{"votes": 100, "DELETE": False, "choice": "Calexico"},
{"votes": 900, "DELETE": True, "choice": "Fergie"},
{},
],
)
self.assertEqual(
[form.cleaned_data for form in formset.deleted_forms],
[{"votes": 900, "DELETE": True, "choice": "Fergie"}],
)
def test_formset_with_deletion_remove_deletion_flag(self):
"""
If a form is filled with something and can_delete is also checked, that
form's errors shouldn't make the entire formset invalid since it's
going to be deleted.
"""
class CheckForm(Form):
field = IntegerField(min_value=100)
data = {
"check-TOTAL_FORMS": "3", # the number of forms rendered
"check-INITIAL_FORMS": "2", # the number of forms with initial data
"choices-MIN_NUM_FORMS": "0", # min number of forms
"check-MAX_NUM_FORMS": "0", # max number of forms
"check-0-field": "200",
"check-0-DELETE": "",
"check-1-field": "50",
"check-1-DELETE": "on",
"check-2-field": "",
"check-2-DELETE": "",
}
CheckFormSet = formset_factory(CheckForm, can_delete=True)
formset = CheckFormSet(data, prefix="check")
self.assertTrue(formset.is_valid())
# If the deletion flag is removed, validation is enabled.
data["check-1-DELETE"] = ""
formset = CheckFormSet(data, prefix="check")
self.assertFalse(formset.is_valid())
def test_formset_with_deletion_invalid_deleted_form(self):
"""
deleted_forms works on a valid formset even if a deleted form would
have been invalid.
"""
FavoriteDrinkFormset = formset_factory(form=FavoriteDrinkForm, can_delete=True)
formset = FavoriteDrinkFormset(
{
"form-0-name": "",
"form-0-DELETE": "on", # no name!
"form-TOTAL_FORMS": 1,
"form-INITIAL_FORMS": 1,
"form-MIN_NUM_FORMS": 0,
"form-MAX_NUM_FORMS": 1,
}
)
self.assertTrue(formset.is_valid())
self.assertEqual(formset._errors, [])
self.assertEqual(len(formset.deleted_forms), 1)
def test_formset_with_deletion_custom_widget(self):
class DeletionAttributeFormSet(BaseFormSet):
deletion_widget = HiddenInput
class DeletionMethodFormSet(BaseFormSet):
def get_deletion_widget(self):
return HiddenInput(attrs={"class": "deletion"})
tests = [
(DeletionAttributeFormSet, '<input type="hidden" name="form-0-DELETE">'),
(
DeletionMethodFormSet,
'<input class="deletion" type="hidden" name="form-0-DELETE">',
),
]
for formset_class, delete_html in tests:
with self.subTest(formset_class=formset_class.__name__):
ArticleFormSet = formset_factory(
ArticleForm,
formset=formset_class,
can_delete=True,
)
formset = ArticleFormSet(auto_id=False)
self.assertHTMLEqual(
"\n".join([form.as_ul() for form in formset.forms]),
(
f'<li>Title: <input type="text" name="form-0-title"></li>'
f'<li>Pub date: <input type="text" name="form-0-pub_date">'
f"{delete_html}</li>"
),
)
def test_formsets_with_ordering(self):
"""
formset_factory's can_order argument adds an integer field to each
form. When form validation succeeds,
[form.cleaned_data for form in formset.forms]
will have the data in the correct order specified by the ordering
fields. If a number is duplicated in the set of ordering fields, for
instance form 0 and form 3 are both marked as 1, then the form index
used as a secondary ordering criteria. In order to put something at the
front of the list, you'd need to set its order to 0.
"""
ChoiceFormSet = formset_factory(Choice, can_order=True)
initial = [
{"choice": "Calexico", "votes": 100},
{"choice": "Fergie", "votes": 900},
]
formset = ChoiceFormSet(initial=initial, auto_id=False, prefix="choices")
self.assertHTMLEqual(
"\n".join(form.as_ul() for form in formset.forms),
'<li>Choice: <input type="text" name="choices-0-choice" value="Calexico">'
"</li>"
'<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>'
'<li>Order: <input type="number" name="choices-0-ORDER" value="1"></li>'
'<li>Choice: <input type="text" name="choices-1-choice" value="Fergie">'
"</li>"
'<li>Votes: <input type="number" name="choices-1-votes" value="900"></li>'
'<li>Order: <input type="number" name="choices-1-ORDER" value="2"></li>'
'<li>Choice: <input type="text" name="choices-2-choice"></li>'
'<li>Votes: <input type="number" name="choices-2-votes"></li>'
'<li>Order: <input type="number" name="choices-2-ORDER"></li>',
)
data = {
"choices-TOTAL_FORMS": "3", # the number of forms rendered
"choices-INITIAL_FORMS": "2", # the number of forms with initial data
"choices-MIN_NUM_FORMS": "0", # min number of forms
"choices-MAX_NUM_FORMS": "0", # max number of forms
"choices-0-choice": "Calexico",
"choices-0-votes": "100",
"choices-0-ORDER": "1",
"choices-1-choice": "Fergie",
"choices-1-votes": "900",
"choices-1-ORDER": "2",
"choices-2-choice": "The Decemberists",
"choices-2-votes": "500",
"choices-2-ORDER": "0",
}
formset = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertTrue(formset.is_valid())
self.assertEqual(
[form.cleaned_data for form in formset.ordered_forms],
[
{"votes": 500, "ORDER": 0, "choice": "The Decemberists"},
{"votes": 100, "ORDER": 1, "choice": "Calexico"},
{"votes": 900, "ORDER": 2, "choice": "Fergie"},
],
)
def test_formsets_with_ordering_custom_widget(self):
class OrderingAttributeFormSet(BaseFormSet):
ordering_widget = HiddenInput
class OrderingMethodFormSet(BaseFormSet):
def get_ordering_widget(self):
return HiddenInput(attrs={"class": "ordering"})
tests = (
(OrderingAttributeFormSet, '<input type="hidden" name="form-0-ORDER">'),
(
OrderingMethodFormSet,
'<input class="ordering" type="hidden" name="form-0-ORDER">',
),
)
for formset_class, order_html in tests:
with self.subTest(formset_class=formset_class.__name__):
ArticleFormSet = formset_factory(
ArticleForm, formset=formset_class, can_order=True
)
formset = ArticleFormSet(auto_id=False)
self.assertHTMLEqual(
"\n".join(form.as_ul() for form in formset.forms),
(
'<li>Title: <input type="text" name="form-0-title"></li>'
'<li>Pub date: <input type="text" name="form-0-pub_date">'
"%s</li>" % order_html
),
)
def test_empty_ordered_fields(self):
"""
Ordering fields are allowed to be left blank. If they are left blank,
they'll be sorted below everything else.
"""
data = {
"choices-TOTAL_FORMS": "4", # the number of forms rendered
"choices-INITIAL_FORMS": "3", # the number of forms with initial data
"choices-MIN_NUM_FORMS": "0", # min number of forms
"choices-MAX_NUM_FORMS": "0", # max number of forms
"choices-0-choice": "Calexico",
"choices-0-votes": "100",
"choices-0-ORDER": "1",
"choices-1-choice": "Fergie",
"choices-1-votes": "900",
"choices-1-ORDER": "2",
"choices-2-choice": "The Decemberists",
"choices-2-votes": "500",
"choices-2-ORDER": "",
"choices-3-choice": "Basia Bulat",
"choices-3-votes": "50",
"choices-3-ORDER": "",
}
ChoiceFormSet = formset_factory(Choice, can_order=True)
formset = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertTrue(formset.is_valid())
self.assertEqual(
[form.cleaned_data for form in formset.ordered_forms],
[
{"votes": 100, "ORDER": 1, "choice": "Calexico"},
{"votes": 900, "ORDER": 2, "choice": "Fergie"},
{"votes": 500, "ORDER": None, "choice": "The Decemberists"},
{"votes": 50, "ORDER": None, "choice": "Basia Bulat"},
],
)
def test_ordering_blank_fieldsets(self):
"""Ordering works with blank fieldsets."""
data = {
"choices-TOTAL_FORMS": "3", # the number of forms rendered
"choices-INITIAL_FORMS": "0", # the number of forms with initial data
"choices-MIN_NUM_FORMS": "0", # min number of forms
"choices-MAX_NUM_FORMS": "0", # max number of forms
}
ChoiceFormSet = formset_factory(Choice, can_order=True)
formset = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertTrue(formset.is_valid())
self.assertEqual(formset.ordered_forms, [])
def test_formset_with_ordering_and_deletion(self):
"""FormSets with ordering + deletion."""
ChoiceFormSet = formset_factory(Choice, can_order=True, can_delete=True)
initial = [
{"choice": "Calexico", "votes": 100},
{"choice": "Fergie", "votes": 900},
{"choice": "The Decemberists", "votes": 500},
]
formset = ChoiceFormSet(initial=initial, auto_id=False, prefix="choices")
self.assertHTMLEqual(
"\n".join(form.as_ul() for form in formset.forms),
'<li>Choice: <input type="text" name="choices-0-choice" value="Calexico">'
"</li>"
'<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>'
'<li>Order: <input type="number" name="choices-0-ORDER" value="1"></li>'
'<li>Delete: <input type="checkbox" name="choices-0-DELETE"></li>'
'<li>Choice: <input type="text" name="choices-1-choice" value="Fergie">'
"</li>"
'<li>Votes: <input type="number" name="choices-1-votes" value="900"></li>'
'<li>Order: <input type="number" name="choices-1-ORDER" value="2"></li>'
'<li>Delete: <input type="checkbox" name="choices-1-DELETE"></li>'
'<li>Choice: <input type="text" name="choices-2-choice" '
'value="The Decemberists"></li>'
'<li>Votes: <input type="number" name="choices-2-votes" value="500"></li>'
'<li>Order: <input type="number" name="choices-2-ORDER" value="3"></li>'
'<li>Delete: <input type="checkbox" name="choices-2-DELETE"></li>'
'<li>Choice: <input type="text" name="choices-3-choice"></li>'
'<li>Votes: <input type="number" name="choices-3-votes"></li>'
'<li>Order: <input type="number" name="choices-3-ORDER"></li>'
'<li>Delete: <input type="checkbox" name="choices-3-DELETE"></li>',
)
# Let's delete Fergie, and put The Decemberists ahead of Calexico.
data = {
"choices-TOTAL_FORMS": "4", # the number of forms rendered
"choices-INITIAL_FORMS": "3", # the number of forms with initial data
"choices-MIN_NUM_FORMS": "0", # min number of forms
"choices-MAX_NUM_FORMS": "0", # max number of forms
"choices-0-choice": "Calexico",
"choices-0-votes": "100",
"choices-0-ORDER": "1",
"choices-0-DELETE": "",
"choices-1-choice": "Fergie",
"choices-1-votes": "900",
"choices-1-ORDER": "2",
"choices-1-DELETE": "on",
"choices-2-choice": "The Decemberists",
"choices-2-votes": "500",
"choices-2-ORDER": "0",
"choices-2-DELETE": "",
"choices-3-choice": "",
"choices-3-votes": "",
"choices-3-ORDER": "",
"choices-3-DELETE": "",
}
formset = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertTrue(formset.is_valid())
self.assertEqual(
[form.cleaned_data for form in formset.ordered_forms],
[
{
"votes": 500,
"DELETE": False,
"ORDER": 0,
"choice": "The Decemberists",
},
{"votes": 100, "DELETE": False, "ORDER": 1, "choice": "Calexico"},
],
)
self.assertEqual(
[form.cleaned_data for form in formset.deleted_forms],
[{"votes": 900, "DELETE": True, "ORDER": 2, "choice": "Fergie"}],
)
def test_invalid_deleted_form_with_ordering(self):
"""
Can get ordered_forms from a valid formset even if a deleted form
would have been invalid.
"""
FavoriteDrinkFormset = formset_factory(
form=FavoriteDrinkForm, can_delete=True, can_order=True
)
formset = FavoriteDrinkFormset(
{
"form-0-name": "",
"form-0-DELETE": "on", # no name!
"form-TOTAL_FORMS": 1,
"form-INITIAL_FORMS": 1,
"form-MIN_NUM_FORMS": 0,
"form-MAX_NUM_FORMS": 1,
}
)
self.assertTrue(formset.is_valid())
self.assertEqual(formset.ordered_forms, [])
def test_clean_hook(self):
"""
FormSets have a clean() hook for doing extra validation that isn't tied
to any form. It follows the same pattern as the clean() hook on Forms.
"""
# Start out with a some duplicate data.
data = {
"drinks-TOTAL_FORMS": "2", # the number of forms rendered
"drinks-INITIAL_FORMS": "0", # the number of forms with initial data
"drinks-MIN_NUM_FORMS": "0", # min number of forms
"drinks-MAX_NUM_FORMS": "0", # max number of forms
"drinks-0-name": "Gin and Tonic",
"drinks-1-name": "Gin and Tonic",
}
formset = FavoriteDrinksFormSet(data, prefix="drinks")
self.assertFalse(formset.is_valid())
# Any errors raised by formset.clean() are available via the
# formset.non_form_errors() method.
for error in formset.non_form_errors():
self.assertEqual(str(error), "You may only specify a drink once.")
# The valid case still works.
data["drinks-1-name"] = "Bloody Mary"
formset = FavoriteDrinksFormSet(data, prefix="drinks")
self.assertTrue(formset.is_valid())
self.assertEqual(formset.non_form_errors(), [])
def test_limiting_max_forms(self):
"""Limiting the maximum number of forms with max_num."""
# When not passed, max_num will take a high default value, leaving the
# number of forms only controlled by the value of the extra parameter.
LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3)
formset = LimitedFavoriteDrinkFormSet()
self.assertHTMLEqual(
"\n".join(str(form) for form in formset.forms),
"""<div><label for="id_form-0-name">Name:</label>
<input type="text" name="form-0-name" id="id_form-0-name"></div>
<div><label for="id_form-1-name">Name:</label>
<input type="text" name="form-1-name" id="id_form-1-name"></div>
<div><label for="id_form-2-name">Name:</label>
<input type="text" name="form-2-name" id="id_form-2-name"></div>""",
)
# If max_num is 0 then no form is rendered at all.
LimitedFavoriteDrinkFormSet = formset_factory(
FavoriteDrinkForm, extra=3, max_num=0
)
formset = LimitedFavoriteDrinkFormSet()
self.assertEqual(formset.forms, [])
def test_limited_max_forms_two(self):
LimitedFavoriteDrinkFormSet = formset_factory(
FavoriteDrinkForm, extra=5, max_num=2
)
formset = LimitedFavoriteDrinkFormSet()
self.assertHTMLEqual(
"\n".join(str(form) for form in formset.forms),
"""<div><label for="id_form-0-name">Name:</label>
<input type="text" name="form-0-name" id="id_form-0-name"></div>
<div><label for="id_form-1-name">Name:</label>
<input type="text" name="form-1-name" id="id_form-1-name"></div>""",
)
def test_limiting_extra_lest_than_max_num(self):
"""max_num has no effect when extra is less than max_num."""
LimitedFavoriteDrinkFormSet = formset_factory(
FavoriteDrinkForm, extra=1, max_num=2
)
formset = LimitedFavoriteDrinkFormSet()
self.assertHTMLEqual(
"\n".join(str(form) for form in formset.forms),
"""<div><label for="id_form-0-name">Name:</label>
<input type="text" name="form-0-name" id="id_form-0-name"></div>""",
)
def test_max_num_with_initial_data(self):
# When not passed, max_num will take a high default value, leaving the
# number of forms only controlled by the value of the initial and extra
# parameters.
LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1)
formset = LimitedFavoriteDrinkFormSet(initial=[{"name": "Fernet and Coke"}])
self.assertHTMLEqual(
"\n".join(str(form) for form in formset.forms),
"""
<div><label for="id_form-0-name">Name:</label>
<input type="text" name="form-0-name" value="Fernet and Coke"
id="id_form-0-name"></div>
<div><label for="id_form-1-name">Name:</label>
<input type="text" name="form-1-name" id="id_form-1-name"></div>
""",
)
def test_max_num_zero(self):
"""
If max_num is 0 then no form is rendered at all, regardless of extra,
unless initial data is present.
"""
LimitedFavoriteDrinkFormSet = formset_factory(
FavoriteDrinkForm, extra=1, max_num=0
)
formset = LimitedFavoriteDrinkFormSet()
self.assertEqual(formset.forms, [])
def test_max_num_zero_with_initial(self):
# initial trumps max_num
initial = [
{"name": "Fernet and Coke"},
{"name": "Bloody Mary"},
]
LimitedFavoriteDrinkFormSet = formset_factory(
FavoriteDrinkForm, extra=1, max_num=0
)
formset = LimitedFavoriteDrinkFormSet(initial=initial)
self.assertHTMLEqual(
"\n".join(str(form) for form in formset.forms),
"""
<div><label for="id_form-0-name">Name:</label>
<input id="id_form-0-name" name="form-0-name" type="text"
value="Fernet and Coke"></div>
<div><label for="id_form-1-name">Name:</label>
<input id="id_form-1-name" name="form-1-name" type="text"
value="Bloody Mary"></div>
""",
)
def test_more_initial_than_max_num(self):
"""
More initial forms than max_num results in all initial forms being
displayed (but no extra forms).
"""
initial = [
{"name": "Gin Tonic"},
{"name": "Bloody Mary"},
{"name": "Jack and Coke"},
]
LimitedFavoriteDrinkFormSet = formset_factory(
FavoriteDrinkForm, extra=1, max_num=2
)
formset = LimitedFavoriteDrinkFormSet(initial=initial)
self.assertHTMLEqual(
"\n".join(str(form) for form in formset.forms),
"""
<div><label for="id_form-0-name">Name:</label>
<input id="id_form-0-name" name="form-0-name" type="text" value="Gin Tonic">
</div>
<div><label for="id_form-1-name">Name:</label>
<input id="id_form-1-name" name="form-1-name" type="text"
value="Bloody Mary"></div>
<div><label for="id_form-2-name">Name:</label>
<input id="id_form-2-name" name="form-2-name" type="text"
value="Jack and Coke"></div>
""",
)
def test_default_absolute_max(self):
# absolute_max defaults to 2 * DEFAULT_MAX_NUM if max_num is None.
data = {
"form-TOTAL_FORMS": 2001,
"form-INITIAL_FORMS": "0",
"form-MAX_NUM_FORMS": "0",
}
formset = FavoriteDrinksFormSet(data=data)
self.assertIs(formset.is_valid(), False)
self.assertEqual(
formset.non_form_errors(),
["Please submit at most 1000 forms."],
)
self.assertEqual(formset.absolute_max, 2000)
def test_absolute_max(self):
data = {
"form-TOTAL_FORMS": "2001",
"form-INITIAL_FORMS": "0",
"form-MAX_NUM_FORMS": "0",
}
AbsoluteMaxFavoriteDrinksFormSet = formset_factory(
FavoriteDrinkForm,
absolute_max=3000,
)
formset = AbsoluteMaxFavoriteDrinksFormSet(data=data)
self.assertIs(formset.is_valid(), True)
self.assertEqual(len(formset.forms), 2001)
# absolute_max provides a hard limit.
data["form-TOTAL_FORMS"] = "3001"
formset = AbsoluteMaxFavoriteDrinksFormSet(data=data)
self.assertIs(formset.is_valid(), False)
self.assertEqual(len(formset.forms), 3000)
self.assertEqual(
formset.non_form_errors(),
["Please submit at most 1000 forms."],
)
def test_absolute_max_with_max_num(self):
data = {
"form-TOTAL_FORMS": "1001",
"form-INITIAL_FORMS": "0",
"form-MAX_NUM_FORMS": "0",
}
LimitedFavoriteDrinksFormSet = formset_factory(
FavoriteDrinkForm,
max_num=30,
absolute_max=1000,
)
formset = LimitedFavoriteDrinksFormSet(data=data)
self.assertIs(formset.is_valid(), False)
self.assertEqual(len(formset.forms), 1000)
self.assertEqual(
formset.non_form_errors(),
["Please submit at most 30 forms."],
)
def test_absolute_max_invalid(self):
msg = "'absolute_max' must be greater or equal to 'max_num'."
for max_num in [None, 31]:
with self.subTest(max_num=max_num):
with self.assertRaisesMessage(ValueError, msg):
formset_factory(FavoriteDrinkForm, max_num=max_num, absolute_max=30)
def test_more_initial_form_result_in_one(self):
"""
One form from initial and extra=3 with max_num=2 results in the one
initial form and one extra.
"""
LimitedFavoriteDrinkFormSet = formset_factory(
FavoriteDrinkForm, extra=3, max_num=2
)
formset = LimitedFavoriteDrinkFormSet(initial=[{"name": "Gin Tonic"}])
self.assertHTMLEqual(
"\n".join(str(form) for form in formset.forms),
"""
<div><label for="id_form-0-name">Name:</label>
<input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name">
</div>
<div><label for="id_form-1-name">Name:</label>
<input type="text" name="form-1-name" id="id_form-1-name"></div>""",
)
def test_management_form_field_names(self):
"""The management form class has field names matching the constants."""
self.assertCountEqual(
ManagementForm.base_fields,
[
TOTAL_FORM_COUNT,
INITIAL_FORM_COUNT,
MIN_NUM_FORM_COUNT,
MAX_NUM_FORM_COUNT,
],
)
def test_management_form_prefix(self):
"""The management form has the correct prefix."""
formset = FavoriteDrinksFormSet()
self.assertEqual(formset.management_form.prefix, "form")
data = {
"form-TOTAL_FORMS": "2",
"form-INITIAL_FORMS": "0",
"form-MIN_NUM_FORMS": "0",
"form-MAX_NUM_FORMS": "0",
}
formset = FavoriteDrinksFormSet(data=data)
self.assertEqual(formset.management_form.prefix, "form")
formset = FavoriteDrinksFormSet(initial={})
self.assertEqual(formset.management_form.prefix, "form")
def test_non_form_errors(self):
data = {
"drinks-TOTAL_FORMS": "2", # the number of forms rendered
"drinks-INITIAL_FORMS": "0", # the number of forms with initial data
"drinks-MIN_NUM_FORMS": "0", # min number of forms
"drinks-MAX_NUM_FORMS": "0", # max number of forms
"drinks-0-name": "Gin and Tonic",
"drinks-1-name": "Gin and Tonic",
}
formset = FavoriteDrinksFormSet(data, prefix="drinks")
self.assertFalse(formset.is_valid())
self.assertEqual(
formset.non_form_errors(), ["You may only specify a drink once."]
)
self.assertEqual(
str(formset.non_form_errors()),
'<ul class="errorlist nonform"><li>'
"You may only specify a drink once.</li></ul>",
)
def test_formset_iteration(self):
"""Formset instances are iterable."""
ChoiceFormset = formset_factory(Choice, extra=3)
formset = ChoiceFormset()
# An iterated formset yields formset.forms.
forms = list(formset)
self.assertEqual(forms, formset.forms)
self.assertEqual(len(formset), len(forms))
# A formset may be indexed to retrieve its forms.
self.assertEqual(formset[0], forms[0])
with self.assertRaises(IndexError):
formset[3]
# Formsets can override the default iteration order
class BaseReverseFormSet(BaseFormSet):
def __iter__(self):
return reversed(self.forms)
def __getitem__(self, idx):
return super().__getitem__(len(self) - idx - 1)
ReverseChoiceFormset = formset_factory(Choice, BaseReverseFormSet, extra=3)
reverse_formset = ReverseChoiceFormset()
# __iter__() modifies the rendering order.
# Compare forms from "reverse" formset with forms from original formset
self.assertEqual(str(reverse_formset[0]), str(forms[-1]))
self.assertEqual(str(reverse_formset[1]), str(forms[-2]))
self.assertEqual(len(reverse_formset), len(forms))
def test_formset_nonzero(self):
"""A formsets without any forms evaluates as True."""
ChoiceFormset = formset_factory(Choice, extra=0)
formset = ChoiceFormset()
self.assertEqual(len(formset.forms), 0)
self.assertTrue(formset)
def test_formset_splitdatetimefield(self):
"""
Formset works with SplitDateTimeField(initial=datetime.datetime.now).
"""
class SplitDateTimeForm(Form):
when = SplitDateTimeField(initial=datetime.datetime.now)
SplitDateTimeFormSet = formset_factory(SplitDateTimeForm)
data = {
"form-TOTAL_FORMS": "1",
"form-INITIAL_FORMS": "0",
"form-0-when_0": "1904-06-16",
"form-0-when_1": "15:51:33",
}
formset = SplitDateTimeFormSet(data)
self.assertTrue(formset.is_valid())
def test_formset_error_class(self):
"""Formset's forms use the formset's error_class."""
class CustomErrorList(ErrorList):
pass
formset = FavoriteDrinksFormSet(error_class=CustomErrorList)
self.assertEqual(formset.forms[0].error_class, CustomErrorList)
def test_formset_calls_forms_is_valid(self):
"""Formsets call is_valid() on each form."""
class AnotherChoice(Choice):
def is_valid(self):
self.is_valid_called = True
return super().is_valid()
AnotherChoiceFormSet = formset_factory(AnotherChoice)
data = {
"choices-TOTAL_FORMS": "1", # number of forms rendered
"choices-INITIAL_FORMS": "0", # number of forms with initial data
"choices-MIN_NUM_FORMS": "0", # min number of forms
"choices-MAX_NUM_FORMS": "0", # max number of forms
"choices-0-choice": "Calexico",
"choices-0-votes": "100",
}
formset = AnotherChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertTrue(formset.is_valid())
self.assertTrue(all(form.is_valid_called for form in formset.forms))
def test_hard_limit_on_instantiated_forms(self):
"""A formset has a hard limit on the number of forms instantiated."""
# reduce the default limit of 1000 temporarily for testing
_old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM
try:
formsets.DEFAULT_MAX_NUM = 2
ChoiceFormSet = formset_factory(Choice, max_num=1)
# someone fiddles with the mgmt form data...
formset = ChoiceFormSet(
{
"choices-TOTAL_FORMS": "4",
"choices-INITIAL_FORMS": "0",
"choices-MIN_NUM_FORMS": "0", # min number of forms
"choices-MAX_NUM_FORMS": "4",
"choices-0-choice": "Zero",
"choices-0-votes": "0",
"choices-1-choice": "One",
"choices-1-votes": "1",
"choices-2-choice": "Two",
"choices-2-votes": "2",
"choices-3-choice": "Three",
"choices-3-votes": "3",
},
prefix="choices",
)
# But we still only instantiate 3 forms
self.assertEqual(len(formset.forms), 3)
# and the formset isn't valid
self.assertFalse(formset.is_valid())
finally:
formsets.DEFAULT_MAX_NUM = _old_DEFAULT_MAX_NUM
def test_increase_hard_limit(self):
"""Can increase the built-in forms limit via a higher max_num."""
# reduce the default limit of 1000 temporarily for testing
_old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM
try:
formsets.DEFAULT_MAX_NUM = 3
# for this form, we want a limit of 4
ChoiceFormSet = formset_factory(Choice, max_num=4)
formset = ChoiceFormSet(
{
"choices-TOTAL_FORMS": "4",
"choices-INITIAL_FORMS": "0",
"choices-MIN_NUM_FORMS": "0", # min number of forms
"choices-MAX_NUM_FORMS": "4",
"choices-0-choice": "Zero",
"choices-0-votes": "0",
"choices-1-choice": "One",
"choices-1-votes": "1",
"choices-2-choice": "Two",
"choices-2-votes": "2",
"choices-3-choice": "Three",
"choices-3-votes": "3",
},
prefix="choices",
)
# Four forms are instantiated and no exception is raised
self.assertEqual(len(formset.forms), 4)
finally:
formsets.DEFAULT_MAX_NUM = _old_DEFAULT_MAX_NUM
def test_non_form_errors_run_full_clean(self):
"""
If non_form_errors() is called without calling is_valid() first,
it should ensure that full_clean() is called.
"""
class BaseCustomFormSet(BaseFormSet):
def clean(self):
raise ValidationError("This is a non-form error")
ChoiceFormSet = formset_factory(Choice, formset=BaseCustomFormSet)
data = {
"choices-TOTAL_FORMS": "1",
"choices-INITIAL_FORMS": "0",
}
formset = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertIsInstance(formset.non_form_errors(), ErrorList)
self.assertEqual(list(formset.non_form_errors()), ["This is a non-form error"])
def test_validate_max_ignores_forms_marked_for_deletion(self):
class CheckForm(Form):
field = IntegerField()
data = {
"check-TOTAL_FORMS": "2",
"check-INITIAL_FORMS": "0",
"check-MAX_NUM_FORMS": "1",
"check-0-field": "200",
"check-0-DELETE": "",
"check-1-field": "50",
"check-1-DELETE": "on",
}
CheckFormSet = formset_factory(
CheckForm, max_num=1, validate_max=True, can_delete=True
)
formset = CheckFormSet(data, prefix="check")
self.assertTrue(formset.is_valid())
def test_formset_total_error_count(self):
"""A valid formset should have 0 total errors."""
data = [ # formset_data, expected error count
([("Calexico", "100")], 0),
([("Calexico", "")], 1),
([("", "invalid")], 2),
([("Calexico", "100"), ("Calexico", "")], 1),
([("Calexico", ""), ("Calexico", "")], 2),
]
for formset_data, expected_error_count in data:
formset = self.make_choiceformset(formset_data)
self.assertEqual(formset.total_error_count(), expected_error_count)
def test_formset_total_error_count_with_non_form_errors(self):
data = {
"choices-TOTAL_FORMS": "2", # the number of forms rendered
"choices-INITIAL_FORMS": "0", # the number of forms with initial data
"choices-MAX_NUM_FORMS": "2", # max number of forms - should be ignored
"choices-0-choice": "Zero",
"choices-0-votes": "0",
"choices-1-choice": "One",
"choices-1-votes": "1",
}
ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True)
formset = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertEqual(formset.total_error_count(), 1)
data["choices-1-votes"] = ""
formset = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertEqual(formset.total_error_count(), 2)
def test_html_safe(self):
formset = self.make_choiceformset()
self.assertTrue(hasattr(formset, "__html__"))
self.assertEqual(str(formset), formset.__html__())
def test_can_delete_extra_formset_forms(self):
ChoiceFormFormset = formset_factory(form=Choice, can_delete=True, extra=2)
formset = ChoiceFormFormset()
self.assertEqual(len(formset), 2)
self.assertIn("DELETE", formset.forms[0].fields)
self.assertIn("DELETE", formset.forms[1].fields)
def test_disable_delete_extra_formset_forms(self):
ChoiceFormFormset = formset_factory(
form=Choice,
can_delete=True,
can_delete_extra=False,
extra=2,
)
formset = ChoiceFormFormset()
self.assertEqual(len(formset), 2)
self.assertNotIn("DELETE", formset.forms[0].fields)
self.assertNotIn("DELETE", formset.forms[1].fields)
formset = ChoiceFormFormset(initial=[{"choice": "Zero", "votes": "1"}])
self.assertEqual(len(formset), 3)
self.assertIn("DELETE", formset.forms[0].fields)
self.assertNotIn("DELETE", formset.forms[1].fields)
self.assertNotIn("DELETE", formset.forms[2].fields)
formset = ChoiceFormFormset(
data={
"form-0-choice": "Zero",
"form-0-votes": "0",
"form-0-DELETE": "on",
"form-1-choice": "One",
"form-1-votes": "1",
"form-2-choice": "",
"form-2-votes": "",
"form-TOTAL_FORMS": "3",
"form-INITIAL_FORMS": "1",
},
initial=[{"choice": "Zero", "votes": "1"}],
)
self.assertEqual(
formset.cleaned_data,
[
{"choice": "Zero", "votes": 0, "DELETE": True},
{"choice": "One", "votes": 1},
{},
],
)
self.assertIs(formset._should_delete_form(formset.forms[0]), True)
self.assertIs(formset._should_delete_form(formset.forms[1]), False)
self.assertIs(formset._should_delete_form(formset.forms[2]), False)
def test_template_name_uses_renderer_value(self):
class CustomRenderer(TemplatesSetting):
formset_template_name = "a/custom/formset/template.html"
ChoiceFormSet = formset_factory(Choice, renderer=CustomRenderer)
self.assertEqual(
ChoiceFormSet().template_name, "a/custom/formset/template.html"
)
def test_template_name_can_be_overridden(self):
class CustomFormSet(BaseFormSet):
template_name = "a/custom/formset/template.html"
ChoiceFormSet = formset_factory(Choice, formset=CustomFormSet)
self.assertEqual(
ChoiceFormSet().template_name, "a/custom/formset/template.html"
)
def test_custom_renderer(self):
"""
A custom renderer passed to a formset_factory() is passed to all forms
and ErrorList.
"""
from django.forms.renderers import Jinja2
renderer = Jinja2()
data = {
"choices-TOTAL_FORMS": "2",
"choices-INITIAL_FORMS": "0",
"choices-MIN_NUM_FORMS": "0",
"choices-0-choice": "Zero",
"choices-0-votes": "",
"choices-1-choice": "One",
"choices-1-votes": "",
}
ChoiceFormSet = formset_factory(Choice, renderer=renderer)
formset = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertEqual(formset.renderer, renderer)
self.assertEqual(formset.forms[0].renderer, renderer)
self.assertEqual(formset.management_form.renderer, renderer)
self.assertEqual(formset.non_form_errors().renderer, renderer)
self.assertEqual(formset.empty_form.renderer, renderer)
def test_repr(self):
valid_formset = self.make_choiceformset([("test", 1)])
valid_formset.full_clean()
invalid_formset = self.make_choiceformset([("test", "")])
invalid_formset.full_clean()
partially_invalid_formset = self.make_choiceformset(
[("test", "1"), ("test", "")],
)
partially_invalid_formset.full_clean()
invalid_formset_non_form_errors_only = self.make_choiceformset(
[("test", "")],
formset_class=ChoiceFormsetWithNonFormError,
)
invalid_formset_non_form_errors_only.full_clean()
cases = [
(
self.make_choiceformset(),
"<ChoiceFormSet: bound=False valid=Unknown total_forms=1>",
),
(
self.make_choiceformset(
formset_class=formset_factory(Choice, extra=10),
),
"<ChoiceFormSet: bound=False valid=Unknown total_forms=10>",
),
(
self.make_choiceformset([]),
"<ChoiceFormSet: bound=True valid=Unknown total_forms=0>",
),
(
self.make_choiceformset([("test", 1)]),
"<ChoiceFormSet: bound=True valid=Unknown total_forms=1>",
),
(valid_formset, "<ChoiceFormSet: bound=True valid=True total_forms=1>"),
(invalid_formset, "<ChoiceFormSet: bound=True valid=False total_forms=1>"),
(
partially_invalid_formset,
"<ChoiceFormSet: bound=True valid=False total_forms=2>",
),
(
invalid_formset_non_form_errors_only,
"<ChoiceFormsetWithNonFormError: bound=True valid=False total_forms=1>",
),
]
for formset, expected_repr in cases:
with self.subTest(expected_repr=expected_repr):
self.assertEqual(repr(formset), expected_repr)
def test_repr_do_not_trigger_validation(self):
formset = self.make_choiceformset([("test", 1)])
with mock.patch.object(formset, "full_clean") as mocked_full_clean:
repr(formset)
mocked_full_clean.assert_not_called()
formset.is_valid()
mocked_full_clean.assert_called()
@jinja2_tests
class Jinja2FormsFormsetTestCase(FormsFormsetTestCase):
pass
class FormsetAsTagTests(SimpleTestCase):
def setUp(self):
data = {
"choices-TOTAL_FORMS": "1",
"choices-INITIAL_FORMS": "0",
"choices-MIN_NUM_FORMS": "0",
"choices-MAX_NUM_FORMS": "0",
"choices-0-choice": "Calexico",
"choices-0-votes": "100",
}
self.formset = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.management_form_html = (
'<input type="hidden" name="choices-TOTAL_FORMS" value="1">'
'<input type="hidden" name="choices-INITIAL_FORMS" value="0">'
'<input type="hidden" name="choices-MIN_NUM_FORMS" value="0">'
'<input type="hidden" name="choices-MAX_NUM_FORMS" value="0">'
)
def test_as_table(self):
self.assertHTMLEqual(
self.formset.as_table(),
self.management_form_html
+ (
"<tr><th>Choice:</th><td>"
'<input type="text" name="choices-0-choice" value="Calexico"></td></tr>'
"<tr><th>Votes:</th><td>"
'<input type="number" name="choices-0-votes" value="100"></td></tr>'
),
)
def test_as_p(self):
self.assertHTMLEqual(
self.formset.as_p(),
self.management_form_html
+ (
"<p>Choice: "
'<input type="text" name="choices-0-choice" value="Calexico"></p>'
'<p>Votes: <input type="number" name="choices-0-votes" value="100"></p>'
),
)
def test_as_ul(self):
self.assertHTMLEqual(
self.formset.as_ul(),
self.management_form_html
+ (
"<li>Choice: "
'<input type="text" name="choices-0-choice" value="Calexico"></li>'
"<li>Votes: "
'<input type="number" name="choices-0-votes" value="100"></li>'
),
)
def test_as_div(self):
self.assertHTMLEqual(
self.formset.as_div(),
self.management_form_html
+ (
"<div>Choice: "
'<input type="text" name="choices-0-choice" value="Calexico"></div>'
'<div>Votes: <input type="number" name="choices-0-votes" value="100">'
"</div>"
),
)
@jinja2_tests
class Jinja2FormsetAsTagTests(FormsetAsTagTests):
pass
class ArticleForm(Form):
title = CharField()
pub_date = DateField()
ArticleFormSet = formset_factory(ArticleForm)
class TestIsBoundBehavior(SimpleTestCase):
def test_no_data_error(self):
formset = ArticleFormSet({})
self.assertIs(formset.is_valid(), False)
self.assertEqual(
formset.non_form_errors(),
[
"ManagementForm data is missing or has been tampered with. "
"Missing fields: form-TOTAL_FORMS, form-INITIAL_FORMS. "
"You may need to file a bug report if the issue persists.",
],
)
self.assertEqual(formset.errors, [])
# Can still render the formset.
self.assertHTMLEqual(
str(formset),
'<ul class="errorlist nonfield">'
"<li>(Hidden field TOTAL_FORMS) This field is required.</li>"
"<li>(Hidden field INITIAL_FORMS) This field is required.</li>"
"</ul>"
"<div>"
'<input type="hidden" name="form-TOTAL_FORMS" id="id_form-TOTAL_FORMS">'
'<input type="hidden" name="form-INITIAL_FORMS" id="id_form-INITIAL_FORMS">'
'<input type="hidden" name="form-MIN_NUM_FORMS" id="id_form-MIN_NUM_FORMS">'
'<input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS">'
"</div>\n",
)
def test_management_form_invalid_data(self):
data = {
"form-TOTAL_FORMS": "two",
"form-INITIAL_FORMS": "one",
}
formset = ArticleFormSet(data)
self.assertIs(formset.is_valid(), False)
self.assertEqual(
formset.non_form_errors(),
[
"ManagementForm data is missing or has been tampered with. "
"Missing fields: form-TOTAL_FORMS, form-INITIAL_FORMS. "
"You may need to file a bug report if the issue persists.",
],
)
self.assertEqual(formset.errors, [])
# Can still render the formset.
self.assertHTMLEqual(
str(formset),
'<ul class="errorlist nonfield">'
"<li>(Hidden field TOTAL_FORMS) Enter a whole number.</li>"
"<li>(Hidden field INITIAL_FORMS) Enter a whole number.</li>"
"</ul>"
"<div>"
'<input type="hidden" name="form-TOTAL_FORMS" value="two" '
'id="id_form-TOTAL_FORMS">'
'<input type="hidden" name="form-INITIAL_FORMS" value="one" '
'id="id_form-INITIAL_FORMS">'
'<input type="hidden" name="form-MIN_NUM_FORMS" id="id_form-MIN_NUM_FORMS">'
'<input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS">'
"</div>\n",
)
def test_customize_management_form_error(self):
formset = ArticleFormSet(
{}, error_messages={"missing_management_form": "customized"}
)
self.assertIs(formset.is_valid(), False)
self.assertEqual(formset.non_form_errors(), ["customized"])
self.assertEqual(formset.errors, [])
def test_with_management_data_attrs_work_fine(self):
data = {
"form-TOTAL_FORMS": "1",
"form-INITIAL_FORMS": "0",
}
formset = ArticleFormSet(data)
self.assertEqual(0, formset.initial_form_count())
self.assertEqual(1, formset.total_form_count())
self.assertTrue(formset.is_bound)
self.assertTrue(formset.forms[0].is_bound)
self.assertTrue(formset.is_valid())
self.assertTrue(formset.forms[0].is_valid())
self.assertEqual([{}], formset.cleaned_data)
def test_form_errors_are_caught_by_formset(self):
data = {
"form-TOTAL_FORMS": "2",
"form-INITIAL_FORMS": "0",
"form-0-title": "Test",
"form-0-pub_date": "1904-06-16",
"form-1-title": "Test",
"form-1-pub_date": "", # <-- this date is missing but required
}
formset = ArticleFormSet(data)
self.assertFalse(formset.is_valid())
self.assertEqual(
[{}, {"pub_date": ["This field is required."]}], formset.errors
)
def test_empty_forms_are_unbound(self):
data = {
"form-TOTAL_FORMS": "1",
"form-INITIAL_FORMS": "0",
"form-0-title": "Test",
"form-0-pub_date": "1904-06-16",
}
unbound_formset = ArticleFormSet()
bound_formset = ArticleFormSet(data)
empty_forms = [unbound_formset.empty_form, bound_formset.empty_form]
# Empty forms should be unbound
self.assertFalse(empty_forms[0].is_bound)
self.assertFalse(empty_forms[1].is_bound)
# The empty forms should be equal.
self.assertHTMLEqual(empty_forms[0].as_p(), empty_forms[1].as_p())
@jinja2_tests
class TestIsBoundBehavior(TestIsBoundBehavior):
pass
class TestEmptyFormSet(SimpleTestCase):
def test_empty_formset_is_valid(self):
"""An empty formset still calls clean()"""
class EmptyFsetWontValidate(BaseFormSet):
def clean(self):
raise ValidationError("Clean method called")
EmptyFsetWontValidateFormset = formset_factory(
FavoriteDrinkForm, extra=0, formset=EmptyFsetWontValidate
)
formset = EmptyFsetWontValidateFormset(
data={"form-INITIAL_FORMS": "0", "form-TOTAL_FORMS": "0"},
prefix="form",
)
formset2 = EmptyFsetWontValidateFormset(
data={
"form-INITIAL_FORMS": "0",
"form-TOTAL_FORMS": "1",
"form-0-name": "bah",
},
prefix="form",
)
self.assertFalse(formset.is_valid())
self.assertFalse(formset2.is_valid())
def test_empty_formset_media(self):
"""Media is available on empty formset."""
class MediaForm(Form):
class Media:
js = ("some-file.js",)
self.assertIn("some-file.js", str(formset_factory(MediaForm, extra=0)().media))
def test_empty_formset_is_multipart(self):
"""is_multipart() works with an empty formset."""
class FileForm(Form):
file = FileField()
self.assertTrue(formset_factory(FileForm, extra=0)().is_multipart())
class AllValidTests(SimpleTestCase):
def test_valid(self):
data = {
"choices-TOTAL_FORMS": "2",
"choices-INITIAL_FORMS": "0",
"choices-MIN_NUM_FORMS": "0",
"choices-0-choice": "Zero",
"choices-0-votes": "0",
"choices-1-choice": "One",
"choices-1-votes": "1",
}
ChoiceFormSet = formset_factory(Choice)
formset1 = ChoiceFormSet(data, auto_id=False, prefix="choices")
formset2 = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertIs(all_valid((formset1, formset2)), True)
expected_errors = [{}, {}]
self.assertEqual(formset1._errors, expected_errors)
self.assertEqual(formset2._errors, expected_errors)
def test_invalid(self):
"""all_valid() validates all forms, even when some are invalid."""
data = {
"choices-TOTAL_FORMS": "2",
"choices-INITIAL_FORMS": "0",
"choices-MIN_NUM_FORMS": "0",
"choices-0-choice": "Zero",
"choices-0-votes": "",
"choices-1-choice": "One",
"choices-1-votes": "",
}
ChoiceFormSet = formset_factory(Choice)
formset1 = ChoiceFormSet(data, auto_id=False, prefix="choices")
formset2 = ChoiceFormSet(data, auto_id=False, prefix="choices")
self.assertIs(all_valid((formset1, formset2)), False)
expected_errors = [
{"votes": ["This field is required."]},
{"votes": ["This field is required."]},
]
self.assertEqual(formset1._errors, expected_errors)
self.assertEqual(formset2._errors, expected_errors)
class DeprecationTests(SimpleTestCase):
def test_warning(self):
from django.forms.utils import DEFAULT_TEMPLATE_DEPRECATION_MSG
with isolate_lru_cache(get_default_renderer), self.settings(
FORM_RENDERER="django.forms.renderers.DjangoTemplates"
), self.assertRaisesMessage(
RemovedInDjango50Warning, DEFAULT_TEMPLATE_DEPRECATION_MSG
):
ChoiceFormSet = formset_factory(Choice)
formset = ChoiceFormSet()
str(formset)
def test_no_management_form_warning(self):
"""
Management forms are already rendered with the new div template.
"""
with isolate_lru_cache(get_default_renderer), self.settings(
FORM_RENDERER="django.forms.renderers.DjangoTemplates"
):
ChoiceFormSet = formset_factory(Choice, formset=BaseFormSet)
formset = ChoiceFormSet()
str(formset.management_form)
|
7a31cd1c1d123d93054663e92e0498c5febc0d4d5013422bddf75145ac80d9f3 | import copy
import datetime
import json
import uuid
from django.core.exceptions import NON_FIELD_ERRORS
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.validators import MaxValueValidator, RegexValidator
from django.forms import (
BooleanField,
CharField,
CheckboxSelectMultiple,
ChoiceField,
DateField,
DateTimeField,
EmailField,
FileField,
FileInput,
FloatField,
Form,
HiddenInput,
ImageField,
IntegerField,
MultipleChoiceField,
MultipleHiddenInput,
MultiValueField,
MultiWidget,
NullBooleanField,
PasswordInput,
RadioSelect,
Select,
SplitDateTimeField,
SplitHiddenDateTimeWidget,
Textarea,
TextInput,
TimeField,
ValidationError,
forms,
)
from django.forms.renderers import DjangoTemplates, get_default_renderer
from django.forms.utils import ErrorList
from django.http import QueryDict
from django.template import Context, Template
from django.test import SimpleTestCase
from django.test.utils import isolate_lru_cache, override_settings
from django.utils.datastructures import MultiValueDict
from django.utils.deprecation import RemovedInDjango50Warning
from django.utils.safestring import mark_safe
from . import jinja2_tests
class FrameworkForm(Form):
name = CharField()
language = ChoiceField(choices=[("P", "Python"), ("J", "Java")], widget=RadioSelect)
class Person(Form):
first_name = CharField()
last_name = CharField()
birthday = DateField()
class PersonNew(Form):
first_name = CharField(widget=TextInput(attrs={"id": "first_name_id"}))
last_name = CharField()
birthday = DateField()
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[("J", "John Lennon"), ("P", "Paul McCartney")],
widget=CheckboxSelectMultiple,
)
class MultiValueDictLike(dict):
def getlist(self, key):
return [self[key]]
class FormsTestCase(SimpleTestCase):
# A Form is a collection of Fields. It knows how to validate a set of data and it
# knows how to render itself in a couple of default ways (e.g., an HTML table).
# You can pass it data in __init__(), as a dictionary.
def test_form(self):
# Pass a dictionary to a Form's __init__().
p = Person(
{"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"}
)
self.assertTrue(p.is_bound)
self.assertEqual(p.errors, {})
self.assertIsInstance(p.errors, dict)
self.assertTrue(p.is_valid())
self.assertHTMLEqual(p.errors.as_ul(), "")
self.assertEqual(p.errors.as_text(), "")
self.assertEqual(p.cleaned_data["first_name"], "John")
self.assertEqual(p.cleaned_data["last_name"], "Lennon")
self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
self.assertHTMLEqual(
str(p["first_name"]),
'<input type="text" name="first_name" value="John" id="id_first_name" '
"required>",
)
self.assertHTMLEqual(
str(p["last_name"]),
'<input type="text" name="last_name" value="Lennon" id="id_last_name" '
"required>",
)
self.assertHTMLEqual(
str(p["birthday"]),
'<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
"required>",
)
msg = (
"Key 'nonexistentfield' not found in 'Person'. Choices are: birthday, "
"first_name, last_name."
)
with self.assertRaisesMessage(KeyError, msg):
p["nonexistentfield"]
form_output = []
for boundfield in p:
form_output.append(str(boundfield))
self.assertHTMLEqual(
"\n".join(form_output),
'<input type="text" name="first_name" value="John" id="id_first_name" '
"required>"
'<input type="text" name="last_name" value="Lennon" id="id_last_name" '
"required>"
'<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
"required>",
)
form_output = []
for boundfield in p:
form_output.append([boundfield.label, boundfield.data])
self.assertEqual(
form_output,
[
["First name", "John"],
["Last name", "Lennon"],
["Birthday", "1940-10-9"],
],
)
self.assertHTMLEqual(
str(p),
'<div><label for="id_first_name">First name:</label><input type="text" '
'name="first_name" value="John" required id="id_first_name"></div><div>'
'<label for="id_last_name">Last name:</label><input type="text" '
'name="last_name" value="Lennon" required id="id_last_name"></div><div>'
'<label for="id_birthday">Birthday:</label><input type="text" '
'name="birthday" value="1940-10-9" required id="id_birthday"></div>',
)
self.assertHTMLEqual(
p.as_div(),
'<div><label for="id_first_name">First name:</label><input type="text" '
'name="first_name" value="John" required id="id_first_name"></div><div>'
'<label for="id_last_name">Last name:</label><input type="text" '
'name="last_name" value="Lennon" required id="id_last_name"></div><div>'
'<label for="id_birthday">Birthday:</label><input type="text" '
'name="birthday" value="1940-10-9" required id="id_birthday"></div>',
)
def test_empty_dict(self):
# Empty dictionaries are valid, too.
p = Person({})
self.assertTrue(p.is_bound)
self.assertEqual(p.errors["first_name"], ["This field is required."])
self.assertEqual(p.errors["last_name"], ["This field is required."])
self.assertEqual(p.errors["birthday"], ["This field is required."])
self.assertFalse(p.is_valid())
self.assertEqual(p.cleaned_data, {})
self.assertHTMLEqual(
str(p),
'<div><label for="id_first_name">First name:</label>'
'<ul class="errorlist"><li>This field is required.</li></ul>'
'<input type="text" name="first_name" required id="id_first_name"></div>'
'<div><label for="id_last_name">Last name:</label>'
'<ul class="errorlist"><li>This field is required.</li></ul>'
'<input type="text" name="last_name" required id="id_last_name"></div><div>'
'<label for="id_birthday">Birthday:</label>'
'<ul class="errorlist"><li>This field is required.</li></ul>'
'<input type="text" name="birthday" required id="id_birthday"></div>',
)
self.assertHTMLEqual(
p.as_table(),
"""<tr><th><label for="id_first_name">First name:</label></th><td>
<ul class="errorlist"><li>This field is required.</li></ul>
<input type="text" name="first_name" id="id_first_name" required></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th>
<td><ul class="errorlist"><li>This field is required.</li></ul>
<input type="text" name="last_name" id="id_last_name" required></td></tr>
<tr><th><label for="id_birthday">Birthday:</label></th>
<td><ul class="errorlist"><li>This field is required.</li></ul>
<input type="text" name="birthday" id="id_birthday" required></td></tr>""",
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
<label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
<label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
<label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" required></li>""",
)
self.assertHTMLEqual(
p.as_p(),
"""<ul class="errorlist"><li>This field is required.</li></ul>
<p><label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" required></p>
<ul class="errorlist"><li>This field is required.</li></ul>
<p><label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" required></p>
<ul class="errorlist"><li>This field is required.</li></ul>
<p><label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" required></p>""",
)
self.assertHTMLEqual(
p.as_div(),
'<div><label for="id_first_name">First name:</label>'
'<ul class="errorlist"><li>This field is required.</li></ul>'
'<input type="text" name="first_name" required id="id_first_name"></div>'
'<div><label for="id_last_name">Last name:</label>'
'<ul class="errorlist"><li>This field is required.</li></ul>'
'<input type="text" name="last_name" required id="id_last_name"></div><div>'
'<label for="id_birthday">Birthday:</label>'
'<ul class="errorlist"><li>This field is required.</li></ul>'
'<input type="text" name="birthday" required id="id_birthday"></div>',
)
def test_empty_querydict_args(self):
data = QueryDict()
files = QueryDict()
p = Person(data, files)
self.assertIs(p.data, data)
self.assertIs(p.files, files)
def test_unbound_form(self):
# If you don't pass any values to the Form's __init__(), or if you pass None,
# the Form will be considered unbound and won't do any validation. Form.errors
# will be an empty dictionary *but* Form.is_valid() will return False.
p = Person()
self.assertFalse(p.is_bound)
self.assertEqual(p.errors, {})
self.assertFalse(p.is_valid())
with self.assertRaises(AttributeError):
p.cleaned_data
self.assertHTMLEqual(
str(p),
'<div><label for="id_first_name">First name:</label><input type="text" '
'name="first_name" id="id_first_name" required></div><div><label '
'for="id_last_name">Last name:</label><input type="text" name="last_name" '
'id="id_last_name" required></div><div><label for="id_birthday">'
'Birthday:</label><input type="text" name="birthday" id="id_birthday" '
"required></div>",
)
self.assertHTMLEqual(
p.as_table(),
"""<tr><th><label for="id_first_name">First name:</label></th><td>
<input type="text" name="first_name" id="id_first_name" required></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th><td>
<input type="text" name="last_name" id="id_last_name" required></td></tr>
<tr><th><label for="id_birthday">Birthday:</label></th><td>
<input type="text" name="birthday" id="id_birthday" required></td></tr>""",
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" required></li>
<li><label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" required></li>
<li><label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" required></li>""",
)
self.assertHTMLEqual(
p.as_p(),
"""<p><label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" required></p>
<p><label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" required></p>
<p><label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" required></p>""",
)
self.assertHTMLEqual(
p.as_div(),
'<div><label for="id_first_name">First name:</label><input type="text" '
'name="first_name" id="id_first_name" required></div><div><label '
'for="id_last_name">Last name:</label><input type="text" name="last_name" '
'id="id_last_name" required></div><div><label for="id_birthday">'
'Birthday:</label><input type="text" name="birthday" id="id_birthday" '
"required></div>",
)
def test_unicode_values(self):
# Unicode values are handled properly.
p = Person(
{
"first_name": "John",
"last_name": "\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111",
"birthday": "1940-10-9",
}
)
self.assertHTMLEqual(
p.as_table(),
'<tr><th><label for="id_first_name">First name:</label></th><td>'
'<input type="text" name="first_name" value="John" id="id_first_name" '
"required></td></tr>\n"
'<tr><th><label for="id_last_name">Last name:</label>'
'</th><td><input type="text" name="last_name" '
'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111"'
'id="id_last_name" required></td></tr>\n'
'<tr><th><label for="id_birthday">Birthday:</label></th><td>'
'<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
"required></td></tr>",
)
self.assertHTMLEqual(
p.as_ul(),
'<li><label for="id_first_name">First name:</label> '
'<input type="text" name="first_name" value="John" id="id_first_name" '
"required></li>\n"
'<li><label for="id_last_name">Last name:</label> '
'<input type="text" name="last_name" '
'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" '
'id="id_last_name" required></li>\n'
'<li><label for="id_birthday">Birthday:</label> '
'<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
"required></li>",
)
self.assertHTMLEqual(
p.as_p(),
'<p><label for="id_first_name">First name:</label> '
'<input type="text" name="first_name" value="John" id="id_first_name" '
"required></p>\n"
'<p><label for="id_last_name">Last name:</label> '
'<input type="text" name="last_name" '
'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" '
'id="id_last_name" required></p>\n'
'<p><label for="id_birthday">Birthday:</label> '
'<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
"required></p>",
)
self.assertHTMLEqual(
p.as_div(),
'<div><label for="id_first_name">First name:</label>'
'<input type="text" name="first_name" value="John" id="id_first_name" '
'required></div><div><label for="id_last_name">Last name:</label>'
'<input type="text" name="last_name"'
'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" '
'id="id_last_name" required></div><div><label for="id_birthday">'
'Birthday:</label><input type="text" name="birthday" value="1940-10-9" '
'id="id_birthday" required></div>',
)
p = Person({"last_name": "Lennon"})
self.assertEqual(p.errors["first_name"], ["This field is required."])
self.assertEqual(p.errors["birthday"], ["This field is required."])
self.assertFalse(p.is_valid())
self.assertEqual(
p.errors,
{
"birthday": ["This field is required."],
"first_name": ["This field is required."],
},
)
self.assertEqual(p.cleaned_data, {"last_name": "Lennon"})
self.assertEqual(p["first_name"].errors, ["This field is required."])
self.assertHTMLEqual(
p["first_name"].errors.as_ul(),
'<ul class="errorlist"><li>This field is required.</li></ul>',
)
self.assertEqual(p["first_name"].errors.as_text(), "* This field is required.")
p = Person()
self.assertHTMLEqual(
str(p["first_name"]),
'<input type="text" name="first_name" id="id_first_name" required>',
)
self.assertHTMLEqual(
str(p["last_name"]),
'<input type="text" name="last_name" id="id_last_name" required>',
)
self.assertHTMLEqual(
str(p["birthday"]),
'<input type="text" name="birthday" id="id_birthday" required>',
)
def test_cleaned_data_only_fields(self):
# cleaned_data will always *only* contain a key for fields defined in the
# Form, even if you pass extra data when you define the Form. In this
# example, we pass a bunch of extra fields to the form constructor,
# but cleaned_data contains only the form's fields.
data = {
"first_name": "John",
"last_name": "Lennon",
"birthday": "1940-10-9",
"extra1": "hello",
"extra2": "hello",
}
p = Person(data)
self.assertTrue(p.is_valid())
self.assertEqual(p.cleaned_data["first_name"], "John")
self.assertEqual(p.cleaned_data["last_name"], "Lennon")
self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
def test_optional_data(self):
# cleaned_data will include a key and value for *all* fields defined in
# the Form, even if the Form's data didn't include a value for fields
# that are not required. In this example, the data dictionary doesn't
# include a value for the "nick_name" field, but cleaned_data includes
# it. For CharFields, it's set to the empty string.
class OptionalPersonForm(Form):
first_name = CharField()
last_name = CharField()
nick_name = CharField(required=False)
data = {"first_name": "John", "last_name": "Lennon"}
f = OptionalPersonForm(data)
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data["nick_name"], "")
self.assertEqual(f.cleaned_data["first_name"], "John")
self.assertEqual(f.cleaned_data["last_name"], "Lennon")
# For DateFields, it's set to None.
class OptionalPersonForm(Form):
first_name = CharField()
last_name = CharField()
birth_date = DateField(required=False)
data = {"first_name": "John", "last_name": "Lennon"}
f = OptionalPersonForm(data)
self.assertTrue(f.is_valid())
self.assertIsNone(f.cleaned_data["birth_date"])
self.assertEqual(f.cleaned_data["first_name"], "John")
self.assertEqual(f.cleaned_data["last_name"], "Lennon")
def test_auto_id(self):
# "auto_id" tells the Form to add an "id" attribute to each form
# element. If it's a string that contains '%s', Django will use that as
# a format string into which the field's name will be inserted. It will
# also put a <label> around the human-readable labels for a field.
p = Person(auto_id="%s_id")
self.assertHTMLEqual(
p.as_table(),
"""<tr><th><label for="first_name_id">First name:</label></th><td>
<input type="text" name="first_name" id="first_name_id" required></td></tr>
<tr><th><label for="last_name_id">Last name:</label></th><td>
<input type="text" name="last_name" id="last_name_id" required></td></tr>
<tr><th><label for="birthday_id">Birthday:</label></th><td>
<input type="text" name="birthday" id="birthday_id" required></td></tr>""",
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="first_name_id">First name:</label>
<input type="text" name="first_name" id="first_name_id" required></li>
<li><label for="last_name_id">Last name:</label>
<input type="text" name="last_name" id="last_name_id" required></li>
<li><label for="birthday_id">Birthday:</label>
<input type="text" name="birthday" id="birthday_id" required></li>""",
)
self.assertHTMLEqual(
p.as_p(),
"""<p><label for="first_name_id">First name:</label>
<input type="text" name="first_name" id="first_name_id" required></p>
<p><label for="last_name_id">Last name:</label>
<input type="text" name="last_name" id="last_name_id" required></p>
<p><label for="birthday_id">Birthday:</label>
<input type="text" name="birthday" id="birthday_id" required></p>""",
)
self.assertHTMLEqual(
p.as_div(),
'<div><label for="first_name_id">First name:</label><input type="text" '
'name="first_name" id="first_name_id" required></div><div><label '
'for="last_name_id">Last name:</label><input type="text" '
'name="last_name" id="last_name_id" required></div><div><label '
'for="birthday_id">Birthday:</label><input type="text" name="birthday" '
'id="birthday_id" required></div>',
)
def test_auto_id_true(self):
# If auto_id is any True value whose str() does not contain '%s', the "id"
# attribute will be the name of the field.
p = Person(auto_id=True)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="first_name">First name:</label>
<input type="text" name="first_name" id="first_name" required></li>
<li><label for="last_name">Last name:</label>
<input type="text" name="last_name" id="last_name" required></li>
<li><label for="birthday">Birthday:</label>
<input type="text" name="birthday" id="birthday" required></li>""",
)
def test_auto_id_false(self):
# If auto_id is any False value, an "id" attribute won't be output unless it
# was manually entered.
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>First name: <input type="text" name="first_name" required></li>
<li>Last name: <input type="text" name="last_name" required></li>
<li>Birthday: <input type="text" name="birthday" required></li>""",
)
def test_id_on_field(self):
# In this example, auto_id is False, but the "id" attribute for the "first_name"
# field is given. Also note that field gets a <label>, while the others don't.
p = PersonNew(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="first_name_id">First name:</label>
<input type="text" id="first_name_id" name="first_name" required></li>
<li>Last name: <input type="text" name="last_name" required></li>
<li>Birthday: <input type="text" name="birthday" required></li>""",
)
def test_auto_id_on_form_and_field(self):
# If the "id" attribute is specified in the Form and auto_id is True, the "id"
# attribute in the Form gets precedence.
p = PersonNew(auto_id=True)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="first_name_id">First name:</label>
<input type="text" id="first_name_id" name="first_name" required></li>
<li><label for="last_name">Last name:</label>
<input type="text" name="last_name" id="last_name" required></li>
<li><label for="birthday">Birthday:</label>
<input type="text" name="birthday" id="birthday" required></li>""",
)
def test_various_boolean_values(self):
class SignupForm(Form):
email = EmailField()
get_spam = BooleanField()
f = SignupForm(auto_id=False)
self.assertHTMLEqual(
str(f["email"]), '<input type="email" name="email" required>'
)
self.assertHTMLEqual(
str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>'
)
f = SignupForm({"email": "[email protected]", "get_spam": True}, auto_id=False)
self.assertHTMLEqual(
str(f["email"]),
'<input type="email" name="email" value="[email protected]" required>',
)
self.assertHTMLEqual(
str(f["get_spam"]),
'<input checked type="checkbox" name="get_spam" required>',
)
# 'True' or 'true' should be rendered without a value attribute
f = SignupForm({"email": "[email protected]", "get_spam": "True"}, auto_id=False)
self.assertHTMLEqual(
str(f["get_spam"]),
'<input checked type="checkbox" name="get_spam" required>',
)
f = SignupForm({"email": "[email protected]", "get_spam": "true"}, auto_id=False)
self.assertHTMLEqual(
str(f["get_spam"]),
'<input checked type="checkbox" name="get_spam" required>',
)
# A value of 'False' or 'false' should be rendered unchecked
f = SignupForm(
{"email": "[email protected]", "get_spam": "False"}, auto_id=False
)
self.assertHTMLEqual(
str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>'
)
f = SignupForm(
{"email": "[email protected]", "get_spam": "false"}, auto_id=False
)
self.assertHTMLEqual(
str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>'
)
# A value of '0' should be interpreted as a True value (#16820)
f = SignupForm({"email": "[email protected]", "get_spam": "0"})
self.assertTrue(f.is_valid())
self.assertTrue(f.cleaned_data.get("get_spam"))
def test_widget_output(self):
# Any Field can have a Widget class passed to its constructor:
class ContactForm(Form):
subject = CharField()
message = CharField(widget=Textarea)
f = ContactForm(auto_id=False)
self.assertHTMLEqual(
str(f["subject"]), '<input type="text" name="subject" required>'
)
self.assertHTMLEqual(
str(f["message"]),
'<textarea name="message" rows="10" cols="40" required></textarea>',
)
# as_textarea(), as_text() and as_hidden() are shortcuts for changing the output
# widget type:
self.assertHTMLEqual(
f["subject"].as_textarea(),
'<textarea name="subject" rows="10" cols="40" required></textarea>',
)
self.assertHTMLEqual(
f["message"].as_text(), '<input type="text" name="message" required>'
)
self.assertHTMLEqual(
f["message"].as_hidden(), '<input type="hidden" name="message">'
)
# The 'widget' parameter to a Field can also be an instance:
class ContactForm(Form):
subject = CharField()
message = CharField(widget=Textarea(attrs={"rows": 80, "cols": 20}))
f = ContactForm(auto_id=False)
self.assertHTMLEqual(
str(f["message"]),
'<textarea name="message" rows="80" cols="20" required></textarea>',
)
# Instance-level attrs are *not* carried over to as_textarea(), as_text() and
# as_hidden():
self.assertHTMLEqual(
f["message"].as_text(), '<input type="text" name="message" required>'
)
f = ContactForm({"subject": "Hello", "message": "I love you."}, auto_id=False)
self.assertHTMLEqual(
f["subject"].as_textarea(),
'<textarea rows="10" cols="40" name="subject" required>Hello</textarea>',
)
self.assertHTMLEqual(
f["message"].as_text(),
'<input type="text" name="message" value="I love you." required>',
)
self.assertHTMLEqual(
f["message"].as_hidden(),
'<input type="hidden" name="message" value="I love you.">',
)
def test_forms_with_choices(self):
# For a form with a <select>, use ChoiceField:
class FrameworkForm(Form):
name = CharField()
language = ChoiceField(choices=[("P", "Python"), ("J", "Java")])
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<select name="language">
<option value="P">Python</option>
<option value="J">Java</option>
</select>""",
)
f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<select name="language">
<option value="P" selected>Python</option>
<option value="J">Java</option>
</select>""",
)
# A subtlety: If one of the choices' value is the empty string and the form is
# unbound, then the <option> for the empty-string choice will get selected.
class FrameworkForm(Form):
name = CharField()
language = ChoiceField(
choices=[("", "------"), ("P", "Python"), ("J", "Java")]
)
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<select name="language" required>
<option value="" selected>------</option>
<option value="P">Python</option>
<option value="J">Java</option>
</select>""",
)
# You can specify widget attributes in the Widget constructor.
class FrameworkForm(Form):
name = CharField()
language = ChoiceField(
choices=[("P", "Python"), ("J", "Java")],
widget=Select(attrs={"class": "foo"}),
)
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<select class="foo" name="language">
<option value="P">Python</option>
<option value="J">Java</option>
</select>""",
)
f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<select class="foo" name="language">
<option value="P" selected>Python</option>
<option value="J">Java</option>
</select>""",
)
# When passing a custom widget instance to ChoiceField, note that setting
# 'choices' on the widget is meaningless. The widget will use the choices
# defined on the Field, not the ones defined on the Widget.
class FrameworkForm(Form):
name = CharField()
language = ChoiceField(
choices=[("P", "Python"), ("J", "Java")],
widget=Select(
choices=[("R", "Ruby"), ("P", "Perl")], attrs={"class": "foo"}
),
)
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<select class="foo" name="language">
<option value="P">Python</option>
<option value="J">Java</option>
</select>""",
)
f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<select class="foo" name="language">
<option value="P" selected>Python</option>
<option value="J">Java</option>
</select>""",
)
# You can set a ChoiceField's choices after the fact.
class FrameworkForm(Form):
name = CharField()
language = ChoiceField()
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<select name="language">
</select>""",
)
f.fields["language"].choices = [("P", "Python"), ("J", "Java")]
self.assertHTMLEqual(
str(f["language"]),
"""<select name="language">
<option value="P">Python</option>
<option value="J">Java</option>
</select>""",
)
def test_forms_with_radio(self):
# Add widget=RadioSelect to use that widget with a ChoiceField.
f = FrameworkForm(auto_id=False)
self.assertHTMLEqual(
str(f["language"]),
"""<div>
<div><label><input type="radio" name="language" value="P" required> Python</label></div>
<div><label><input type="radio" name="language" value="J" required> Java</label></div>
</div>""",
)
self.assertHTMLEqual(
f.as_table(),
"""<tr><th>Name:</th><td><input type="text" name="name" required></td></tr>
<tr><th>Language:</th><td><div>
<div><label><input type="radio" name="language" value="P" required> Python</label></div>
<div><label><input type="radio" name="language" value="J" required> Java</label></div>
</div></td></tr>""",
)
self.assertHTMLEqual(
f.as_ul(),
"""<li>Name: <input type="text" name="name" required></li>
<li>Language: <div>
<div><label><input type="radio" name="language" value="P" required> Python</label></div>
<div><label><input type="radio" name="language" value="J" required> Java</label></div>
</div></li>""",
)
# Need an auto_id to generate legend.
self.assertHTMLEqual(
f.render(f.template_name_div),
'<div> Name: <input type="text" name="name" required></div><div><fieldset>'
'Language:<div><div><label><input type="radio" name="language" value="P" '
'required> Python</label></div><div><label><input type="radio" '
'name="language" value="J" required> Java</label></div></div></fieldset>'
"</div>",
)
# Regarding auto_id and <label>, RadioSelect is a special case. Each
# radio button gets a distinct ID, formed by appending an underscore
# plus the button's zero-based index.
f = FrameworkForm(auto_id="id_%s")
self.assertHTMLEqual(
str(f["language"]),
"""
<div id="id_language">
<div><label for="id_language_0">
<input type="radio" id="id_language_0" value="P" name="language" required>
Python</label></div>
<div><label for="id_language_1">
<input type="radio" id="id_language_1" value="J" name="language" required>
Java</label></div>
</div>""",
)
# When RadioSelect is used with auto_id, and the whole form is printed
# using either as_table() or as_ul(), the label for the RadioSelect
# will **not** point to the ID of the *first* radio button to improve
# accessibility for screen reader users.
self.assertHTMLEqual(
f.as_table(),
"""
<tr><th><label for="id_name">Name:</label></th><td>
<input type="text" name="name" id="id_name" required></td></tr>
<tr><th><label>Language:</label></th><td><div id="id_language">
<div><label for="id_language_0">
<input type="radio" id="id_language_0" value="P" name="language" required>
Python</label></div>
<div><label for="id_language_1">
<input type="radio" id="id_language_1" value="J" name="language" required>
Java</label></div>
</div></td></tr>""",
)
self.assertHTMLEqual(
f.as_ul(),
"""
<li><label for="id_name">Name:</label>
<input type="text" name="name" id="id_name" required></li>
<li><label>Language:</label> <div id="id_language">
<div><label for="id_language_0">
<input type="radio" id="id_language_0" value="P" name="language" required>
Python</label></div>
<div><label for="id_language_1">
<input type="radio" id="id_language_1" value="J" name="language" required>
Java</label></div>
</div></li>
""",
)
self.assertHTMLEqual(
f.as_p(),
"""
<p><label for="id_name">Name:</label>
<input type="text" name="name" id="id_name" required></p>
<p><label>Language:</label> <div id="id_language">
<div><label for="id_language_0">
<input type="radio" id="id_language_0" value="P" name="language" required>
Python</label></div>
<div><label for="id_language_1">
<input type="radio" id="id_language_1" value="J" name="language" required>
Java</label></div>
</div></p>
""",
)
self.assertHTMLEqual(
f.render(f.template_name_div),
'<div><label for="id_name">Name:</label><input type="text" name="name" '
'required id="id_name"></div><div><fieldset><legend>Language:</legend>'
'<div id="id_language"><div><label for="id_language_0"><input '
'type="radio" name="language" value="P" required id="id_language_0">'
'Python</label></div><div><label for="id_language_1"><input type="radio" '
'name="language" value="J" required id="id_language_1">Java</label></div>'
"</div></fieldset></div>",
)
def test_form_with_iterable_boundfield(self):
class BeatleForm(Form):
name = ChoiceField(
choices=[
("john", "John"),
("paul", "Paul"),
("george", "George"),
("ringo", "Ringo"),
],
widget=RadioSelect,
)
f = BeatleForm(auto_id=False)
self.assertHTMLEqual(
"\n".join(str(bf) for bf in f["name"]),
'<label><input type="radio" name="name" value="john" required> John</label>'
'<label><input type="radio" name="name" value="paul" required> Paul</label>'
'<label><input type="radio" name="name" value="george" required> George'
"</label>"
'<label><input type="radio" name="name" value="ringo" required> Ringo'
"</label>",
)
self.assertHTMLEqual(
"\n".join("<div>%s</div>" % bf for bf in f["name"]),
"""
<div><label>
<input type="radio" name="name" value="john" required> John</label></div>
<div><label>
<input type="radio" name="name" value="paul" required> Paul</label></div>
<div><label>
<input type="radio" name="name" value="george" required> George
</label></div>
<div><label>
<input type="radio" name="name" value="ringo" required> Ringo</label></div>
""",
)
def test_form_with_iterable_boundfield_id(self):
class BeatleForm(Form):
name = ChoiceField(
choices=[
("john", "John"),
("paul", "Paul"),
("george", "George"),
("ringo", "Ringo"),
],
widget=RadioSelect,
)
fields = list(BeatleForm()["name"])
self.assertEqual(len(fields), 4)
self.assertEqual(fields[0].id_for_label, "id_name_0")
self.assertEqual(fields[0].choice_label, "John")
self.assertHTMLEqual(
fields[0].tag(),
'<input type="radio" name="name" value="john" id="id_name_0" required>',
)
self.assertHTMLEqual(
str(fields[0]),
'<label for="id_name_0"><input type="radio" name="name" '
'value="john" id="id_name_0" required> John</label>',
)
self.assertEqual(fields[1].id_for_label, "id_name_1")
self.assertEqual(fields[1].choice_label, "Paul")
self.assertHTMLEqual(
fields[1].tag(),
'<input type="radio" name="name" value="paul" id="id_name_1" required>',
)
self.assertHTMLEqual(
str(fields[1]),
'<label for="id_name_1"><input type="radio" name="name" '
'value="paul" id="id_name_1" required> Paul</label>',
)
def test_iterable_boundfield_select(self):
class BeatleForm(Form):
name = ChoiceField(
choices=[
("john", "John"),
("paul", "Paul"),
("george", "George"),
("ringo", "Ringo"),
]
)
fields = list(BeatleForm(auto_id=False)["name"])
self.assertEqual(len(fields), 4)
self.assertIsNone(fields[0].id_for_label)
self.assertEqual(fields[0].choice_label, "John")
self.assertHTMLEqual(fields[0].tag(), '<option value="john">John</option>')
self.assertHTMLEqual(str(fields[0]), '<option value="john">John</option>')
def test_form_with_noniterable_boundfield(self):
# You can iterate over any BoundField, not just those with widget=RadioSelect.
class BeatleForm(Form):
name = CharField()
f = BeatleForm(auto_id=False)
self.assertHTMLEqual(
"\n".join(str(bf) for bf in f["name"]),
'<input type="text" name="name" required>',
)
def test_boundfield_slice(self):
class BeatleForm(Form):
name = ChoiceField(
choices=[
("john", "John"),
("paul", "Paul"),
("george", "George"),
("ringo", "Ringo"),
],
widget=RadioSelect,
)
f = BeatleForm()
bf = f["name"]
self.assertEqual(
[str(item) for item in bf[1:]],
[str(bf[1]), str(bf[2]), str(bf[3])],
)
def test_boundfield_invalid_index(self):
class TestForm(Form):
name = ChoiceField(choices=[])
field = TestForm()["name"]
msg = "BoundField indices must be integers or slices, not str."
with self.assertRaisesMessage(TypeError, msg):
field["foo"]
def test_boundfield_bool(self):
"""BoundField without any choices (subwidgets) evaluates to True."""
class TestForm(Form):
name = ChoiceField(choices=[])
self.assertIs(bool(TestForm()["name"]), True)
def test_forms_with_multiple_choice(self):
# MultipleChoiceField is a special case, as its data is required to be a list:
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField()
f = SongForm(auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
"""<select multiple name="composers" required>
</select>""",
)
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[("J", "John Lennon"), ("P", "Paul McCartney")]
)
f = SongForm(auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
"""<select multiple name="composers" required>
<option value="J">John Lennon</option>
<option value="P">Paul McCartney</option>
</select>""",
)
f = SongForm({"name": "Yesterday", "composers": ["P"]}, auto_id=False)
self.assertHTMLEqual(
str(f["name"]), '<input type="text" name="name" value="Yesterday" required>'
)
self.assertHTMLEqual(
str(f["composers"]),
"""<select multiple name="composers" required>
<option value="J">John Lennon</option>
<option value="P" selected>Paul McCartney</option>
</select>""",
)
f = SongForm()
self.assertHTMLEqual(
f.as_table(),
'<tr><th><label for="id_name">Name:</label></th>'
'<td><input type="text" name="name" required id="id_name"></td>'
'</tr><tr><th><label for="id_composers">Composers:</label></th>'
'<td><select name="composers" required id="id_composers" multiple>'
'<option value="J">John Lennon</option>'
'<option value="P">Paul McCartney</option>'
"</select></td></tr>",
)
self.assertHTMLEqual(
f.as_ul(),
'<li><label for="id_name">Name:</label>'
'<input type="text" name="name" required id="id_name"></li>'
'<li><label for="id_composers">Composers:</label>'
'<select name="composers" required id="id_composers" multiple>'
'<option value="J">John Lennon</option>'
'<option value="P">Paul McCartney</option>'
"</select></li>",
)
self.assertHTMLEqual(
f.as_p(),
'<p><label for="id_name">Name:</label>'
'<input type="text" name="name" required id="id_name"></p>'
'<p><label for="id_composers">Composers:</label>'
'<select name="composers" required id="id_composers" multiple>'
'<option value="J">John Lennon</option>'
'<option value="P">Paul McCartney</option>'
"</select></p>",
)
self.assertHTMLEqual(
f.render(f.template_name_div),
'<div><label for="id_name">Name:</label><input type="text" name="name" '
'required id="id_name"></div><div><label for="id_composers">Composers:'
'</label><select name="composers" required id="id_composers" multiple>'
'<option value="J">John Lennon</option><option value="P">Paul McCartney'
"</option></select></div>",
)
def test_multiple_checkbox_render(self):
f = SongForm()
self.assertHTMLEqual(
f.as_table(),
'<tr><th><label for="id_name">Name:</label></th><td>'
'<input type="text" name="name" required id="id_name"></td></tr>'
'<tr><th><label>Composers:</label></th><td><div id="id_composers">'
'<div><label for="id_composers_0">'
'<input type="checkbox" name="composers" value="J" '
'id="id_composers_0">John Lennon</label></div>'
'<div><label for="id_composers_1">'
'<input type="checkbox" name="composers" value="P" '
'id="id_composers_1">Paul McCartney</label></div>'
"</div></td></tr>",
)
self.assertHTMLEqual(
f.as_ul(),
'<li><label for="id_name">Name:</label>'
'<input type="text" name="name" required id="id_name"></li>'
'<li><label>Composers:</label><div id="id_composers">'
'<div><label for="id_composers_0">'
'<input type="checkbox" name="composers" value="J" '
'id="id_composers_0">John Lennon</label></div>'
'<div><label for="id_composers_1">'
'<input type="checkbox" name="composers" value="P" '
'id="id_composers_1">Paul McCartney</label></div>'
"</div></li>",
)
self.assertHTMLEqual(
f.as_p(),
'<p><label for="id_name">Name:</label>'
'<input type="text" name="name" required id="id_name"></p>'
'<p><label>Composers:</label><div id="id_composers">'
'<div><label for="id_composers_0">'
'<input type="checkbox" name="composers" value="J" '
'id="id_composers_0">John Lennon</label></div>'
'<div><label for="id_composers_1">'
'<input type="checkbox" name="composers" value="P" '
'id="id_composers_1">Paul McCartney</label></div>'
"</div></p>",
)
self.assertHTMLEqual(
f.render(f.template_name_div),
'<div><label for="id_name">Name:</label><input type="text" name="name" '
'required id="id_name"></div><div><fieldset><legend>Composers:</legend>'
'<div id="id_composers"><div><label for="id_composers_0"><input '
'type="checkbox" name="composers" value="J" id="id_composers_0">'
'John Lennon</label></div><div><label for="id_composers_1"><input '
'type="checkbox" name="composers" value="P" id="id_composers_1">'
"Paul McCartney</label></div></div></fieldset></div>",
)
def test_form_with_disabled_fields(self):
class PersonForm(Form):
name = CharField()
birthday = DateField(disabled=True)
class PersonFormFieldInitial(Form):
name = CharField()
birthday = DateField(disabled=True, initial=datetime.date(1974, 8, 16))
# Disabled fields are generally not transmitted by user agents.
# The value from the form's initial data is used.
f1 = PersonForm(
{"name": "John Doe"}, initial={"birthday": datetime.date(1974, 8, 16)}
)
f2 = PersonFormFieldInitial({"name": "John Doe"})
for form in (f1, f2):
self.assertTrue(form.is_valid())
self.assertEqual(
form.cleaned_data,
{"birthday": datetime.date(1974, 8, 16), "name": "John Doe"},
)
# Values provided in the form's data are ignored.
data = {"name": "John Doe", "birthday": "1984-11-10"}
f1 = PersonForm(data, initial={"birthday": datetime.date(1974, 8, 16)})
f2 = PersonFormFieldInitial(data)
for form in (f1, f2):
self.assertTrue(form.is_valid())
self.assertEqual(
form.cleaned_data,
{"birthday": datetime.date(1974, 8, 16), "name": "John Doe"},
)
# Initial data remains present on invalid forms.
data = {}
f1 = PersonForm(data, initial={"birthday": datetime.date(1974, 8, 16)})
f2 = PersonFormFieldInitial(data)
for form in (f1, f2):
self.assertFalse(form.is_valid())
self.assertEqual(form["birthday"].value(), datetime.date(1974, 8, 16))
def test_hidden_data(self):
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[("J", "John Lennon"), ("P", "Paul McCartney")]
)
# MultipleChoiceField rendered as_hidden() is a special case. Because it can
# have multiple values, its as_hidden() renders multiple <input type="hidden">
# tags.
f = SongForm({"name": "Yesterday", "composers": ["P"]}, auto_id=False)
self.assertHTMLEqual(
f["composers"].as_hidden(),
'<input type="hidden" name="composers" value="P">',
)
f = SongForm({"name": "From Me To You", "composers": ["P", "J"]}, auto_id=False)
self.assertHTMLEqual(
f["composers"].as_hidden(),
"""<input type="hidden" name="composers" value="P">
<input type="hidden" name="composers" value="J">""",
)
# DateTimeField rendered as_hidden() is special too
class MessageForm(Form):
when = SplitDateTimeField()
f = MessageForm({"when_0": "1992-01-01", "when_1": "01:01"})
self.assertTrue(f.is_valid())
self.assertHTMLEqual(
str(f["when"]),
'<input type="text" name="when_0" value="1992-01-01" id="id_when_0" '
"required>"
'<input type="text" name="when_1" value="01:01" id="id_when_1" required>',
)
self.assertHTMLEqual(
f["when"].as_hidden(),
'<input type="hidden" name="when_0" value="1992-01-01" id="id_when_0">'
'<input type="hidden" name="when_1" value="01:01" id="id_when_1">',
)
def test_multiple_choice_checkbox(self):
# MultipleChoiceField can also be used with the CheckboxSelectMultiple widget.
f = SongForm(auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
"""
<div>
<div><label><input type="checkbox" name="composers" value="J">
John Lennon</label></div>
<div><label><input type="checkbox" name="composers" value="P">
Paul McCartney</label></div>
</div>
""",
)
f = SongForm({"composers": ["J"]}, auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
"""
<div>
<div><label><input checked type="checkbox" name="composers" value="J">
John Lennon</label></div>
<div><label><input type="checkbox" name="composers" value="P">
Paul McCartney</label></div>
</div>
""",
)
f = SongForm({"composers": ["J", "P"]}, auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
"""
<div>
<div><label><input checked type="checkbox" name="composers" value="J">
John Lennon</label></div>
<div><label><input checked type="checkbox" name="composers" value="P">
Paul McCartney</label></div>
</div>
""",
)
def test_checkbox_auto_id(self):
# Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox
# gets a distinct ID, formed by appending an underscore plus the checkbox's
# zero-based index.
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[("J", "John Lennon"), ("P", "Paul McCartney")],
widget=CheckboxSelectMultiple,
)
f = SongForm(auto_id="%s_id")
self.assertHTMLEqual(
str(f["composers"]),
"""
<div id="composers_id">
<div><label for="composers_id_0">
<input type="checkbox" name="composers" value="J" id="composers_id_0">
John Lennon</label></div>
<div><label for="composers_id_1">
<input type="checkbox" name="composers" value="P" id="composers_id_1">
Paul McCartney</label></div>
</div>
""",
)
def test_multiple_choice_list_data(self):
# Data for a MultipleChoiceField should be a list. QueryDict and
# MultiValueDict conveniently work with this.
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[("J", "John Lennon"), ("P", "Paul McCartney")],
widget=CheckboxSelectMultiple,
)
data = {"name": "Yesterday", "composers": ["J", "P"]}
f = SongForm(data)
self.assertEqual(f.errors, {})
data = QueryDict("name=Yesterday&composers=J&composers=P")
f = SongForm(data)
self.assertEqual(f.errors, {})
data = MultiValueDict({"name": ["Yesterday"], "composers": ["J", "P"]})
f = SongForm(data)
self.assertEqual(f.errors, {})
# SelectMultiple uses ducktyping so that MultiValueDictLike.getlist()
# is called.
f = SongForm(MultiValueDictLike({"name": "Yesterday", "composers": "J"}))
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data["composers"], ["J"])
def test_multiple_hidden(self):
class SongForm(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[("J", "John Lennon"), ("P", "Paul McCartney")],
widget=CheckboxSelectMultiple,
)
# The MultipleHiddenInput widget renders multiple values as hidden fields.
class SongFormHidden(Form):
name = CharField()
composers = MultipleChoiceField(
choices=[("J", "John Lennon"), ("P", "Paul McCartney")],
widget=MultipleHiddenInput,
)
f = SongFormHidden(
MultiValueDict({"name": ["Yesterday"], "composers": ["J", "P"]}),
auto_id=False,
)
self.assertHTMLEqual(
f.as_ul(),
"""<li>Name: <input type="text" name="name" value="Yesterday" required>
<input type="hidden" name="composers" value="J">
<input type="hidden" name="composers" value="P"></li>""",
)
# When using CheckboxSelectMultiple, the framework expects a list of input and
# returns a list of input.
f = SongForm({"name": "Yesterday"}, auto_id=False)
self.assertEqual(f.errors["composers"], ["This field is required."])
f = SongForm({"name": "Yesterday", "composers": ["J"]}, auto_id=False)
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data["composers"], ["J"])
self.assertEqual(f.cleaned_data["name"], "Yesterday")
f = SongForm({"name": "Yesterday", "composers": ["J", "P"]}, auto_id=False)
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data["composers"], ["J", "P"])
self.assertEqual(f.cleaned_data["name"], "Yesterday")
# MultipleHiddenInput uses ducktyping so that
# MultiValueDictLike.getlist() is called.
f = SongForm(MultiValueDictLike({"name": "Yesterday", "composers": "J"}))
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data["composers"], ["J"])
def test_escaping(self):
# Validation errors are HTML-escaped when output as HTML.
class EscapingForm(Form):
special_name = CharField(label="<em>Special</em> Field")
special_safe_name = CharField(label=mark_safe("<em>Special</em> Field"))
def clean_special_name(self):
raise ValidationError(
"Something's wrong with '%s'" % self.cleaned_data["special_name"]
)
def clean_special_safe_name(self):
raise ValidationError(
mark_safe(
"'<b>%s</b>' is a safe string"
% self.cleaned_data["special_safe_name"]
)
)
f = EscapingForm(
{
"special_name": "Nothing to escape",
"special_safe_name": "Nothing to escape",
},
auto_id=False,
)
self.assertHTMLEqual(
f.as_table(),
"""
<tr><th><em>Special</em> Field:</th><td>
<ul class="errorlist">
<li>Something's wrong with 'Nothing to escape'</li></ul>
<input type="text" name="special_name" value="Nothing to escape" required>
</td></tr>
<tr><th><em>Special</em> Field:</th><td>
<ul class="errorlist">
<li>'<b>Nothing to escape</b>' is a safe string</li></ul>
<input type="text" name="special_safe_name" value="Nothing to escape"
required></td></tr>
""",
)
f = EscapingForm(
{
"special_name": "Should escape < & > and <script>alert('xss')</script>",
"special_safe_name": "<i>Do not escape</i>",
},
auto_id=False,
)
self.assertHTMLEqual(
f.as_table(),
"<tr><th><em>Special</em> Field:</th><td>"
'<ul class="errorlist"><li>'
"Something's wrong with 'Should escape < & > and "
"<script>alert('xss')</script>'</li></ul>"
'<input type="text" name="special_name" value="Should escape < & '
'> and <script>alert('xss')</script>" required>'
"</td></tr>"
"<tr><th><em>Special</em> Field:</th><td>"
'<ul class="errorlist">'
"<li>'<b><i>Do not escape</i></b>' is a safe string</li></ul>"
'<input type="text" name="special_safe_name" '
'value="<i>Do not escape</i>" required></td></tr>',
)
def test_validating_multiple_fields(self):
# There are a couple of ways to do multiple-field validation. If you
# want the validation message to be associated with a particular field,
# implement the clean_XXX() method on the Form, where XXX is the field
# name. As in Field.clean(), the clean_XXX() method should return the
# cleaned value. In the clean_XXX() method, you have access to
# self.cleaned_data, which is a dictionary of all the data that has
# been cleaned *so far*, in order by the fields, including the current
# field (e.g., the field XXX if you're in clean_XXX()).
class UserRegistration(Form):
username = CharField(max_length=10)
password1 = CharField(widget=PasswordInput)
password2 = CharField(widget=PasswordInput)
def clean_password2(self):
if (
self.cleaned_data.get("password1")
and self.cleaned_data.get("password2")
and self.cleaned_data["password1"] != self.cleaned_data["password2"]
):
raise ValidationError("Please make sure your passwords match.")
return self.cleaned_data["password2"]
f = UserRegistration(auto_id=False)
self.assertEqual(f.errors, {})
f = UserRegistration({}, auto_id=False)
self.assertEqual(f.errors["username"], ["This field is required."])
self.assertEqual(f.errors["password1"], ["This field is required."])
self.assertEqual(f.errors["password2"], ["This field is required."])
f = UserRegistration(
{"username": "adrian", "password1": "foo", "password2": "bar"},
auto_id=False,
)
self.assertEqual(
f.errors["password2"], ["Please make sure your passwords match."]
)
f = UserRegistration(
{"username": "adrian", "password1": "foo", "password2": "foo"},
auto_id=False,
)
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data["username"], "adrian")
self.assertEqual(f.cleaned_data["password1"], "foo")
self.assertEqual(f.cleaned_data["password2"], "foo")
# Another way of doing multiple-field validation is by implementing the
# Form's clean() method. Usually ValidationError raised by that method
# will not be associated with a particular field and will have a
# special-case association with the field named '__all__'. It's
# possible to associate the errors to particular field with the
# Form.add_error() method or by passing a dictionary that maps each
# field to one or more errors.
#
# Note that in Form.clean(), you have access to self.cleaned_data, a
# dictionary of all the fields/values that have *not* raised a
# ValidationError. Also note Form.clean() is required to return a
# dictionary of all clean data.
class UserRegistration(Form):
username = CharField(max_length=10)
password1 = CharField(widget=PasswordInput)
password2 = CharField(widget=PasswordInput)
def clean(self):
# Test raising a ValidationError as NON_FIELD_ERRORS.
if (
self.cleaned_data.get("password1")
and self.cleaned_data.get("password2")
and self.cleaned_data["password1"] != self.cleaned_data["password2"]
):
raise ValidationError("Please make sure your passwords match.")
# Test raising ValidationError that targets multiple fields.
errors = {}
if self.cleaned_data.get("password1") == "FORBIDDEN_VALUE":
errors["password1"] = "Forbidden value."
if self.cleaned_data.get("password2") == "FORBIDDEN_VALUE":
errors["password2"] = ["Forbidden value."]
if errors:
raise ValidationError(errors)
# Test Form.add_error()
if self.cleaned_data.get("password1") == "FORBIDDEN_VALUE2":
self.add_error(None, "Non-field error 1.")
self.add_error("password1", "Forbidden value 2.")
if self.cleaned_data.get("password2") == "FORBIDDEN_VALUE2":
self.add_error("password2", "Forbidden value 2.")
raise ValidationError("Non-field error 2.")
return self.cleaned_data
f = UserRegistration(auto_id=False)
self.assertEqual(f.errors, {})
f = UserRegistration({}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
"""<tr><th>Username:</th><td>
<ul class="errorlist"><li>This field is required.</li></ul>
<input type="text" name="username" maxlength="10" required></td></tr>
<tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul>
<input type="password" name="password1" required></td></tr>
<tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul>
<input type="password" name="password2" required></td></tr>""",
)
self.assertEqual(f.errors["username"], ["This field is required."])
self.assertEqual(f.errors["password1"], ["This field is required."])
self.assertEqual(f.errors["password2"], ["This field is required."])
f = UserRegistration(
{"username": "adrian", "password1": "foo", "password2": "bar"},
auto_id=False,
)
self.assertEqual(
f.errors["__all__"], ["Please make sure your passwords match."]
)
self.assertHTMLEqual(
f.as_table(),
"""
<tr><td colspan="2">
<ul class="errorlist nonfield">
<li>Please make sure your passwords match.</li></ul></td></tr>
<tr><th>Username:</th><td>
<input type="text" name="username" value="adrian" maxlength="10" required>
</td></tr>
<tr><th>Password1:</th><td>
<input type="password" name="password1" required></td></tr>
<tr><th>Password2:</th><td>
<input type="password" name="password2" required></td></tr>
""",
)
self.assertHTMLEqual(
f.as_ul(),
"""
<li><ul class="errorlist nonfield">
<li>Please make sure your passwords match.</li></ul></li>
<li>Username:
<input type="text" name="username" value="adrian" maxlength="10" required>
</li>
<li>Password1: <input type="password" name="password1" required></li>
<li>Password2: <input type="password" name="password2" required></li>
""",
)
self.assertHTMLEqual(
f.render(f.template_name_div),
'<ul class="errorlist nonfield"><li>Please make sure your passwords match.'
'</li></ul><div>Username: <input type="text" name="username" '
'value="adrian" maxlength="10" required></div><div>Password1: <input '
'type="password" name="password1" required></div><div>Password2: <input '
'type="password" name="password2" required></div>',
)
f = UserRegistration(
{"username": "adrian", "password1": "foo", "password2": "foo"},
auto_id=False,
)
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data["username"], "adrian")
self.assertEqual(f.cleaned_data["password1"], "foo")
self.assertEqual(f.cleaned_data["password2"], "foo")
f = UserRegistration(
{
"username": "adrian",
"password1": "FORBIDDEN_VALUE",
"password2": "FORBIDDEN_VALUE",
},
auto_id=False,
)
self.assertEqual(f.errors["password1"], ["Forbidden value."])
self.assertEqual(f.errors["password2"], ["Forbidden value."])
f = UserRegistration(
{
"username": "adrian",
"password1": "FORBIDDEN_VALUE2",
"password2": "FORBIDDEN_VALUE2",
},
auto_id=False,
)
self.assertEqual(
f.errors["__all__"], ["Non-field error 1.", "Non-field error 2."]
)
self.assertEqual(f.errors["password1"], ["Forbidden value 2."])
self.assertEqual(f.errors["password2"], ["Forbidden value 2."])
with self.assertRaisesMessage(ValueError, "has no field named"):
f.add_error("missing_field", "Some error.")
def test_update_error_dict(self):
class CodeForm(Form):
code = CharField(max_length=10)
def clean(self):
try:
raise ValidationError({"code": [ValidationError("Code error 1.")]})
except ValidationError as e:
self._errors = e.update_error_dict(self._errors)
try:
raise ValidationError({"code": [ValidationError("Code error 2.")]})
except ValidationError as e:
self._errors = e.update_error_dict(self._errors)
try:
raise ValidationError({"code": forms.ErrorList(["Code error 3."])})
except ValidationError as e:
self._errors = e.update_error_dict(self._errors)
try:
raise ValidationError("Non-field error 1.")
except ValidationError as e:
self._errors = e.update_error_dict(self._errors)
try:
raise ValidationError([ValidationError("Non-field error 2.")])
except ValidationError as e:
self._errors = e.update_error_dict(self._errors)
# The newly added list of errors is an instance of ErrorList.
for field, error_list in self._errors.items():
if not isinstance(error_list, self.error_class):
self._errors[field] = self.error_class(error_list)
form = CodeForm({"code": "hello"})
# Trigger validation.
self.assertFalse(form.is_valid())
# update_error_dict didn't lose track of the ErrorDict type.
self.assertIsInstance(form._errors, forms.ErrorDict)
self.assertEqual(
dict(form.errors),
{
"code": ["Code error 1.", "Code error 2.", "Code error 3."],
NON_FIELD_ERRORS: ["Non-field error 1.", "Non-field error 2."],
},
)
def test_has_error(self):
class UserRegistration(Form):
username = CharField(max_length=10)
password1 = CharField(widget=PasswordInput, min_length=5)
password2 = CharField(widget=PasswordInput)
def clean(self):
if (
self.cleaned_data.get("password1")
and self.cleaned_data.get("password2")
and self.cleaned_data["password1"] != self.cleaned_data["password2"]
):
raise ValidationError(
"Please make sure your passwords match.",
code="password_mismatch",
)
f = UserRegistration(data={})
self.assertTrue(f.has_error("password1"))
self.assertTrue(f.has_error("password1", "required"))
self.assertFalse(f.has_error("password1", "anything"))
f = UserRegistration(data={"password1": "Hi", "password2": "Hi"})
self.assertTrue(f.has_error("password1"))
self.assertTrue(f.has_error("password1", "min_length"))
self.assertFalse(f.has_error("password1", "anything"))
self.assertFalse(f.has_error("password2"))
self.assertFalse(f.has_error("password2", "anything"))
f = UserRegistration(data={"password1": "Bonjour", "password2": "Hello"})
self.assertFalse(f.has_error("password1"))
self.assertFalse(f.has_error("password1", "required"))
self.assertTrue(f.has_error(NON_FIELD_ERRORS))
self.assertTrue(f.has_error(NON_FIELD_ERRORS, "password_mismatch"))
self.assertFalse(f.has_error(NON_FIELD_ERRORS, "anything"))
def test_html_output_with_hidden_input_field_errors(self):
class TestForm(Form):
hidden_input = CharField(widget=HiddenInput)
def clean(self):
self.add_error(None, "Form error")
f = TestForm(data={})
error_dict = {
"hidden_input": ["This field is required."],
"__all__": ["Form error"],
}
self.assertEqual(f.errors, error_dict)
f.as_table()
self.assertEqual(f.errors, error_dict)
self.assertHTMLEqual(
f.as_table(),
'<tr><td colspan="2"><ul class="errorlist nonfield"><li>Form error</li>'
"<li>(Hidden field hidden_input) This field is required.</li></ul>"
'<input type="hidden" name="hidden_input" id="id_hidden_input"></td></tr>',
)
self.assertHTMLEqual(
f.as_ul(),
'<li><ul class="errorlist nonfield"><li>Form error</li>'
"<li>(Hidden field hidden_input) This field is required.</li></ul>"
'<input type="hidden" name="hidden_input" id="id_hidden_input"></li>',
)
self.assertHTMLEqual(
f.as_p(),
'<ul class="errorlist nonfield"><li>Form error</li>'
"<li>(Hidden field hidden_input) This field is required.</li></ul>"
'<p><input type="hidden" name="hidden_input" id="id_hidden_input"></p>',
)
self.assertHTMLEqual(
f.render(f.template_name_div),
'<ul class="errorlist nonfield"><li>Form error</li>'
"<li>(Hidden field hidden_input) This field is required.</li></ul>"
'<div><input type="hidden" name="hidden_input" id="id_hidden_input"></div>',
)
def test_dynamic_construction(self):
# It's possible to construct a Form dynamically by adding to the self.fields
# dictionary in __init__(). Don't forget to call Form.__init__() within the
# subclass' __init__().
class Person(Form):
first_name = CharField()
last_name = CharField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["birthday"] = DateField()
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_table(),
"""
<tr><th>First name:</th><td>
<input type="text" name="first_name" required></td></tr>
<tr><th>Last name:</th><td>
<input type="text" name="last_name" required></td></tr>
<tr><th>Birthday:</th><td>
<input type="text" name="birthday" required></td></tr>
""",
)
# Instances of a dynamic Form do not persist fields from one Form instance to
# the next.
class MyForm(Form):
def __init__(self, data=None, auto_id=False, field_list=[]):
Form.__init__(self, data, auto_id=auto_id)
for field in field_list:
self.fields[field[0]] = field[1]
field_list = [("field1", CharField()), ("field2", CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
"""
<tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr>
<tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>
""",
)
field_list = [("field3", CharField()), ("field4", CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
"""
<tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr>
<tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr>
""",
)
class MyForm(Form):
default_field_1 = CharField()
default_field_2 = CharField()
def __init__(self, data=None, auto_id=False, field_list=[]):
Form.__init__(self, data, auto_id=auto_id)
for field in field_list:
self.fields[field[0]] = field[1]
field_list = [("field1", CharField()), ("field2", CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
"""
<tr><th>Default field 1:</th><td>
<input type="text" name="default_field_1" required></td></tr>
<tr><th>Default field 2:</th><td>
<input type="text" name="default_field_2" required></td></tr>
<tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr>
<tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>
""",
)
field_list = [("field3", CharField()), ("field4", CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
"""
<tr><th>Default field 1:</th><td>
<input type="text" name="default_field_1" required></td></tr>
<tr><th>Default field 2:</th><td>
<input type="text" name="default_field_2" required></td></tr>
<tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr>
<tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr>
""",
)
# Similarly, changes to field attributes do not persist from one Form instance
# to the next.
class Person(Form):
first_name = CharField(required=False)
last_name = CharField(required=False)
def __init__(self, names_required=False, *args, **kwargs):
super().__init__(*args, **kwargs)
if names_required:
self.fields["first_name"].required = True
self.fields["first_name"].widget.attrs["class"] = "required"
self.fields["last_name"].required = True
self.fields["last_name"].widget.attrs["class"] = "required"
f = Person(names_required=False)
self.assertEqual(
f["first_name"].field.required,
f["last_name"].field.required,
(False, False),
)
self.assertEqual(
f["first_name"].field.widget.attrs,
f["last_name"].field.widget.attrs,
({}, {}),
)
f = Person(names_required=True)
self.assertEqual(
f["first_name"].field.required, f["last_name"].field.required, (True, True)
)
self.assertEqual(
f["first_name"].field.widget.attrs,
f["last_name"].field.widget.attrs,
({"class": "reuired"}, {"class": "required"}),
)
f = Person(names_required=False)
self.assertEqual(
f["first_name"].field.required,
f["last_name"].field.required,
(False, False),
)
self.assertEqual(
f["first_name"].field.widget.attrs,
f["last_name"].field.widget.attrs,
({}, {}),
)
class Person(Form):
first_name = CharField(max_length=30)
last_name = CharField(max_length=30)
def __init__(self, name_max_length=None, *args, **kwargs):
super().__init__(*args, **kwargs)
if name_max_length:
self.fields["first_name"].max_length = name_max_length
self.fields["last_name"].max_length = name_max_length
f = Person(name_max_length=None)
self.assertEqual(
f["first_name"].field.max_length, f["last_name"].field.max_length, (30, 30)
)
f = Person(name_max_length=20)
self.assertEqual(
f["first_name"].field.max_length, f["last_name"].field.max_length, (20, 20)
)
f = Person(name_max_length=None)
self.assertEqual(
f["first_name"].field.max_length, f["last_name"].field.max_length, (30, 30)
)
# Similarly, choices do not persist from one Form instance to the next.
# Refs #15127.
class Person(Form):
first_name = CharField(required=False)
last_name = CharField(required=False)
gender = ChoiceField(choices=(("f", "Female"), ("m", "Male")))
def __init__(self, allow_unspec_gender=False, *args, **kwargs):
super().__init__(*args, **kwargs)
if allow_unspec_gender:
self.fields["gender"].choices += (("u", "Unspecified"),)
f = Person()
self.assertEqual(f["gender"].field.choices, [("f", "Female"), ("m", "Male")])
f = Person(allow_unspec_gender=True)
self.assertEqual(
f["gender"].field.choices,
[("f", "Female"), ("m", "Male"), ("u", "Unspecified")],
)
f = Person()
self.assertEqual(f["gender"].field.choices, [("f", "Female"), ("m", "Male")])
def test_validators_independence(self):
"""
The list of form field validators can be modified without polluting
other forms.
"""
class MyForm(Form):
myfield = CharField(max_length=25)
f1 = MyForm()
f2 = MyForm()
f1.fields["myfield"].validators[0] = MaxValueValidator(12)
self.assertNotEqual(
f1.fields["myfield"].validators[0], f2.fields["myfield"].validators[0]
)
def test_hidden_widget(self):
# HiddenInput widgets are displayed differently in the as_table(), as_ul())
# and as_p() output of a Form -- their verbose names are not displayed, and a
# separate row is not displayed. They're displayed in the last row of the
# form, directly after that row's form element.
class Person(Form):
first_name = CharField()
last_name = CharField()
hidden_text = CharField(widget=HiddenInput)
birthday = DateField()
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_table(),
"""
<tr><th>First name:</th><td><input type="text" name="first_name" required>
</td></tr>
<tr><th>Last name:</th><td><input type="text" name="last_name" required>
</td></tr>
<tr><th>Birthday:</th>
<td><input type="text" name="birthday" required>
<input type="hidden" name="hidden_text"></td></tr>
""",
)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>First name: <input type="text" name="first_name" required></li>
<li>Last name: <input type="text" name="last_name" required></li>
<li>Birthday: <input type="text" name="birthday" required>
<input type="hidden" name="hidden_text"></li>
""",
)
self.assertHTMLEqual(
p.as_p(),
"""
<p>First name: <input type="text" name="first_name" required></p>
<p>Last name: <input type="text" name="last_name" required></p>
<p>Birthday: <input type="text" name="birthday" required>
<input type="hidden" name="hidden_text"></p>
""",
)
self.assertHTMLEqual(
p.as_div(),
'<div>First name: <input type="text" name="first_name" required></div>'
'<div>Last name: <input type="text" name="last_name" required></div><div>'
'Birthday: <input type="text" name="birthday" required><input '
'type="hidden" name="hidden_text"></div>',
)
# With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label.
p = Person(auto_id="id_%s")
self.assertHTMLEqual(
p.as_table(),
"""<tr><th><label for="id_first_name">First name:</label></th><td>
<input type="text" name="first_name" id="id_first_name" required></td></tr>
<tr><th><label for="id_last_name">Last name:</label></th><td>
<input type="text" name="last_name" id="id_last_name" required></td></tr>
<tr><th><label for="id_birthday">Birthday:</label></th><td>
<input type="text" name="birthday" id="id_birthday" required>
<input type="hidden" name="hidden_text" id="id_hidden_text"></td></tr>""",
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" required></li>
<li><label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" required></li>
<li><label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" required>
<input type="hidden" name="hidden_text" id="id_hidden_text"></li>""",
)
self.assertHTMLEqual(
p.as_p(),
"""<p><label for="id_first_name">First name:</label>
<input type="text" name="first_name" id="id_first_name" required></p>
<p><label for="id_last_name">Last name:</label>
<input type="text" name="last_name" id="id_last_name" required></p>
<p><label for="id_birthday">Birthday:</label>
<input type="text" name="birthday" id="id_birthday" required>
<input type="hidden" name="hidden_text" id="id_hidden_text"></p>""",
)
self.assertHTMLEqual(
p.as_div(),
'<div><label for="id_first_name">First name:</label><input type="text" '
'name="first_name" id="id_first_name" required></div><div><label '
'for="id_last_name">Last name:</label><input type="text" name="last_name" '
'id="id_last_name" required></div><div><label for="id_birthday">Birthday:'
'</label><input type="text" name="birthday" id="id_birthday" required>'
'<input type="hidden" name="hidden_text" id="id_hidden_text"></div>',
)
# If a field with a HiddenInput has errors, the as_table() and as_ul() output
# will include the error message(s) with the text "(Hidden field [fieldname]) "
# prepended. This message is displayed at the top of the output, regardless of
# its field's order in the form.
p = Person(
{"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"},
auto_id=False,
)
self.assertHTMLEqual(
p.as_table(),
"""
<tr><td colspan="2">
<ul class="errorlist nonfield"><li>
(Hidden field hidden_text) This field is required.</li></ul></td></tr>
<tr><th>First name:</th><td>
<input type="text" name="first_name" value="John" required></td></tr>
<tr><th>Last name:</th><td>
<input type="text" name="last_name" value="Lennon" required></td></tr>
<tr><th>Birthday:</th><td>
<input type="text" name="birthday" value="1940-10-9" required>
<input type="hidden" name="hidden_text"></td></tr>
""",
)
self.assertHTMLEqual(
p.as_ul(),
"""
<li><ul class="errorlist nonfield"><li>
(Hidden field hidden_text) This field is required.</li></ul></li>
<li>First name: <input type="text" name="first_name" value="John" required>
</li>
<li>Last name: <input type="text" name="last_name" value="Lennon" required>
</li>
<li>Birthday: <input type="text" name="birthday" value="1940-10-9" required>
<input type="hidden" name="hidden_text"></li>
""",
)
self.assertHTMLEqual(
p.as_p(),
"""
<ul class="errorlist nonfield"><li>
(Hidden field hidden_text) This field is required.</li></ul>
<p>First name: <input type="text" name="first_name" value="John" required>
</p>
<p>Last name: <input type="text" name="last_name" value="Lennon" required>
</p>
<p>Birthday: <input type="text" name="birthday" value="1940-10-9" required>
<input type="hidden" name="hidden_text"></p>
""",
)
self.assertHTMLEqual(
p.as_div(),
'<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field '
'is required.</li></ul><div>First name: <input type="text" '
'name="first_name" value="John" required></div><div>Last name: <input '
'type="text" name="last_name" value="Lennon" required></div><div>'
'Birthday: <input type="text" name="birthday" value="1940-10-9" required>'
'<input type="hidden" name="hidden_text"></div>',
)
# A corner case: It's possible for a form to have only HiddenInputs.
class TestForm(Form):
foo = CharField(widget=HiddenInput)
bar = CharField(widget=HiddenInput)
p = TestForm(auto_id=False)
self.assertHTMLEqual(
p.as_table(),
'<input type="hidden" name="foo"><input type="hidden" name="bar">',
)
self.assertHTMLEqual(
p.as_ul(),
'<input type="hidden" name="foo"><input type="hidden" name="bar">',
)
self.assertHTMLEqual(
p.as_p(), '<input type="hidden" name="foo"><input type="hidden" name="bar">'
)
def test_field_order(self):
# A Form's fields are displayed in the same order in which they were defined.
class TestForm(Form):
field1 = CharField()
field2 = CharField()
field3 = CharField()
field4 = CharField()
field5 = CharField()
field6 = CharField()
field7 = CharField()
field8 = CharField()
field9 = CharField()
field10 = CharField()
field11 = CharField()
field12 = CharField()
field13 = CharField()
field14 = CharField()
p = TestForm(auto_id=False)
self.assertHTMLEqual(
p.as_table(),
"".join(
f"<tr><th>Field{i}:</th><td>"
f'<input type="text" name="field{i}" required></td></tr>'
for i in range(1, 15)
),
)
def test_explicit_field_order(self):
class TestFormParent(Form):
field1 = CharField()
field2 = CharField()
field4 = CharField()
field5 = CharField()
field6 = CharField()
field_order = ["field6", "field5", "field4", "field2", "field1"]
class TestForm(TestFormParent):
field3 = CharField()
field_order = ["field2", "field4", "field3", "field5", "field6"]
class TestFormRemove(TestForm):
field1 = None
class TestFormMissing(TestForm):
field_order = ["field2", "field4", "field3", "field5", "field6", "field1"]
field1 = None
class TestFormInit(TestFormParent):
field3 = CharField()
field_order = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.order_fields(field_order=TestForm.field_order)
p = TestFormParent()
self.assertEqual(list(p.fields), TestFormParent.field_order)
p = TestFormRemove()
self.assertEqual(list(p.fields), TestForm.field_order)
p = TestFormMissing()
self.assertEqual(list(p.fields), TestForm.field_order)
p = TestForm()
self.assertEqual(list(p.fields), TestFormMissing.field_order)
p = TestFormInit()
order = [*TestForm.field_order, "field1"]
self.assertEqual(list(p.fields), order)
TestForm.field_order = ["unknown"]
p = TestForm()
self.assertEqual(
list(p.fields), ["field1", "field2", "field4", "field5", "field6", "field3"]
)
def test_form_html_attributes(self):
# Some Field classes have an effect on the HTML attributes of their associated
# Widget. If you set max_length in a CharField and its associated widget is
# either a TextInput or PasswordInput, then the widget's rendered HTML will
# include the "maxlength" attribute.
class UserRegistration(Form):
username = CharField(max_length=10) # uses TextInput by default
password = CharField(max_length=10, widget=PasswordInput)
realname = CharField(
max_length=10, widget=TextInput
) # redundantly define widget, just to test
address = CharField() # no max_length defined here
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" maxlength="10" required>
</li>
<li>Password: <input type="password" name="password" maxlength="10"
required></li>
<li>Realname: <input type="text" name="realname" maxlength="10" required>
</li>
<li>Address: <input type="text" name="address" required></li>
""",
)
# If you specify a custom "attrs" that includes the "maxlength"
# attribute, the Field's max_length attribute will override whatever
# "maxlength" you specify in "attrs".
class UserRegistration(Form):
username = CharField(
max_length=10, widget=TextInput(attrs={"maxlength": 20})
)
password = CharField(max_length=10, widget=PasswordInput)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
'<li>Username: <input type="text" name="username" maxlength="10" required>'
"</li>"
'<li>Password: <input type="password" name="password" maxlength="10" '
"required></li>",
)
def test_specifying_labels(self):
# You can specify the label for a field by using the 'label' argument to a Field
# class. If you don't specify 'label', Django will use the field name with
# underscores converted to spaces, and the initial letter capitalized.
class UserRegistration(Form):
username = CharField(max_length=10, label="Your username")
password1 = CharField(widget=PasswordInput)
password2 = CharField(widget=PasswordInput, label="Contraseña (de nuevo)")
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Your username:
<input type="text" name="username" maxlength="10" required></li>
<li>Password1: <input type="password" name="password1" required></li>
<li>Contraseña (de nuevo):
<input type="password" name="password2" required></li>
""",
)
# Labels for as_* methods will only end in a colon if they don't end in other
# punctuation already.
class Questions(Form):
q1 = CharField(label="The first question")
q2 = CharField(label="What is your name?")
q3 = CharField(label="The answer to life is:")
q4 = CharField(label="Answer this question!")
q5 = CharField(label="The last question. Period.")
self.assertHTMLEqual(
Questions(auto_id=False).as_p(),
"""<p>The first question: <input type="text" name="q1" required></p>
<p>What is your name? <input type="text" name="q2" required></p>
<p>The answer to life is: <input type="text" name="q3" required></p>
<p>Answer this question! <input type="text" name="q4" required></p>
<p>The last question. Period. <input type="text" name="q5" required></p>""",
)
self.assertHTMLEqual(
Questions().as_p(),
"""
<p><label for="id_q1">The first question:</label>
<input type="text" name="q1" id="id_q1" required></p>
<p><label for="id_q2">What is your name?</label>
<input type="text" name="q2" id="id_q2" required></p>
<p><label for="id_q3">The answer to life is:</label>
<input type="text" name="q3" id="id_q3" required></p>
<p><label for="id_q4">Answer this question!</label>
<input type="text" name="q4" id="id_q4" required></p>
<p><label for="id_q5">The last question. Period.</label>
<input type="text" name="q5" id="id_q5" required></p>
""",
)
# If a label is set to the empty string for a field, that field won't
# get a label.
class UserRegistration(Form):
username = CharField(max_length=10, label="")
password = CharField(widget=PasswordInput)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li> <input type="text" name="username" maxlength="10" required></li>
<li>Password: <input type="password" name="password" required></li>""",
)
p = UserRegistration(auto_id="id_%s")
self.assertHTMLEqual(
p.as_ul(),
"""
<li>
<input id="id_username" type="text" name="username" maxlength="10" required>
</li>
<li><label for="id_password">Password:</label>
<input type="password" name="password" id="id_password" required></li>
""",
)
# If label is None, Django will auto-create the label from the field name. This
# is default behavior.
class UserRegistration(Form):
username = CharField(max_length=10, label=None)
password = CharField(widget=PasswordInput)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
'<li>Username: <input type="text" name="username" maxlength="10" required>'
"</li>"
'<li>Password: <input type="password" name="password" required></li>',
)
p = UserRegistration(auto_id="id_%s")
self.assertHTMLEqual(
p.as_ul(),
"""<li><label for="id_username">Username:</label>
<input id="id_username" type="text" name="username" maxlength="10" required></li>
<li><label for="id_password">Password:</label>
<input type="password" name="password" id="id_password" required></li>""",
)
def test_label_suffix(self):
# You can specify the 'label_suffix' argument to a Form class to modify
# the punctuation symbol used at the end of a label. By default, the
# colon (:) is used, and is only appended to the label if the label
# doesn't already end with a punctuation symbol: ., !, ? or :. If you
# specify a different suffix, it will be appended regardless of the
# last character of the label.
class FavoriteForm(Form):
color = CharField(label="Favorite color?")
animal = CharField(label="Favorite animal")
answer = CharField(label="Secret answer", label_suffix=" =")
f = FavoriteForm(auto_id=False)
self.assertHTMLEqual(
f.as_ul(),
"""<li>Favorite color? <input type="text" name="color" required></li>
<li>Favorite animal: <input type="text" name="animal" required></li>
<li>Secret answer = <input type="text" name="answer" required></li>""",
)
f = FavoriteForm(auto_id=False, label_suffix="?")
self.assertHTMLEqual(
f.as_ul(),
"""<li>Favorite color? <input type="text" name="color" required></li>
<li>Favorite animal? <input type="text" name="animal" required></li>
<li>Secret answer = <input type="text" name="answer" required></li>""",
)
f = FavoriteForm(auto_id=False, label_suffix="")
self.assertHTMLEqual(
f.as_ul(),
"""<li>Favorite color? <input type="text" name="color" required></li>
<li>Favorite animal <input type="text" name="animal" required></li>
<li>Secret answer = <input type="text" name="answer" required></li>""",
)
f = FavoriteForm(auto_id=False, label_suffix="\u2192")
self.assertHTMLEqual(
f.as_ul(),
'<li>Favorite color? <input type="text" name="color" required></li>\n'
"<li>Favorite animal\u2192 "
'<input type="text" name="animal" required></li>\n'
'<li>Secret answer = <input type="text" name="answer" required></li>',
)
def test_initial_data(self):
# You can specify initial data for a field by using the 'initial' argument to a
# Field class. This initial data is displayed when a Form is rendered with *no*
# data. It is not displayed when a Form is rendered with any data (including an
# empty dictionary). Also, the initial value is *not* used if data for a
# particular required field isn't provided.
class UserRegistration(Form):
username = CharField(max_length=10, initial="django")
password = CharField(widget=PasswordInput)
# Here, we're not submitting any data, so the initial value will be displayed.)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="django"
maxlength="10" required></li>
<li>Password: <input type="password" name="password" required></li>
""",
)
# Here, we're submitting data, so the initial value will *not* be displayed.
p = UserRegistration({}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required></li>""",
)
p = UserRegistration({"username": ""}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required></li>""",
)
p = UserRegistration({"username": "foo"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="foo" maxlength="10"
required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required></li>
""",
)
# An 'initial' value is *not* used as a fallback if data is not
# provided. In this example, we don't provide a value for 'username',
# and the form raises a validation error rather than using the initial
# value for 'username'.
p = UserRegistration({"password": "secret"})
self.assertEqual(p.errors["username"], ["This field is required."])
self.assertFalse(p.is_valid())
def test_dynamic_initial_data(self):
# The previous technique dealt with "hard-coded" initial data, but it's also
# possible to specify initial data after you've already created the Form class
# (i.e., at runtime). Use the 'initial' parameter to the Form constructor. This
# should be a dictionary containing initial values for one or more fields in the
# form, keyed by field name.
class UserRegistration(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
# Here, we're not submitting any data, so the initial value will be displayed.)
p = UserRegistration(initial={"username": "django"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="django"
maxlength="10" required></li>
<li>Password: <input type="password" name="password" required></li>
""",
)
p = UserRegistration(initial={"username": "stephane"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="stephane"
maxlength="10" required></li>
<li>Password: <input type="password" name="password" required></li>
""",
)
# The 'initial' parameter is meaningless if you pass data.
p = UserRegistration({}, initial={"username": "django"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required></li>""",
)
p = UserRegistration(
{"username": ""}, initial={"username": "django"}, auto_id=False
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required></li>""",
)
p = UserRegistration(
{"username": "foo"}, initial={"username": "django"}, auto_id=False
)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="foo" maxlength="10"
required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required></li>
""",
)
# A dynamic 'initial' value is *not* used as a fallback if data is not provided.
# In this example, we don't provide a value for 'username', and the
# form raises a validation error rather than using the initial value
# for 'username'.
p = UserRegistration({"password": "secret"}, initial={"username": "django"})
self.assertEqual(p.errors["username"], ["This field is required."])
self.assertFalse(p.is_valid())
# If a Form defines 'initial' *and* 'initial' is passed as a parameter
# to Form(), then the latter will get precedence.
class UserRegistration(Form):
username = CharField(max_length=10, initial="django")
password = CharField(widget=PasswordInput)
p = UserRegistration(initial={"username": "babik"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="babik"
maxlength="10" required></li>
<li>Password: <input type="password" name="password" required></li>
""",
)
def test_callable_initial_data(self):
# The previous technique dealt with raw values as initial data, but it's also
# possible to specify callable data.
class UserRegistration(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
options = MultipleChoiceField(
choices=[("f", "foo"), ("b", "bar"), ("w", "whiz")]
)
# We need to define functions that get called later.)
def initial_django():
return "django"
def initial_stephane():
return "stephane"
def initial_options():
return ["f", "b"]
def initial_other_options():
return ["b", "w"]
# Here, we're not submitting any data, so the initial value will be displayed.)
p = UserRegistration(
initial={"username": initial_django, "options": initial_options},
auto_id=False,
)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="django"
maxlength="10" required></li>
<li>Password: <input type="password" name="password" required></li>
<li>Options: <select multiple name="options" required>
<option value="f" selected>foo</option>
<option value="b" selected>bar</option>
<option value="w">whiz</option>
</select></li>
""",
)
# The 'initial' parameter is meaningless if you pass data.
p = UserRegistration(
{},
initial={"username": initial_django, "options": initial_options},
auto_id=False,
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Options: <select multiple name="options" required>
<option value="f">foo</option>
<option value="b">bar</option>
<option value="w">whiz</option>
</select></li>""",
)
p = UserRegistration(
{"username": ""}, initial={"username": initial_django}, auto_id=False
)
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist"><li>This field is required.</li></ul>
Username: <input type="text" name="username" maxlength="10" required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Options: <select multiple name="options" required>
<option value="f">foo</option>
<option value="b">bar</option>
<option value="w">whiz</option>
</select></li>""",
)
p = UserRegistration(
{"username": "foo", "options": ["f", "b"]},
initial={"username": initial_django},
auto_id=False,
)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="foo" maxlength="10"
required></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>
Password: <input type="password" name="password" required></li>
<li>Options: <select multiple name="options" required>
<option value="f" selected>foo</option>
<option value="b" selected>bar</option>
<option value="w">whiz</option>
</select></li>
""",
)
# A callable 'initial' value is *not* used as a fallback if data is not
# provided. In this example, we don't provide a value for 'username',
# and the form raises a validation error rather than using the initial
# value for 'username'.
p = UserRegistration(
{"password": "secret"},
initial={"username": initial_django, "options": initial_options},
)
self.assertEqual(p.errors["username"], ["This field is required."])
self.assertFalse(p.is_valid())
# If a Form defines 'initial' *and* 'initial' is passed as a parameter
# to Form(), then the latter will get precedence.
class UserRegistration(Form):
username = CharField(max_length=10, initial=initial_django)
password = CharField(widget=PasswordInput)
options = MultipleChoiceField(
choices=[("f", "foo"), ("b", "bar"), ("w", "whiz")],
initial=initial_other_options,
)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="django"
maxlength="10" required></li>
<li>Password: <input type="password" name="password" required></li>
<li>Options: <select multiple name="options" required>
<option value="f">foo</option>
<option value="b" selected>bar</option>
<option value="w" selected>whiz</option>
</select></li>
""",
)
p = UserRegistration(
initial={"username": initial_stephane, "options": initial_options},
auto_id=False,
)
self.assertHTMLEqual(
p.as_ul(),
"""
<li>Username: <input type="text" name="username" value="stephane"
maxlength="10" required></li>
<li>Password: <input type="password" name="password" required></li>
<li>Options: <select multiple name="options" required>
<option value="f" selected>foo</option>
<option value="b" selected>bar</option>
<option value="w">whiz</option>
</select></li>
""",
)
def test_get_initial_for_field(self):
now = datetime.datetime(2006, 10, 25, 14, 30, 45, 123456)
class PersonForm(Form):
first_name = CharField(initial="John")
last_name = CharField(initial="Doe")
age = IntegerField()
occupation = CharField(initial=lambda: "Unknown")
dt_fixed = DateTimeField(initial=now)
dt_callable = DateTimeField(initial=lambda: now)
form = PersonForm(initial={"first_name": "Jane"})
cases = [
("age", None),
("last_name", "Doe"),
# Form.initial overrides Field.initial.
("first_name", "Jane"),
# Callables are evaluated.
("occupation", "Unknown"),
# Microseconds are removed from datetimes.
("dt_fixed", datetime.datetime(2006, 10, 25, 14, 30, 45)),
("dt_callable", datetime.datetime(2006, 10, 25, 14, 30, 45)),
]
for field_name, expected in cases:
with self.subTest(field_name=field_name):
field = form.fields[field_name]
actual = form.get_initial_for_field(field, field_name)
self.assertEqual(actual, expected)
def test_changed_data(self):
class Person(Form):
first_name = CharField(initial="Hans")
last_name = CharField(initial="Greatel")
birthday = DateField(initial=datetime.date(1974, 8, 16))
p = Person(
data={"first_name": "Hans", "last_name": "Scrmbl", "birthday": "1974-08-16"}
)
self.assertTrue(p.is_valid())
self.assertNotIn("first_name", p.changed_data)
self.assertIn("last_name", p.changed_data)
self.assertNotIn("birthday", p.changed_data)
# A field raising ValidationError is always in changed_data
class PedanticField(forms.Field):
def to_python(self, value):
raise ValidationError("Whatever")
class Person2(Person):
pedantic = PedanticField(initial="whatever", show_hidden_initial=True)
p = Person2(
data={
"first_name": "Hans",
"last_name": "Scrmbl",
"birthday": "1974-08-16",
"initial-pedantic": "whatever",
}
)
self.assertFalse(p.is_valid())
self.assertIn("pedantic", p.changed_data)
def test_boundfield_values(self):
# It's possible to get to the value which would be used for rendering
# the widget for a field by using the BoundField's value method.
class UserRegistration(Form):
username = CharField(max_length=10, initial="djangonaut")
password = CharField(widget=PasswordInput)
unbound = UserRegistration()
bound = UserRegistration({"password": "foo"})
self.assertIsNone(bound["username"].value())
self.assertEqual(unbound["username"].value(), "djangonaut")
self.assertEqual(bound["password"].value(), "foo")
self.assertIsNone(unbound["password"].value())
def test_boundfield_initial_called_once(self):
"""
Multiple calls to BoundField().value() in an unbound form should return
the same result each time (#24391).
"""
class MyForm(Form):
name = CharField(max_length=10, initial=uuid.uuid4)
form = MyForm()
name = form["name"]
self.assertEqual(name.value(), name.value())
# BoundField is also cached
self.assertIs(form["name"], name)
def test_boundfield_value_disabled_callable_initial(self):
class PersonForm(Form):
name = CharField(initial=lambda: "John Doe", disabled=True)
# Without form data.
form = PersonForm()
self.assertEqual(form["name"].value(), "John Doe")
# With form data. As the field is disabled, the value should not be
# affected by the form data.
form = PersonForm({})
self.assertEqual(form["name"].value(), "John Doe")
def test_custom_boundfield(self):
class CustomField(CharField):
def get_bound_field(self, form, name):
return (form, name)
class SampleForm(Form):
name = CustomField()
f = SampleForm()
self.assertEqual(f["name"], (f, "name"))
def test_initial_datetime_values(self):
now = datetime.datetime.now()
# Nix microseconds (since they should be ignored). #22502
now_no_ms = now.replace(microsecond=0)
if now == now_no_ms:
now = now.replace(microsecond=1)
def delayed_now():
return now
def delayed_now_time():
return now.time()
class HiddenInputWithoutMicrosec(HiddenInput):
supports_microseconds = False
class TextInputWithoutMicrosec(TextInput):
supports_microseconds = False
class DateTimeForm(Form):
# Test a non-callable.
fixed = DateTimeField(initial=now)
auto_timestamp = DateTimeField(initial=delayed_now)
auto_time_only = TimeField(initial=delayed_now_time)
supports_microseconds = DateTimeField(initial=delayed_now, widget=TextInput)
hi_default_microsec = DateTimeField(initial=delayed_now, widget=HiddenInput)
hi_without_microsec = DateTimeField(
initial=delayed_now, widget=HiddenInputWithoutMicrosec
)
ti_without_microsec = DateTimeField(
initial=delayed_now, widget=TextInputWithoutMicrosec
)
unbound = DateTimeForm()
cases = [
("fixed", now_no_ms),
("auto_timestamp", now_no_ms),
("auto_time_only", now_no_ms.time()),
("supports_microseconds", now),
("hi_default_microsec", now),
("hi_without_microsec", now_no_ms),
("ti_without_microsec", now_no_ms),
]
for field_name, expected in cases:
with self.subTest(field_name=field_name):
actual = unbound[field_name].value()
self.assertEqual(actual, expected)
# Also check get_initial_for_field().
field = unbound.fields[field_name]
actual = unbound.get_initial_for_field(field, field_name)
self.assertEqual(actual, expected)
def get_datetime_form_with_callable_initial(self, disabled, microseconds=0):
class FakeTime:
def __init__(self):
self.elapsed_seconds = 0
def now(self):
self.elapsed_seconds += 1
return datetime.datetime(
2006,
10,
25,
14,
30,
45 + self.elapsed_seconds,
microseconds,
)
class DateTimeForm(forms.Form):
dt = DateTimeField(initial=FakeTime().now, disabled=disabled)
return DateTimeForm({})
def test_datetime_clean_disabled_callable_initial_microseconds(self):
"""
Cleaning a form with a disabled DateTimeField and callable initial
removes microseconds.
"""
form = self.get_datetime_form_with_callable_initial(
disabled=True,
microseconds=123456,
)
self.assertEqual(form.errors, {})
self.assertEqual(
form.cleaned_data,
{
"dt": datetime.datetime(2006, 10, 25, 14, 30, 46),
},
)
def test_datetime_clean_disabled_callable_initial_bound_field(self):
"""
The cleaned value for a form with a disabled DateTimeField and callable
initial matches the bound field's cached initial value.
"""
form = self.get_datetime_form_with_callable_initial(disabled=True)
self.assertEqual(form.errors, {})
cleaned = form.cleaned_data["dt"]
self.assertEqual(cleaned, datetime.datetime(2006, 10, 25, 14, 30, 46))
bf = form["dt"]
self.assertEqual(cleaned, bf.initial)
def test_datetime_changed_data_callable_with_microseconds(self):
class DateTimeForm(forms.Form):
dt = DateTimeField(
initial=lambda: datetime.datetime(2006, 10, 25, 14, 30, 45, 123456),
disabled=True,
)
form = DateTimeForm({"dt": "2006-10-25 14:30:45"})
self.assertEqual(form.changed_data, [])
def test_help_text(self):
# You can specify descriptive text for a field by using the 'help_text'
# argument.
class UserRegistration(Form):
username = CharField(max_length=10, help_text="e.g., [email protected]")
password = CharField(
widget=PasswordInput, help_text="Wählen Sie mit Bedacht."
)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" maxlength="10" required>
<span class="helptext">e.g., [email protected]</span></li>
<li>Password: <input type="password" name="password" required>
<span class="helptext">Wählen Sie mit Bedacht.</span></li>""",
)
self.assertHTMLEqual(
p.as_p(),
"""<p>Username: <input type="text" name="username" maxlength="10" required>
<span class="helptext">e.g., [email protected]</span></p>
<p>Password: <input type="password" name="password" required>
<span class="helptext">Wählen Sie mit Bedacht.</span></p>""",
)
self.assertHTMLEqual(
p.as_table(),
"""
<tr><th>Username:</th><td>
<input type="text" name="username" maxlength="10" required><br>
<span class="helptext">e.g., [email protected]</span></td></tr>
<tr><th>Password:</th><td><input type="password" name="password" required>
<br>
<span class="helptext">Wählen Sie mit Bedacht.</span></td></tr>""",
)
self.assertHTMLEqual(
p.as_div(),
'<div>Username: <div class="helptext">e.g., [email protected]</div>'
'<input type="text" name="username" maxlength="10" required></div>'
'<div>Password: <div class="helptext">Wählen Sie mit Bedacht.</div>'
'<input type="password" name="password" required></div>',
)
# The help text is displayed whether or not data is provided for the form.
p = UserRegistration({"username": "foo"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
'<li>Username: <input type="text" name="username" value="foo" '
'maxlength="10" required>'
'<span class="helptext">e.g., [email protected]</span></li>'
'<li><ul class="errorlist"><li>This field is required.</li></ul>'
'Password: <input type="password" name="password" required>'
'<span class="helptext">Wählen Sie mit Bedacht.</span></li>',
)
# help_text is not displayed for hidden fields. It can be used for documentation
# purposes, though.
class UserRegistration(Form):
username = CharField(max_length=10, help_text="e.g., [email protected]")
password = CharField(widget=PasswordInput)
next = CharField(
widget=HiddenInput, initial="/", help_text="Redirect destination"
)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>Username: <input type="text" name="username" maxlength="10" required>
<span class="helptext">e.g., [email protected]</span></li>
<li>Password: <input type="password" name="password" required>
<input type="hidden" name="next" value="/"></li>""",
)
def test_help_text_html_safe(self):
"""help_text should not be escaped."""
class UserRegistration(Form):
username = CharField(max_length=10, help_text="e.g., [email protected]")
password = CharField(
widget=PasswordInput,
help_text="Help text is <strong>escaped</strong>.",
)
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
'<li>Username: <input type="text" name="username" maxlength="10" required>'
'<span class="helptext">e.g., [email protected]</span></li>'
'<li>Password: <input type="password" name="password" required>'
'<span class="helptext">Help text is <strong>escaped</strong>.</span></li>',
)
self.assertHTMLEqual(
p.as_p(),
'<p>Username: <input type="text" name="username" maxlength="10" required>'
'<span class="helptext">e.g., [email protected]</span></p>'
'<p>Password: <input type="password" name="password" required>'
'<span class="helptext">Help text is <strong>escaped</strong>.</span></p>',
)
self.assertHTMLEqual(
p.as_table(),
"<tr><th>Username:</th><td>"
'<input type="text" name="username" maxlength="10" required><br>'
'<span class="helptext">e.g., [email protected]</span></td></tr>'
"<tr><th>Password:</th><td>"
'<input type="password" name="password" required><br>'
'<span class="helptext">Help text is <strong>escaped</strong>.</span>'
"</td></tr>",
)
def test_subclassing_forms(self):
# You can subclass a Form to add fields. The resulting form subclass will have
# all of the fields of the parent Form, plus whichever fields you define in the
# subclass.
class Person(Form):
first_name = CharField()
last_name = CharField()
birthday = DateField()
class Musician(Person):
instrument = CharField()
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
"""<li>First name: <input type="text" name="first_name" required></li>
<li>Last name: <input type="text" name="last_name" required></li>
<li>Birthday: <input type="text" name="birthday" required></li>""",
)
m = Musician(auto_id=False)
self.assertHTMLEqual(
m.as_ul(),
"""<li>First name: <input type="text" name="first_name" required></li>
<li>Last name: <input type="text" name="last_name" required></li>
<li>Birthday: <input type="text" name="birthday" required></li>
<li>Instrument: <input type="text" name="instrument" required></li>""",
)
# Yes, you can subclass multiple forms. The fields are added in the order in
# which the parent classes are listed.
class Person(Form):
first_name = CharField()
last_name = CharField()
birthday = DateField()
class Instrument(Form):
instrument = CharField()
class Beatle(Person, Instrument):
haircut_type = CharField()
b = Beatle(auto_id=False)
self.assertHTMLEqual(
b.as_ul(),
"""<li>Instrument: <input type="text" name="instrument" required></li>
<li>First name: <input type="text" name="first_name" required></li>
<li>Last name: <input type="text" name="last_name" required></li>
<li>Birthday: <input type="text" name="birthday" required></li>
<li>Haircut type: <input type="text" name="haircut_type" required></li>""",
)
def test_forms_with_prefixes(self):
# Sometimes it's necessary to have multiple forms display on the same
# HTML page, or multiple copies of the same form. We can accomplish
# this with form prefixes. Pass the keyword argument 'prefix' to the
# Form constructor to use this feature. This value will be prepended to
# each HTML form field name. One way to think about this is "namespaces
# for HTML forms". Notice that in the data argument, each field's key
# has the prefix, in this case 'person1', prepended to the actual field
# name.
class Person(Form):
first_name = CharField()
last_name = CharField()
birthday = DateField()
data = {
"person1-first_name": "John",
"person1-last_name": "Lennon",
"person1-birthday": "1940-10-9",
}
p = Person(data, prefix="person1")
self.assertHTMLEqual(
p.as_ul(),
"""
<li><label for="id_person1-first_name">First name:</label>
<input type="text" name="person1-first_name" value="John"
id="id_person1-first_name" required></li>
<li><label for="id_person1-last_name">Last name:</label>
<input type="text" name="person1-last_name" value="Lennon"
id="id_person1-last_name" required></li>
<li><label for="id_person1-birthday">Birthday:</label>
<input type="text" name="person1-birthday" value="1940-10-9"
id="id_person1-birthday" required></li>
""",
)
self.assertHTMLEqual(
str(p["first_name"]),
'<input type="text" name="person1-first_name" value="John" '
'id="id_person1-first_name" required>',
)
self.assertHTMLEqual(
str(p["last_name"]),
'<input type="text" name="person1-last_name" value="Lennon" '
'id="id_person1-last_name" required>',
)
self.assertHTMLEqual(
str(p["birthday"]),
'<input type="text" name="person1-birthday" value="1940-10-9" '
'id="id_person1-birthday" required>',
)
self.assertEqual(p.errors, {})
self.assertTrue(p.is_valid())
self.assertEqual(p.cleaned_data["first_name"], "John")
self.assertEqual(p.cleaned_data["last_name"], "Lennon")
self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
# Let's try submitting some bad data to make sure form.errors and field.errors
# work as expected.
data = {
"person1-first_name": "",
"person1-last_name": "",
"person1-birthday": "",
}
p = Person(data, prefix="person1")
self.assertEqual(p.errors["first_name"], ["This field is required."])
self.assertEqual(p.errors["last_name"], ["This field is required."])
self.assertEqual(p.errors["birthday"], ["This field is required."])
self.assertEqual(p["first_name"].errors, ["This field is required."])
# Accessing a nonexistent field.
with self.assertRaises(KeyError):
p["person1-first_name"].errors
# In this example, the data doesn't have a prefix, but the form requires it, so
# the form doesn't "see" the fields.
data = {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"}
p = Person(data, prefix="person1")
self.assertEqual(p.errors["first_name"], ["This field is required."])
self.assertEqual(p.errors["last_name"], ["This field is required."])
self.assertEqual(p.errors["birthday"], ["This field is required."])
# With prefixes, a single data dictionary can hold data for multiple instances
# of the same form.
data = {
"person1-first_name": "John",
"person1-last_name": "Lennon",
"person1-birthday": "1940-10-9",
"person2-first_name": "Jim",
"person2-last_name": "Morrison",
"person2-birthday": "1943-12-8",
}
p1 = Person(data, prefix="person1")
self.assertTrue(p1.is_valid())
self.assertEqual(p1.cleaned_data["first_name"], "John")
self.assertEqual(p1.cleaned_data["last_name"], "Lennon")
self.assertEqual(p1.cleaned_data["birthday"], datetime.date(1940, 10, 9))
p2 = Person(data, prefix="person2")
self.assertTrue(p2.is_valid())
self.assertEqual(p2.cleaned_data["first_name"], "Jim")
self.assertEqual(p2.cleaned_data["last_name"], "Morrison")
self.assertEqual(p2.cleaned_data["birthday"], datetime.date(1943, 12, 8))
# By default, forms append a hyphen between the prefix and the field name, but a
# form can alter that behavior by implementing the add_prefix() method. This
# method takes a field name and returns the prefixed field, according to
# self.prefix.
class Person(Form):
first_name = CharField()
last_name = CharField()
birthday = DateField()
def add_prefix(self, field_name):
return (
"%s-prefix-%s" % (self.prefix, field_name)
if self.prefix
else field_name
)
p = Person(prefix="foo")
self.assertHTMLEqual(
p.as_ul(),
"""
<li><label for="id_foo-prefix-first_name">First name:</label>
<input type="text" name="foo-prefix-first_name"
id="id_foo-prefix-first_name" required></li>
<li><label for="id_foo-prefix-last_name">Last name:</label>
<input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name"
required></li>
<li><label for="id_foo-prefix-birthday">Birthday:</label>
<input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday"
required></li>
""",
)
data = {
"foo-prefix-first_name": "John",
"foo-prefix-last_name": "Lennon",
"foo-prefix-birthday": "1940-10-9",
}
p = Person(data, prefix="foo")
self.assertTrue(p.is_valid())
self.assertEqual(p.cleaned_data["first_name"], "John")
self.assertEqual(p.cleaned_data["last_name"], "Lennon")
self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
def test_class_prefix(self):
# Prefix can be also specified at the class level.
class Person(Form):
first_name = CharField()
prefix = "foo"
p = Person()
self.assertEqual(p.prefix, "foo")
p = Person(prefix="bar")
self.assertEqual(p.prefix, "bar")
def test_forms_with_null_boolean(self):
# NullBooleanField is a bit of a special case because its presentation (widget)
# is different than its data. This is handled transparently, though.
class Person(Form):
name = CharField()
is_cool = NullBooleanField()
p = Person({"name": "Joe"}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown" selected>Unknown</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>""",
)
p = Person({"name": "Joe", "is_cool": "1"}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown" selected>Unknown</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>""",
)
p = Person({"name": "Joe", "is_cool": "2"}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown">Unknown</option>
<option value="true" selected>Yes</option>
<option value="false">No</option>
</select>""",
)
p = Person({"name": "Joe", "is_cool": "3"}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown">Unknown</option>
<option value="true">Yes</option>
<option value="false" selected>No</option>
</select>""",
)
p = Person({"name": "Joe", "is_cool": True}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown">Unknown</option>
<option value="true" selected>Yes</option>
<option value="false">No</option>
</select>""",
)
p = Person({"name": "Joe", "is_cool": False}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown">Unknown</option>
<option value="true">Yes</option>
<option value="false" selected>No</option>
</select>""",
)
p = Person({"name": "Joe", "is_cool": "unknown"}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown" selected>Unknown</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>""",
)
p = Person({"name": "Joe", "is_cool": "true"}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown">Unknown</option>
<option value="true" selected>Yes</option>
<option value="false">No</option>
</select>""",
)
p = Person({"name": "Joe", "is_cool": "false"}, auto_id=False)
self.assertHTMLEqual(
str(p["is_cool"]),
"""<select name="is_cool">
<option value="unknown">Unknown</option>
<option value="true">Yes</option>
<option value="false" selected>No</option>
</select>""",
)
def test_forms_with_file_fields(self):
# FileFields are a special case because they take their data from the
# request.FILES, not request.POST.
class FileForm(Form):
file1 = FileField()
f = FileForm(auto_id=False)
self.assertHTMLEqual(
f.as_table(),
"<tr><th>File1:</th><td>"
'<input type="file" name="file1" required></td></tr>',
)
f = FileForm(data={}, files={}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
"<tr><th>File1:</th><td>"
'<ul class="errorlist"><li>This field is required.</li></ul>'
'<input type="file" name="file1" required></td></tr>',
)
f = FileForm(
data={}, files={"file1": SimpleUploadedFile("name", b"")}, auto_id=False
)
self.assertHTMLEqual(
f.as_table(),
"<tr><th>File1:</th><td>"
'<ul class="errorlist"><li>The submitted file is empty.</li></ul>'
'<input type="file" name="file1" required></td></tr>',
)
f = FileForm(
data={}, files={"file1": "something that is not a file"}, auto_id=False
)
self.assertHTMLEqual(
f.as_table(),
"<tr><th>File1:</th><td>"
'<ul class="errorlist"><li>No file was submitted. Check the '
"encoding type on the form.</li></ul>"
'<input type="file" name="file1" required></td></tr>',
)
f = FileForm(
data={},
files={"file1": SimpleUploadedFile("name", b"some content")},
auto_id=False,
)
self.assertHTMLEqual(
f.as_table(),
"<tr><th>File1:</th><td>"
'<input type="file" name="file1" required></td></tr>',
)
self.assertTrue(f.is_valid())
file1 = SimpleUploadedFile(
"我隻氣墊船裝滿晒鱔.txt", "मेरी मँडराने वाली नाव सर्पमीनों से भरी ह".encode()
)
f = FileForm(data={}, files={"file1": file1}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
"<tr><th>File1:</th><td>"
'<input type="file" name="file1" required></td></tr>',
)
# A required file field with initial data should not contain the
# required HTML attribute. The file input is left blank by the user to
# keep the existing, initial value.
f = FileForm(initial={"file1": "resume.txt"}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
'<tr><th>File1:</th><td><input type="file" name="file1"></td></tr>',
)
def test_filefield_initial_callable(self):
class FileForm(forms.Form):
file1 = forms.FileField(initial=lambda: "resume.txt")
f = FileForm({})
self.assertEqual(f.errors, {})
self.assertEqual(f.cleaned_data["file1"], "resume.txt")
def test_filefield_with_fileinput_required(self):
class FileForm(Form):
file1 = forms.FileField(widget=FileInput)
f = FileForm(auto_id=False)
self.assertHTMLEqual(
f.as_table(),
"<tr><th>File1:</th><td>"
'<input type="file" name="file1" required></td></tr>',
)
# A required file field with initial data doesn't contain the required
# HTML attribute. The file input is left blank by the user to keep the
# existing, initial value.
f = FileForm(initial={"file1": "resume.txt"}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
'<tr><th>File1:</th><td><input type="file" name="file1"></td></tr>',
)
def test_empty_permitted(self):
# Sometimes (pretty much in formsets) we want to allow a form to pass validation
# if it is completely empty. We can accomplish this by using the empty_permitted
# argument to a form constructor.
class SongForm(Form):
artist = CharField()
name = CharField()
# First let's show what happens id empty_permitted=False (the default):
data = {"artist": "", "song": ""}
form = SongForm(data, empty_permitted=False)
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{
"name": ["This field is required."],
"artist": ["This field is required."],
},
)
self.assertEqual(form.cleaned_data, {})
# Now let's show what happens when empty_permitted=True and the form is empty.
form = SongForm(data, empty_permitted=True, use_required_attribute=False)
self.assertTrue(form.is_valid())
self.assertEqual(form.errors, {})
self.assertEqual(form.cleaned_data, {})
# But if we fill in data for one of the fields, the form is no longer empty and
# the whole thing must pass validation.
data = {"artist": "The Doors", "song": ""}
form = SongForm(data, empty_permitted=False)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {"name": ["This field is required."]})
self.assertEqual(form.cleaned_data, {"artist": "The Doors"})
# If a field is not given in the data then None is returned for its data. Lets
# make sure that when checking for empty_permitted that None is treated
# accordingly.
data = {"artist": None, "song": ""}
form = SongForm(data, empty_permitted=True, use_required_attribute=False)
self.assertTrue(form.is_valid())
# However, we *really* need to be sure we are checking for None as any data in
# initial that returns False on a boolean call needs to be treated literally.
class PriceForm(Form):
amount = FloatField()
qty = IntegerField()
data = {"amount": "0.0", "qty": ""}
form = PriceForm(
data,
initial={"amount": 0.0},
empty_permitted=True,
use_required_attribute=False,
)
self.assertTrue(form.is_valid())
def test_empty_permitted_and_use_required_attribute(self):
msg = (
"The empty_permitted and use_required_attribute arguments may not "
"both be True."
)
with self.assertRaisesMessage(ValueError, msg):
Person(empty_permitted=True, use_required_attribute=True)
def test_extracting_hidden_and_visible(self):
class SongForm(Form):
token = CharField(widget=HiddenInput)
artist = CharField()
name = CharField()
form = SongForm()
self.assertEqual([f.name for f in form.hidden_fields()], ["token"])
self.assertEqual([f.name for f in form.visible_fields()], ["artist", "name"])
def test_hidden_initial_gets_id(self):
class MyForm(Form):
field1 = CharField(max_length=50, show_hidden_initial=True)
self.assertHTMLEqual(
MyForm().as_table(),
'<tr><th><label for="id_field1">Field1:</label></th><td>'
'<input id="id_field1" type="text" name="field1" maxlength="50" required>'
'<input type="hidden" name="initial-field1" id="initial-id_field1">'
"</td></tr>",
)
def test_error_html_required_html_classes(self):
class Person(Form):
name = CharField()
is_cool = NullBooleanField()
email = EmailField(required=False)
age = IntegerField()
p = Person({})
p.error_css_class = "error"
p.required_css_class = "required"
self.assertHTMLEqual(
p.as_ul(),
"""
<li class="required error"><ul class="errorlist">
<li>This field is required.</li></ul>
<label class="required" for="id_name">Name:</label>
<input type="text" name="name" id="id_name" required></li>
<li class="required">
<label class="required" for="id_is_cool">Is cool:</label>
<select name="is_cool" id="id_is_cool">
<option value="unknown" selected>Unknown</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select></li>
<li><label for="id_email">Email:</label>
<input type="email" name="email" id="id_email"></li>
<li class="required error"><ul class="errorlist">
<li>This field is required.</li></ul>
<label class="required" for="id_age">Age:</label>
<input type="number" name="age" id="id_age" required></li>""",
)
self.assertHTMLEqual(
p.as_p(),
"""
<ul class="errorlist"><li>This field is required.</li></ul>
<p class="required error">
<label class="required" for="id_name">Name:</label>
<input type="text" name="name" id="id_name" required></p>
<p class="required">
<label class="required" for="id_is_cool">Is cool:</label>
<select name="is_cool" id="id_is_cool">
<option value="unknown" selected>Unknown</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select></p>
<p><label for="id_email">Email:</label>
<input type="email" name="email" id="id_email"></p>
<ul class="errorlist"><li>This field is required.</li></ul>
<p class="required error"><label class="required" for="id_age">Age:</label>
<input type="number" name="age" id="id_age" required></p>
""",
)
self.assertHTMLEqual(
p.as_table(),
"""<tr class="required error">
<th><label class="required" for="id_name">Name:</label></th>
<td><ul class="errorlist"><li>This field is required.</li></ul>
<input type="text" name="name" id="id_name" required></td></tr>
<tr class="required"><th><label class="required" for="id_is_cool">Is cool:</label></th>
<td><select name="is_cool" id="id_is_cool">
<option value="unknown" selected>Unknown</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select></td></tr>
<tr><th><label for="id_email">Email:</label></th><td>
<input type="email" name="email" id="id_email"></td></tr>
<tr class="required error"><th><label class="required" for="id_age">Age:</label></th>
<td><ul class="errorlist"><li>This field is required.</li></ul>
<input type="number" name="age" id="id_age" required></td></tr>""",
)
self.assertHTMLEqual(
p.as_div(),
'<div class="required error"><label for="id_name" class="required">Name:'
'</label><ul class="errorlist"><li>This field is required.</li></ul>'
'<input type="text" name="name" required id="id_name" /></div>'
'<div class="required"><label for="id_is_cool" class="required">Is cool:'
'</label><select name="is_cool" id="id_is_cool">'
'<option value="unknown" selected>Unknown</option>'
'<option value="true">Yes</option><option value="false">No</option>'
'</select></div><div><label for="id_email">Email:</label>'
'<input type="email" name="email" id="id_email" /></div>'
'<div class="required error"><label for="id_age" class="required">Age:'
'</label><ul class="errorlist"><li>This field is required.</li></ul>'
'<input type="number" name="age" required id="id_age" /></div>',
)
def test_label_has_required_css_class(self):
"""
required_css_class is added to label_tag() and legend_tag() of required
fields.
"""
class SomeForm(Form):
required_css_class = "required"
field = CharField(max_length=10)
field2 = IntegerField(required=False)
f = SomeForm({"field": "test"})
self.assertHTMLEqual(
f["field"].label_tag(),
'<label for="id_field" class="required">Field:</label>',
)
self.assertHTMLEqual(
f["field"].legend_tag(),
'<legend for="id_field" class="required">Field:</legend>',
)
self.assertHTMLEqual(
f["field"].label_tag(attrs={"class": "foo"}),
'<label for="id_field" class="foo required">Field:</label>',
)
self.assertHTMLEqual(
f["field"].legend_tag(attrs={"class": "foo"}),
'<legend for="id_field" class="foo required">Field:</legend>',
)
self.assertHTMLEqual(
f["field2"].label_tag(), '<label for="id_field2">Field2:</label>'
)
self.assertHTMLEqual(
f["field2"].legend_tag(),
'<legend for="id_field2">Field2:</legend>',
)
def test_label_split_datetime_not_displayed(self):
class EventForm(Form):
happened_at = SplitDateTimeField(widget=SplitHiddenDateTimeWidget)
form = EventForm()
self.assertHTMLEqual(
form.as_ul(),
'<input type="hidden" name="happened_at_0" id="id_happened_at_0">'
'<input type="hidden" name="happened_at_1" id="id_happened_at_1">',
)
def test_multivalue_field_validation(self):
def bad_names(value):
if value == "bad value":
raise ValidationError("bad value not allowed")
class NameField(MultiValueField):
def __init__(self, fields=(), *args, **kwargs):
fields = (
CharField(label="First name", max_length=10),
CharField(label="Last name", max_length=10),
)
super().__init__(fields=fields, *args, **kwargs)
def compress(self, data_list):
return " ".join(data_list)
class NameForm(Form):
name = NameField(validators=[bad_names])
form = NameForm(data={"name": ["bad", "value"]})
form.full_clean()
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {"name": ["bad value not allowed"]})
form = NameForm(data={"name": ["should be overly", "long for the field names"]})
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{
"name": [
"Ensure this value has at most 10 characters (it has 16).",
"Ensure this value has at most 10 characters (it has 24).",
],
},
)
form = NameForm(data={"name": ["fname", "lname"]})
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data, {"name": "fname lname"})
def test_multivalue_deep_copy(self):
"""
#19298 -- MultiValueField needs to override the default as it needs
to deep-copy subfields:
"""
class ChoicesField(MultiValueField):
def __init__(self, fields=(), *args, **kwargs):
fields = (
ChoiceField(label="Rank", choices=((1, 1), (2, 2))),
CharField(label="Name", max_length=10),
)
super().__init__(fields=fields, *args, **kwargs)
field = ChoicesField()
field2 = copy.deepcopy(field)
self.assertIsInstance(field2, ChoicesField)
self.assertIsNot(field2.fields, field.fields)
self.assertIsNot(field2.fields[0].choices, field.fields[0].choices)
def test_multivalue_initial_data(self):
"""
#23674 -- invalid initial data should not break form.changed_data()
"""
class DateAgeField(MultiValueField):
def __init__(self, fields=(), *args, **kwargs):
fields = (DateField(label="Date"), IntegerField(label="Age"))
super().__init__(fields=fields, *args, **kwargs)
class DateAgeForm(Form):
date_age = DateAgeField()
data = {"date_age": ["1998-12-06", 16]}
form = DateAgeForm(data, initial={"date_age": ["200-10-10", 14]})
self.assertTrue(form.has_changed())
def test_multivalue_optional_subfields(self):
class PhoneField(MultiValueField):
def __init__(self, *args, **kwargs):
fields = (
CharField(
label="Country Code",
validators=[
RegexValidator(
r"^\+[0-9]{1,2}$", message="Enter a valid country code."
)
],
),
CharField(label="Phone Number"),
CharField(
label="Extension",
error_messages={"incomplete": "Enter an extension."},
),
CharField(
label="Label", required=False, help_text="E.g. home, work."
),
)
super().__init__(fields, *args, **kwargs)
def compress(self, data_list):
if data_list:
return "%s.%s ext. %s (label: %s)" % tuple(data_list)
return None
# An empty value for any field will raise a `required` error on a
# required `MultiValueField`.
f = PhoneField()
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean("")
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean([])
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(["+61"])
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(["+61", "287654321", "123"])
self.assertEqual(
"+61.287654321 ext. 123 (label: Home)",
f.clean(["+61", "287654321", "123", "Home"]),
)
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(["61", "287654321", "123", "Home"])
# Empty values for fields will NOT raise a `required` error on an
# optional `MultiValueField`
f = PhoneField(required=False)
self.assertIsNone(f.clean(""))
self.assertIsNone(f.clean(None))
self.assertIsNone(f.clean([]))
self.assertEqual("+61. ext. (label: )", f.clean(["+61"]))
self.assertEqual(
"+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"])
)
self.assertEqual(
"+61.287654321 ext. 123 (label: Home)",
f.clean(["+61", "287654321", "123", "Home"]),
)
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(["61", "287654321", "123", "Home"])
# For a required `MultiValueField` with `require_all_fields=False`, a
# `required` error will only be raised if all fields are empty. Fields
# can individually be required or optional. An empty value for any
# required field will raise an `incomplete` error.
f = PhoneField(require_all_fields=False)
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean("")
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean([])
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
f.clean(["+61"])
self.assertEqual(
"+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"])
)
with self.assertRaisesMessage(
ValidationError, "'Enter a complete value.', 'Enter an extension.'"
):
f.clean(["", "", "", "Home"])
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(["61", "287654321", "123", "Home"])
# For an optional `MultiValueField` with `require_all_fields=False`, we
# don't get any `required` error but we still get `incomplete` errors.
f = PhoneField(required=False, require_all_fields=False)
self.assertIsNone(f.clean(""))
self.assertIsNone(f.clean(None))
self.assertIsNone(f.clean([]))
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
f.clean(["+61"])
self.assertEqual(
"+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"])
)
with self.assertRaisesMessage(
ValidationError, "'Enter a complete value.', 'Enter an extension.'"
):
f.clean(["", "", "", "Home"])
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(["61", "287654321", "123", "Home"])
def test_multivalue_optional_subfields_rendering(self):
class PhoneWidget(MultiWidget):
def __init__(self, attrs=None):
widgets = [TextInput(), TextInput()]
super().__init__(widgets, attrs)
def decompress(self, value):
return [None, None]
class PhoneField(MultiValueField):
def __init__(self, *args, **kwargs):
fields = [CharField(), CharField(required=False)]
super().__init__(fields, *args, **kwargs)
class PhoneForm(Form):
phone1 = PhoneField(widget=PhoneWidget)
phone2 = PhoneField(widget=PhoneWidget, required=False)
phone3 = PhoneField(widget=PhoneWidget, require_all_fields=False)
phone4 = PhoneField(
widget=PhoneWidget,
required=False,
require_all_fields=False,
)
form = PhoneForm(auto_id=False)
self.assertHTMLEqual(
form.as_p(),
"""
<p>Phone1:<input type="text" name="phone1_0" required>
<input type="text" name="phone1_1" required></p>
<p>Phone2:<input type="text" name="phone2_0">
<input type="text" name="phone2_1"></p>
<p>Phone3:<input type="text" name="phone3_0" required>
<input type="text" name="phone3_1"></p>
<p>Phone4:<input type="text" name="phone4_0">
<input type="text" name="phone4_1"></p>
""",
)
def test_custom_empty_values(self):
"""
Form fields can customize what is considered as an empty value
for themselves (#19997).
"""
class CustomJSONField(CharField):
empty_values = [None, ""]
def to_python(self, value):
# Fake json.loads
if value == "{}":
return {}
return super().to_python(value)
class JSONForm(forms.Form):
json = CustomJSONField()
form = JSONForm(data={"json": "{}"})
form.full_clean()
self.assertEqual(form.cleaned_data, {"json": {}})
def test_boundfield_label_tag(self):
class SomeForm(Form):
field = CharField()
boundfield = SomeForm()["field"]
testcases = [ # (args, kwargs, expected)
# without anything: just print the <label>
((), {}, '<%(tag)s for="id_field">Field:</%(tag)s>'),
# passing just one argument: overrides the field's label
(("custom",), {}, '<%(tag)s for="id_field">custom:</%(tag)s>'),
# the overridden label is escaped
(("custom&",), {}, '<%(tag)s for="id_field">custom&:</%(tag)s>'),
((mark_safe("custom&"),), {}, '<%(tag)s for="id_field">custom&:</%(tag)s>'),
# Passing attrs to add extra attributes on the <label>
(
(),
{"attrs": {"class": "pretty"}},
'<%(tag)s for="id_field" class="pretty">Field:</%(tag)s>',
),
]
for args, kwargs, expected in testcases:
with self.subTest(args=args, kwargs=kwargs):
self.assertHTMLEqual(
boundfield.label_tag(*args, **kwargs),
expected % {"tag": "label"},
)
self.assertHTMLEqual(
boundfield.legend_tag(*args, **kwargs),
expected % {"tag": "legend"},
)
def test_boundfield_label_tag_no_id(self):
"""
If a widget has no id, label_tag() and legend_tag() return the text
with no surrounding <label>.
"""
class SomeForm(Form):
field = CharField()
boundfield = SomeForm(auto_id="")["field"]
self.assertHTMLEqual(boundfield.label_tag(), "Field:")
self.assertHTMLEqual(boundfield.legend_tag(), "Field:")
self.assertHTMLEqual(boundfield.label_tag("Custom&"), "Custom&:")
self.assertHTMLEqual(boundfield.legend_tag("Custom&"), "Custom&:")
def test_boundfield_label_tag_custom_widget_id_for_label(self):
class CustomIdForLabelTextInput(TextInput):
def id_for_label(self, id):
return "custom_" + id
class EmptyIdForLabelTextInput(TextInput):
def id_for_label(self, id):
return None
class SomeForm(Form):
custom = CharField(widget=CustomIdForLabelTextInput)
empty = CharField(widget=EmptyIdForLabelTextInput)
form = SomeForm()
self.assertHTMLEqual(
form["custom"].label_tag(), '<label for="custom_id_custom">Custom:</label>'
)
self.assertHTMLEqual(
form["custom"].legend_tag(),
'<legend for="custom_id_custom">Custom:</legend>',
)
self.assertHTMLEqual(form["empty"].label_tag(), "<label>Empty:</label>")
self.assertHTMLEqual(form["empty"].legend_tag(), "<legend>Empty:</legend>")
def test_boundfield_empty_label(self):
class SomeForm(Form):
field = CharField(label="")
boundfield = SomeForm()["field"]
self.assertHTMLEqual(boundfield.label_tag(), '<label for="id_field"></label>')
self.assertHTMLEqual(
boundfield.legend_tag(),
'<legend for="id_field"></legend>',
)
def test_boundfield_id_for_label(self):
class SomeForm(Form):
field = CharField(label="")
self.assertEqual(SomeForm()["field"].id_for_label, "id_field")
def test_boundfield_id_for_label_override_by_attrs(self):
"""
If an id is provided in `Widget.attrs`, it overrides the generated ID,
unless it is `None`.
"""
class SomeForm(Form):
field = CharField(widget=TextInput(attrs={"id": "myCustomID"}))
field_none = CharField(widget=TextInput(attrs={"id": None}))
form = SomeForm()
self.assertEqual(form["field"].id_for_label, "myCustomID")
self.assertEqual(form["field_none"].id_for_label, "id_field_none")
def test_boundfield_subwidget_id_for_label(self):
"""
If auto_id is provided when initializing the form, the generated ID in
subwidgets must reflect that prefix.
"""
class SomeForm(Form):
field = MultipleChoiceField(
choices=[("a", "A"), ("b", "B")],
widget=CheckboxSelectMultiple,
)
form = SomeForm(auto_id="prefix_%s")
subwidgets = form["field"].subwidgets
self.assertEqual(subwidgets[0].id_for_label, "prefix_field_0")
self.assertEqual(subwidgets[1].id_for_label, "prefix_field_1")
def test_boundfield_widget_type(self):
class SomeForm(Form):
first_name = CharField()
birthday = SplitDateTimeField(widget=SplitHiddenDateTimeWidget)
f = SomeForm()
self.assertEqual(f["first_name"].widget_type, "text")
self.assertEqual(f["birthday"].widget_type, "splithiddendatetime")
def test_boundfield_css_classes(self):
form = Person()
field = form["first_name"]
self.assertEqual(field.css_classes(), "")
self.assertEqual(field.css_classes(extra_classes=""), "")
self.assertEqual(field.css_classes(extra_classes="test"), "test")
self.assertEqual(field.css_classes(extra_classes="test test"), "test")
def test_label_suffix_override(self):
"""
BoundField label_suffix (if provided) overrides Form label_suffix
"""
class SomeForm(Form):
field = CharField()
boundfield = SomeForm(label_suffix="!")["field"]
self.assertHTMLEqual(
boundfield.label_tag(label_suffix="$"),
'<label for="id_field">Field$</label>',
)
self.assertHTMLEqual(
boundfield.legend_tag(label_suffix="$"),
'<legend for="id_field">Field$</legend>',
)
def test_error_dict(self):
class MyForm(Form):
foo = CharField()
bar = CharField()
def clean(self):
raise ValidationError(
"Non-field error.", code="secret", params={"a": 1, "b": 2}
)
form = MyForm({})
self.assertIs(form.is_valid(), False)
errors = form.errors.as_text()
control = [
"* foo\n * This field is required.",
"* bar\n * This field is required.",
"* __all__\n * Non-field error.",
]
for error in control:
self.assertIn(error, errors)
errors = form.errors.as_ul()
control = [
'<li>foo<ul class="errorlist"><li>This field is required.</li></ul></li>',
'<li>bar<ul class="errorlist"><li>This field is required.</li></ul></li>',
'<li>__all__<ul class="errorlist nonfield"><li>Non-field error.</li></ul>'
"</li>",
]
for error in control:
self.assertInHTML(error, errors)
errors = form.errors.get_json_data()
control = {
"foo": [{"code": "required", "message": "This field is required."}],
"bar": [{"code": "required", "message": "This field is required."}],
"__all__": [{"code": "secret", "message": "Non-field error."}],
}
self.assertEqual(errors, control)
self.assertEqual(json.dumps(errors), form.errors.as_json())
def test_error_dict_as_json_escape_html(self):
"""#21962 - adding html escape flag to ErrorDict"""
class MyForm(Form):
foo = CharField()
bar = CharField()
def clean(self):
raise ValidationError(
"<p>Non-field error.</p>",
code="secret",
params={"a": 1, "b": 2},
)
control = {
"foo": [{"code": "required", "message": "This field is required."}],
"bar": [{"code": "required", "message": "This field is required."}],
"__all__": [{"code": "secret", "message": "<p>Non-field error.</p>"}],
}
form = MyForm({})
self.assertFalse(form.is_valid())
errors = json.loads(form.errors.as_json())
self.assertEqual(errors, control)
escaped_error = "<p>Non-field error.</p>"
self.assertEqual(
form.errors.get_json_data(escape_html=True)["__all__"][0]["message"],
escaped_error,
)
errors = json.loads(form.errors.as_json(escape_html=True))
control["__all__"][0]["message"] = escaped_error
self.assertEqual(errors, control)
def test_error_list(self):
e = ErrorList()
e.append("Foo")
e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"}))
self.assertIsInstance(e, list)
self.assertIn("Foo", e)
self.assertIn("Foo", ValidationError(e))
self.assertEqual(e.as_text(), "* Foo\n* Foobar")
self.assertEqual(
e.as_ul(), '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>'
)
errors = e.get_json_data()
self.assertEqual(
errors,
[{"message": "Foo", "code": ""}, {"message": "Foobar", "code": "foobar"}],
)
self.assertEqual(json.dumps(errors), e.as_json())
def test_error_list_class_not_specified(self):
e = ErrorList()
e.append("Foo")
e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"}))
self.assertEqual(
e.as_ul(), '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>'
)
def test_error_list_class_has_one_class_specified(self):
e = ErrorList(error_class="foobar-error-class")
e.append("Foo")
e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"}))
self.assertEqual(
e.as_ul(),
'<ul class="errorlist foobar-error-class"><li>Foo</li><li>Foobar</li></ul>',
)
def test_error_list_with_hidden_field_errors_has_correct_class(self):
class Person(Form):
first_name = CharField()
last_name = CharField(widget=HiddenInput)
p = Person({"first_name": "John"})
self.assertHTMLEqual(
p.as_ul(),
"""<li><ul class="errorlist nonfield">
<li>(Hidden field last_name) This field is required.</li></ul></li><li>
<label for="id_first_name">First name:</label>
<input id="id_first_name" name="first_name" type="text" value="John" required>
<input id="id_last_name" name="last_name" type="hidden"></li>""",
)
self.assertHTMLEqual(
p.as_p(),
"""
<ul class="errorlist nonfield">
<li>(Hidden field last_name) This field is required.</li></ul>
<p><label for="id_first_name">First name:</label>
<input id="id_first_name" name="first_name" type="text" value="John"
required>
<input id="id_last_name" name="last_name" type="hidden"></p>
""",
)
self.assertHTMLEqual(
p.as_table(),
"""<tr><td colspan="2"><ul class="errorlist nonfield">
<li>(Hidden field last_name) This field is required.</li></ul></td></tr>
<tr><th><label for="id_first_name">First name:</label></th><td>
<input id="id_first_name" name="first_name" type="text" value="John" required>
<input id="id_last_name" name="last_name" type="hidden"></td></tr>""",
)
self.assertHTMLEqual(
p.as_div(),
'<ul class="errorlist nonfield"><li>(Hidden field last_name) This field '
'is required.</li></ul><div><label for="id_first_name">First name:</label>'
'<input id="id_first_name" name="first_name" type="text" value="John" '
'required><input id="id_last_name" name="last_name" type="hidden"></div>',
)
def test_error_list_with_non_field_errors_has_correct_class(self):
class Person(Form):
first_name = CharField()
last_name = CharField()
def clean(self):
raise ValidationError("Generic validation error")
p = Person({"first_name": "John", "last_name": "Lennon"})
self.assertHTMLEqual(
str(p.non_field_errors()),
'<ul class="errorlist nonfield"><li>Generic validation error</li></ul>',
)
self.assertHTMLEqual(
p.as_ul(),
"""<li>
<ul class="errorlist nonfield"><li>Generic validation error</li></ul></li>
<li><label for="id_first_name">First name:</label>
<input id="id_first_name" name="first_name" type="text" value="John" required></li>
<li><label for="id_last_name">Last name:</label>
<input id="id_last_name" name="last_name" type="text" value="Lennon" required></li>""",
)
self.assertHTMLEqual(
p.non_field_errors().as_text(), "* Generic validation error"
)
self.assertHTMLEqual(
p.as_p(),
"""<ul class="errorlist nonfield"><li>Generic validation error</li></ul>
<p><label for="id_first_name">First name:</label>
<input id="id_first_name" name="first_name" type="text" value="John" required></p>
<p><label for="id_last_name">Last name:</label>
<input id="id_last_name" name="last_name" type="text" value="Lennon" required></p>""",
)
self.assertHTMLEqual(
p.as_table(),
"""
<tr><td colspan="2"><ul class="errorlist nonfield">
<li>Generic validation error</li></ul></td></tr>
<tr><th><label for="id_first_name">First name:</label></th><td>
<input id="id_first_name" name="first_name" type="text" value="John"
required>
</td></tr>
<tr><th><label for="id_last_name">Last name:</label></th><td>
<input id="id_last_name" name="last_name" type="text" value="Lennon"
required>
</td></tr>
""",
)
self.assertHTMLEqual(
p.as_div(),
'<ul class="errorlist nonfield"><li>Generic validation error</li></ul>'
'<div><label for="id_first_name">First name:</label><input '
'id="id_first_name" name="first_name" type="text" value="John" required>'
'</div><div><label for="id_last_name">Last name:</label><input '
'id="id_last_name" name="last_name" type="text" value="Lennon" required>'
"</div>",
)
def test_error_escaping(self):
class TestForm(Form):
hidden = CharField(widget=HiddenInput(), required=False)
visible = CharField()
def clean_hidden(self):
raise ValidationError('Foo & "bar"!')
clean_visible = clean_hidden
form = TestForm({"hidden": "a", "visible": "b"})
form.is_valid()
self.assertHTMLEqual(
form.as_ul(),
'<li><ul class="errorlist nonfield">'
"<li>(Hidden field hidden) Foo & "bar"!</li></ul></li>"
'<li><ul class="errorlist"><li>Foo & "bar"!</li></ul>'
'<label for="id_visible">Visible:</label> '
'<input type="text" name="visible" value="b" id="id_visible" required>'
'<input type="hidden" name="hidden" value="a" id="id_hidden"></li>',
)
def test_baseform_repr(self):
"""
BaseForm.__repr__() should contain some basic information about the
form.
"""
p = Person()
self.assertEqual(
repr(p),
"<Person bound=False, valid=Unknown, "
"fields=(first_name;last_name;birthday)>",
)
p = Person(
{"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"}
)
self.assertEqual(
repr(p),
"<Person bound=True, valid=Unknown, "
"fields=(first_name;last_name;birthday)>",
)
p.is_valid()
self.assertEqual(
repr(p),
"<Person bound=True, valid=True, fields=(first_name;last_name;birthday)>",
)
p = Person(
{"first_name": "John", "last_name": "Lennon", "birthday": "fakedate"}
)
p.is_valid()
self.assertEqual(
repr(p),
"<Person bound=True, valid=False, fields=(first_name;last_name;birthday)>",
)
def test_baseform_repr_dont_trigger_validation(self):
"""
BaseForm.__repr__() shouldn't trigger the form validation.
"""
p = Person(
{"first_name": "John", "last_name": "Lennon", "birthday": "fakedate"}
)
repr(p)
with self.assertRaises(AttributeError):
p.cleaned_data
self.assertFalse(p.is_valid())
self.assertEqual(p.cleaned_data, {"first_name": "John", "last_name": "Lennon"})
def test_accessing_clean(self):
class UserForm(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
def clean(self):
data = self.cleaned_data
if not self.errors:
data["username"] = data["username"].lower()
return data
f = UserForm({"username": "SirRobin", "password": "blue"})
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data["username"], "sirrobin")
def test_changing_cleaned_data_nothing_returned(self):
class UserForm(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
def clean(self):
self.cleaned_data["username"] = self.cleaned_data["username"].lower()
# don't return anything
f = UserForm({"username": "SirRobin", "password": "blue"})
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data["username"], "sirrobin")
def test_changing_cleaned_data_in_clean(self):
class UserForm(Form):
username = CharField(max_length=10)
password = CharField(widget=PasswordInput)
def clean(self):
data = self.cleaned_data
# Return a different dict. We have not changed self.cleaned_data.
return {
"username": data["username"].lower(),
"password": "this_is_not_a_secret",
}
f = UserForm({"username": "SirRobin", "password": "blue"})
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data["username"], "sirrobin")
def test_multipart_encoded_form(self):
class FormWithoutFile(Form):
username = CharField()
class FormWithFile(Form):
username = CharField()
file = FileField()
class FormWithImage(Form):
image = ImageField()
self.assertFalse(FormWithoutFile().is_multipart())
self.assertTrue(FormWithFile().is_multipart())
self.assertTrue(FormWithImage().is_multipart())
def test_html_safe(self):
class SimpleForm(Form):
username = CharField()
form = SimpleForm()
self.assertTrue(hasattr(SimpleForm, "__html__"))
self.assertEqual(str(form), form.__html__())
self.assertTrue(hasattr(form["username"], "__html__"))
self.assertEqual(str(form["username"]), form["username"].__html__())
def test_use_required_attribute_true(self):
class MyForm(Form):
use_required_attribute = True
f1 = CharField(max_length=30)
f2 = CharField(max_length=30, required=False)
f3 = CharField(widget=Textarea)
f4 = ChoiceField(choices=[("P", "Python"), ("J", "Java")])
form = MyForm()
self.assertHTMLEqual(
form.as_p(),
'<p><label for="id_f1">F1:</label>'
'<input id="id_f1" maxlength="30" name="f1" type="text" required></p>'
'<p><label for="id_f2">F2:</label>'
'<input id="id_f2" maxlength="30" name="f2" type="text"></p>'
'<p><label for="id_f3">F3:</label>'
'<textarea cols="40" id="id_f3" name="f3" rows="10" required>'
"</textarea></p>"
'<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
"</select></p>",
)
self.assertHTMLEqual(
form.as_ul(),
'<li><label for="id_f1">F1:</label> '
'<input id="id_f1" maxlength="30" name="f1" type="text" required></li>'
'<li><label for="id_f2">F2:</label>'
'<input id="id_f2" maxlength="30" name="f2" type="text"></li>'
'<li><label for="id_f3">F3:</label>'
'<textarea cols="40" id="id_f3" name="f3" rows="10" required>'
"</textarea></li>"
'<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
"</select></li>",
)
self.assertHTMLEqual(
form.as_table(),
'<tr><th><label for="id_f1">F1:</label></th>'
'<td><input id="id_f1" maxlength="30" name="f1" type="text" required>'
"</td></tr>"
'<tr><th><label for="id_f2">F2:</label></th>'
'<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>'
'<tr><th><label for="id_f3">F3:</label></th>'
'<td><textarea cols="40" id="id_f3" name="f3" rows="10" required>'
"</textarea></td></tr>"
'<tr><th><label for="id_f4">F4:</label></th><td>'
'<select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
"</select></td></tr>",
)
self.assertHTMLEqual(
form.render(form.template_name_div),
'<div><label for="id_f1">F1:</label><input id="id_f1" maxlength="30" '
'name="f1" type="text" required></div><div><label for="id_f2">F2:</label>'
'<input id="id_f2" maxlength="30" name="f2" type="text"></div><div><label '
'for="id_f3">F3:</label><textarea cols="40" id="id_f3" name="f3" '
'rows="10" required></textarea></div><div><label for="id_f4">F4:</label>'
'<select id="id_f4" name="f4"><option value="P">Python</option>'
'<option value="J">Java</option></select></div>',
)
def test_use_required_attribute_false(self):
class MyForm(Form):
use_required_attribute = False
f1 = CharField(max_length=30)
f2 = CharField(max_length=30, required=False)
f3 = CharField(widget=Textarea)
f4 = ChoiceField(choices=[("P", "Python"), ("J", "Java")])
form = MyForm()
self.assertHTMLEqual(
form.as_p(),
'<p><label for="id_f1">F1:</label>'
'<input id="id_f1" maxlength="30" name="f1" type="text"></p>'
'<p><label for="id_f2">F2:</label>'
'<input id="id_f2" maxlength="30" name="f2" type="text"></p>'
'<p><label for="id_f3">F3:</label>'
'<textarea cols="40" id="id_f3" name="f3" rows="10"></textarea></p>'
'<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
"</select></p>",
)
self.assertHTMLEqual(
form.as_ul(),
'<li><label for="id_f1">F1:</label>'
'<input id="id_f1" maxlength="30" name="f1" type="text"></li>'
'<li><label for="id_f2">F2:</label>'
'<input id="id_f2" maxlength="30" name="f2" type="text"></li>'
'<li><label for="id_f3">F3:</label>'
'<textarea cols="40" id="id_f3" name="f3" rows="10"></textarea></li>'
'<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
"</select></li>",
)
self.assertHTMLEqual(
form.as_table(),
'<tr><th><label for="id_f1">F1:</label></th>'
'<td><input id="id_f1" maxlength="30" name="f1" type="text"></td></tr>'
'<tr><th><label for="id_f2">F2:</label></th>'
'<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>'
'<tr><th><label for="id_f3">F3:</label></th><td>'
'<textarea cols="40" id="id_f3" name="f3" rows="10">'
"</textarea></td></tr>"
'<tr><th><label for="id_f4">F4:</label></th><td>'
'<select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
"</select></td></tr>",
)
self.assertHTMLEqual(
form.render(form.template_name_div),
'<div><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" '
'name="f1" type="text"></div><div><label for="id_f2">F2:</label>'
'<input id="id_f2" maxlength="30" name="f2" type="text"></div><div>'
'<label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" '
'rows="10"></textarea></div><div><label for="id_f4">F4:</label>'
'<select id="id_f4" name="f4"><option value="P">Python</option>'
'<option value="J">Java</option></select></div>',
)
def test_only_hidden_fields(self):
# A form with *only* hidden fields that has errors is going to be very unusual.
class HiddenForm(Form):
data = IntegerField(widget=HiddenInput)
f = HiddenForm({})
self.assertHTMLEqual(
f.as_p(),
'<ul class="errorlist nonfield">'
"<li>(Hidden field data) This field is required.</li></ul>\n<p> "
'<input type="hidden" name="data" id="id_data"></p>',
)
self.assertHTMLEqual(
f.as_table(),
'<tr><td colspan="2"><ul class="errorlist nonfield">'
"<li>(Hidden field data) This field is required.</li></ul>"
'<input type="hidden" name="data" id="id_data"></td></tr>',
)
def test_field_named_data(self):
class DataForm(Form):
data = CharField(max_length=10)
f = DataForm({"data": "xyzzy"})
self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data, {"data": "xyzzy"})
def test_empty_data_files_multi_value_dict(self):
p = Person()
self.assertIsInstance(p.data, MultiValueDict)
self.assertIsInstance(p.files, MultiValueDict)
def test_field_deep_copy_error_messages(self):
class CustomCharField(CharField):
def __init__(self, **kwargs):
kwargs["error_messages"] = {"invalid": "Form custom error message."}
super().__init__(**kwargs)
field = CustomCharField()
field_copy = copy.deepcopy(field)
self.assertIsInstance(field_copy, CustomCharField)
self.assertIsNot(field_copy.error_messages, field.error_messages)
def test_label_does_not_include_new_line(self):
form = Person()
field = form["first_name"]
self.assertEqual(
field.label_tag(), '<label for="id_first_name">First name:</label>'
)
self.assertEqual(
field.legend_tag(),
'<legend for="id_first_name">First name:</legend>',
)
@override_settings(USE_THOUSAND_SEPARATOR=True)
def test_label_attrs_not_localized(self):
form = Person()
field = form["first_name"]
self.assertHTMLEqual(
field.label_tag(attrs={"number": 9999}),
'<label number="9999" for="id_first_name">First name:</label>',
)
self.assertHTMLEqual(
field.legend_tag(attrs={"number": 9999}),
'<legend number="9999" for="id_first_name">First name:</legend>',
)
@jinja2_tests
class Jinja2FormsTestCase(FormsTestCase):
pass
class CustomRenderer(DjangoTemplates):
form_template_name = "forms_tests/form_snippet.html"
class RendererTests(SimpleTestCase):
def test_default(self):
form = Form()
self.assertEqual(form.renderer, get_default_renderer())
def test_kwarg_instance(self):
custom = CustomRenderer()
form = Form(renderer=custom)
self.assertEqual(form.renderer, custom)
def test_kwarg_class(self):
custom = CustomRenderer()
form = Form(renderer=custom)
self.assertEqual(form.renderer, custom)
def test_attribute_instance(self):
class CustomForm(Form):
default_renderer = DjangoTemplates()
form = CustomForm()
self.assertEqual(form.renderer, CustomForm.default_renderer)
def test_attribute_class(self):
class CustomForm(Form):
default_renderer = CustomRenderer
form = CustomForm()
self.assertIsInstance(form.renderer, CustomForm.default_renderer)
def test_attribute_override(self):
class CustomForm(Form):
default_renderer = DjangoTemplates()
custom = CustomRenderer()
form = CustomForm(renderer=custom)
self.assertEqual(form.renderer, custom)
class TemplateTests(SimpleTestCase):
def test_iterate_radios(self):
f = FrameworkForm(auto_id="id_%s")
t = Template(
"{% for radio in form.language %}"
'<div class="myradio">{{ radio }}</div>'
"{% endfor %}"
)
self.assertHTMLEqual(
t.render(Context({"form": f})),
'<div class="myradio"><label for="id_language_0">'
'<input id="id_language_0" name="language" type="radio" value="P" '
"required> Python</label></div>"
'<div class="myradio"><label for="id_language_1">'
'<input id="id_language_1" name="language" type="radio" value="J" '
"required> Java</label></div>",
)
def test_iterate_checkboxes(self):
f = SongForm({"composers": ["J", "P"]}, auto_id=False)
t = Template(
"{% for checkbox in form.composers %}"
'<div class="mycheckbox">{{ checkbox }}</div>'
"{% endfor %}"
)
self.assertHTMLEqual(
t.render(Context({"form": f})),
'<div class="mycheckbox"><label>'
'<input checked name="composers" type="checkbox" value="J"> '
"John Lennon</label></div>"
'<div class="mycheckbox"><label>'
'<input checked name="composers" type="checkbox" value="P"> '
"Paul McCartney</label></div>",
)
def test_templates_with_forms(self):
class UserRegistration(Form):
username = CharField(
max_length=10,
help_text=("Good luck picking a username that doesn't already exist."),
)
password1 = CharField(widget=PasswordInput)
password2 = CharField(widget=PasswordInput)
def clean(self):
if (
self.cleaned_data.get("password1")
and self.cleaned_data.get("password2")
and self.cleaned_data["password1"] != self.cleaned_data["password2"]
):
raise ValidationError("Please make sure your passwords match.")
return self.cleaned_data
# There is full flexibility in displaying form fields in a template.
# Just pass a Form instance to the template, and use "dot" access to
# refer to individual fields. However, this flexibility comes with the
# responsibility of displaying all the errors, including any that might
# not be associated with a particular field.
t = Template(
"<form>"
"{{ form.username.errors.as_ul }}"
"<p><label>Your username: {{ form.username }}</label></p>"
"{{ form.password1.errors.as_ul }}"
"<p><label>Password: {{ form.password1 }}</label></p>"
"{{ form.password2.errors.as_ul }}"
"<p><label>Password (again): {{ form.password2 }}</label></p>"
'<input type="submit" required>'
"</form>"
)
f = UserRegistration(auto_id=False)
self.assertHTMLEqual(
t.render(Context({"form": f})),
"<form>"
"<p><label>Your username: "
'<input type="text" name="username" maxlength="10" required></label></p>'
"<p><label>Password: "
'<input type="password" name="password1" required></label></p>'
"<p><label>Password (again): "
'<input type="password" name="password2" required></label></p>'
'<input type="submit" required>'
"</form>",
)
f = UserRegistration({"username": "django"}, auto_id=False)
self.assertHTMLEqual(
t.render(Context({"form": f})),
"<form>"
"<p><label>Your username: "
'<input type="text" name="username" value="django" maxlength="10" required>'
"</label></p>"
'<ul class="errorlist"><li>This field is required.</li></ul><p>'
"<label>Password: "
'<input type="password" name="password1" required></label></p>'
'<ul class="errorlist"><li>This field is required.</li></ul>'
"<p><label>Password (again): "
'<input type="password" name="password2" required></label></p>'
'<input type="submit" required>'
"</form>",
)
# Use form.[field].label to output a field's label. 'label' for a field
# can by specified by using the 'label' argument to a Field class. If
# 'label' is not specified, Django will use the field name with
# underscores converted to spaces, and the initial letter capitalized.
t = Template(
"<form>"
"<p><label>{{ form.username.label }}: {{ form.username }}</label></p>"
"<p><label>{{ form.password1.label }}: {{ form.password1 }}</label></p>"
"<p><label>{{ form.password2.label }}: {{ form.password2 }}</label></p>"
'<input type="submit" required>'
"</form>"
)
f = UserRegistration(auto_id=False)
self.assertHTMLEqual(
t.render(Context({"form": f})),
"<form>"
"<p><label>Username: "
'<input type="text" name="username" maxlength="10" required></label></p>'
"<p><label>Password1: "
'<input type="password" name="password1" required></label></p>'
"<p><label>Password2: "
'<input type="password" name="password2" required></label></p>'
'<input type="submit" required>'
"</form>",
)
# Use form.[field].label_tag to output a field's label with a <label>
# tag wrapped around it, but *only* if the given field has an "id"
# attribute. Recall from above that passing the "auto_id" argument to a
# Form gives each field an "id" attribute.
t = Template(
"<form>"
"<p>{{ form.username.label_tag }} {{ form.username }}</p>"
"<p>{{ form.password1.label_tag }} {{ form.password1 }}</p>"
"<p>{{ form.password2.label_tag }} {{ form.password2 }}</p>"
'<input type="submit" required>'
"</form>"
)
self.assertHTMLEqual(
t.render(Context({"form": f})),
"<form>"
"<p>Username: "
'<input type="text" name="username" maxlength="10" required></p>'
'<p>Password1: <input type="password" name="password1" required></p>'
'<p>Password2: <input type="password" name="password2" required></p>'
'<input type="submit" required>'
"</form>",
)
f = UserRegistration(auto_id="id_%s")
self.assertHTMLEqual(
t.render(Context({"form": f})),
"<form>"
'<p><label for="id_username">Username:</label>'
'<input id="id_username" type="text" name="username" maxlength="10" '
"required></p>"
'<p><label for="id_password1">Password1:</label>'
'<input type="password" name="password1" id="id_password1" required></p>'
'<p><label for="id_password2">Password2:</label>'
'<input type="password" name="password2" id="id_password2" required></p>'
'<input type="submit" required>'
"</form>",
)
# Use form.[field].legend_tag to output a field's label with a <legend>
# tag wrapped around it, but *only* if the given field has an "id"
# attribute. Recall from above that passing the "auto_id" argument to a
# Form gives each field an "id" attribute.
t = Template(
"<form>"
"<p>{{ form.username.legend_tag }} {{ form.username }}</p>"
"<p>{{ form.password1.legend_tag }} {{ form.password1 }}</p>"
"<p>{{ form.password2.legend_tag }} {{ form.password2 }}</p>"
'<input type="submit" required>'
"</form>"
)
f = UserRegistration(auto_id=False)
self.assertHTMLEqual(
t.render(Context({"form": f})),
"<form>"
"<p>Username: "
'<input type="text" name="username" maxlength="10" required></p>'
'<p>Password1: <input type="password" name="password1" required></p>'
'<p>Password2: <input type="password" name="password2" required></p>'
'<input type="submit" required>'
"</form>",
)
f = UserRegistration(auto_id="id_%s")
self.assertHTMLEqual(
t.render(Context({"form": f})),
"<form>"
'<p><legend for="id_username">Username:</legend>'
'<input id="id_username" type="text" name="username" maxlength="10" '
"required></p>"
'<p><legend for="id_password1">Password1:</legend>'
'<input type="password" name="password1" id="id_password1" required></p>'
'<p><legend for="id_password2">Password2:</legend>'
'<input type="password" name="password2" id="id_password2" required></p>'
'<input type="submit" required>'
"</form>",
)
# Use form.[field].help_text to output a field's help text. If the
# given field does not have help text, nothing will be output.
t = Template(
"<form>"
"<p>{{ form.username.label_tag }} {{ form.username }}<br>"
"{{ form.username.help_text }}</p>"
"<p>{{ form.password1.label_tag }} {{ form.password1 }}</p>"
"<p>{{ form.password2.label_tag }} {{ form.password2 }}</p>"
'<input type="submit" required>'
"</form>"
)
f = UserRegistration(auto_id=False)
self.assertHTMLEqual(
t.render(Context({"form": f})),
"<form>"
"<p>Username: "
'<input type="text" name="username" maxlength="10" required><br>'
"Good luck picking a username that doesn't already exist.</p>"
'<p>Password1: <input type="password" name="password1" required></p>'
'<p>Password2: <input type="password" name="password2" required></p>'
'<input type="submit" required>'
"</form>",
)
self.assertEqual(
Template("{{ form.password1.help_text }}").render(Context({"form": f})),
"",
)
# To display the errors that aren't associated with a particular field
# e.g. the errors caused by Form.clean() -- use
# {{ form.non_field_errors }} in the template. If used on its own, it
# is displayed as a <ul> (or an empty string, if the list of errors is
# empty).
t = Template(
"<form>"
"{{ form.username.errors.as_ul }}"
"<p><label>Your username: {{ form.username }}</label></p>"
"{{ form.password1.errors.as_ul }}"
"<p><label>Password: {{ form.password1 }}</label></p>"
"{{ form.password2.errors.as_ul }}"
"<p><label>Password (again): {{ form.password2 }}</label></p>"
'<input type="submit" required>'
"</form>"
)
f = UserRegistration(
{"username": "django", "password1": "foo", "password2": "bar"},
auto_id=False,
)
self.assertHTMLEqual(
t.render(Context({"form": f})),
"<form>"
"<p><label>Your username: "
'<input type="text" name="username" value="django" maxlength="10" required>'
"</label></p>"
"<p><label>Password: "
'<input type="password" name="password1" required></label></p>'
"<p><label>Password (again): "
'<input type="password" name="password2" required></label></p>'
'<input type="submit" required>'
"</form>",
)
t = Template(
"<form>"
"{{ form.non_field_errors }}"
"{{ form.username.errors.as_ul }}"
"<p><label>Your username: {{ form.username }}</label></p>"
"{{ form.password1.errors.as_ul }}"
"<p><label>Password: {{ form.password1 }}</label></p>"
"{{ form.password2.errors.as_ul }}"
"<p><label>Password (again): {{ form.password2 }}</label></p>"
'<input type="submit" required>'
"</form>"
)
self.assertHTMLEqual(
t.render(Context({"form": f})),
"<form>"
'<ul class="errorlist nonfield">'
"<li>Please make sure your passwords match.</li></ul>"
"<p><label>Your username: "
'<input type="text" name="username" value="django" maxlength="10" required>'
"</label></p>"
"<p><label>Password: "
'<input type="password" name="password1" required></label></p>'
"<p><label>Password (again): "
'<input type="password" name="password2" required></label></p>'
'<input type="submit" required>'
"</form>",
)
def test_basic_processing_in_view(self):
class UserRegistration(Form):
username = CharField(max_length=10)
password1 = CharField(widget=PasswordInput)
password2 = CharField(widget=PasswordInput)
def clean(self):
if (
self.cleaned_data.get("password1")
and self.cleaned_data.get("password2")
and self.cleaned_data["password1"] != self.cleaned_data["password2"]
):
raise ValidationError("Please make sure your passwords match.")
return self.cleaned_data
def my_function(method, post_data):
if method == "POST":
form = UserRegistration(post_data, auto_id=False)
else:
form = UserRegistration(auto_id=False)
if form.is_valid():
return "VALID: %r" % sorted(form.cleaned_data.items())
t = Template(
'<form method="post">'
"{{ form }}"
'<input type="submit" required>'
"</form>"
)
return t.render(Context({"form": form}))
# GET with an empty form and no errors.
self.assertHTMLEqual(
my_function("GET", {}),
'<form method="post">'
"<div>Username:"
'<input type="text" name="username" maxlength="10" required></div>'
"<div>Password1:"
'<input type="password" name="password1" required></div>'
"<div>Password2:"
'<input type="password" name="password2" required></div>'
'<input type="submit" required>'
"</form>",
)
# POST with erroneous data, a redisplayed form, with errors.
self.assertHTMLEqual(
my_function(
"POST",
{
"username": "this-is-a-long-username",
"password1": "foo",
"password2": "bar",
},
),
'<form method="post">'
'<ul class="errorlist nonfield">'
"<li>Please make sure your passwords match.</li></ul>"
'<div>Username:<ul class="errorlist">'
"<li>Ensure this value has at most 10 characters (it has 23).</li></ul>"
'<input type="text" name="username" '
'value="this-is-a-long-username" maxlength="10" required></div>'
"<div>Password1:"
'<input type="password" name="password1" required></div>'
"<div>Password2:"
'<input type="password" name="password2" required></div>'
'<input type="submit" required>'
"</form>",
)
# POST with valid data (the success message).
self.assertEqual(
my_function(
"POST",
{
"username": "adrian",
"password1": "secret",
"password2": "secret",
},
),
"VALID: [('password1', 'secret'), ('password2', 'secret'), "
"('username', 'adrian')]",
)
class OverrideTests(SimpleTestCase):
@override_settings(FORM_RENDERER="forms_tests.tests.test_forms.CustomRenderer")
def test_custom_renderer_template_name(self):
class Person(Form):
first_name = CharField()
get_default_renderer.cache_clear()
t = Template("{{ form }}")
html = t.render(Context({"form": Person()}))
expected = """
<div class="fieldWrapper"><label for="id_first_name">First name:</label>
<input type="text" name="first_name" required id="id_first_name"></div>
"""
self.assertHTMLEqual(html, expected)
get_default_renderer.cache_clear()
def test_per_form_template_name(self):
class Person(Form):
first_name = CharField()
template_name = "forms_tests/form_snippet.html"
t = Template("{{ form }}")
html = t.render(Context({"form": Person()}))
expected = """
<div class="fieldWrapper"><label for="id_first_name">First name:</label>
<input type="text" name="first_name" required id="id_first_name"></div>
"""
self.assertHTMLEqual(html, expected)
def test_errorlist_override(self):
class CustomErrorList(ErrorList):
template_name = "forms_tests/error.html"
class CommentForm(Form):
name = CharField(max_length=50, required=False)
email = EmailField()
comment = CharField()
data = {"email": "invalid"}
f = CommentForm(data, auto_id=False, error_class=CustomErrorList)
self.assertHTMLEqual(
f.as_p(),
'<p>Name: <input type="text" name="name" maxlength="50"></p>'
'<div class="errorlist">'
'<div class="error">Enter a valid email address.</div></div>'
'<p>Email: <input type="email" name="email" value="invalid" required></p>'
'<div class="errorlist">'
'<div class="error">This field is required.</div></div>'
'<p>Comment: <input type="text" name="comment" required></p>',
)
def test_cyclic_context_boundfield_render(self):
class FirstNameForm(Form):
first_name = CharField()
template_name_label = "forms_tests/cyclic_context_boundfield_render.html"
f = FirstNameForm()
try:
f.render()
except RecursionError:
self.fail("Cyclic reference in BoundField.render().")
def test_legend_tag(self):
class CustomFrameworkForm(FrameworkForm):
template_name = "forms_tests/legend_test.html"
required_css_class = "required"
f = CustomFrameworkForm()
self.assertHTMLEqual(
str(f),
'<label for="id_name" class="required">Name:</label>'
'<legend class="required">Language:</legend>',
)
class DeprecationTests(SimpleTestCase):
def test_warning(self):
from django.forms.utils import DEFAULT_TEMPLATE_DEPRECATION_MSG
with isolate_lru_cache(get_default_renderer), self.settings(
FORM_RENDERER="django.forms.renderers.DjangoTemplates"
), self.assertRaisesMessage(
RemovedInDjango50Warning, DEFAULT_TEMPLATE_DEPRECATION_MSG
):
form = Person()
str(form)
|
9132d756d204d54e298d0dd1a9bab18c583fd09c4b91f0ecb4b9f200c0bb1bd8 | import gettext
import json
from os import path
from django.conf import settings
from django.test import (
RequestFactory,
SimpleTestCase,
TestCase,
modify_settings,
override_settings,
)
from django.test.selenium import SeleniumTestCase
from django.urls import reverse
from django.utils.translation import get_language, override
from django.views.i18n import JavaScriptCatalog, get_formats
from ..urls import locale_dir
@override_settings(ROOT_URLCONF="view_tests.urls")
class SetLanguageTests(TestCase):
"""Test the django.views.i18n.set_language view."""
def _get_inactive_language_code(self):
"""Return language code for a language which is not activated."""
current_language = get_language()
return [code for code, name in settings.LANGUAGES if code != current_language][
0
]
def test_setlang(self):
"""
The set_language view can be used to change the session language.
The user is redirected to the 'next' argument if provided.
"""
lang_code = self._get_inactive_language_code()
post_data = {"language": lang_code, "next": "/"}
response = self.client.post(
"/i18n/setlang/", post_data, HTTP_REFERER="/i_should_not_be_used/"
)
self.assertRedirects(response, "/")
# The language is set in a cookie.
language_cookie = self.client.cookies[settings.LANGUAGE_COOKIE_NAME]
self.assertEqual(language_cookie.value, lang_code)
self.assertEqual(language_cookie["domain"], "")
self.assertEqual(language_cookie["path"], "/")
self.assertEqual(language_cookie["max-age"], "")
self.assertEqual(language_cookie["httponly"], "")
self.assertEqual(language_cookie["samesite"], "")
self.assertEqual(language_cookie["secure"], "")
def test_setlang_unsafe_next(self):
"""
The set_language view only redirects to the 'next' argument if it is
"safe".
"""
lang_code = self._get_inactive_language_code()
post_data = {"language": lang_code, "next": "//unsafe/redirection/"}
response = self.client.post("/i18n/setlang/", data=post_data)
self.assertEqual(response.url, "/")
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
def test_setlang_http_next(self):
"""
The set_language view only redirects to the 'next' argument if it is
"safe" and its scheme is HTTPS if the request was sent over HTTPS.
"""
lang_code = self._get_inactive_language_code()
non_https_next_url = "http://testserver/redirection/"
post_data = {"language": lang_code, "next": non_https_next_url}
# Insecure URL in POST data.
response = self.client.post("/i18n/setlang/", data=post_data, secure=True)
self.assertEqual(response.url, "/")
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
# Insecure URL in HTTP referer.
response = self.client.post(
"/i18n/setlang/", secure=True, HTTP_REFERER=non_https_next_url
)
self.assertEqual(response.url, "/")
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
def test_setlang_redirect_to_referer(self):
"""
The set_language view redirects to the URL in the referer header when
there isn't a "next" parameter.
"""
lang_code = self._get_inactive_language_code()
post_data = {"language": lang_code}
response = self.client.post("/i18n/setlang/", post_data, HTTP_REFERER="/i18n/")
self.assertRedirects(response, "/i18n/", fetch_redirect_response=False)
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
def test_setlang_default_redirect(self):
"""
The set_language view redirects to '/' when there isn't a referer or
"next" parameter.
"""
lang_code = self._get_inactive_language_code()
post_data = {"language": lang_code}
response = self.client.post("/i18n/setlang/", post_data)
self.assertRedirects(response, "/")
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
def test_setlang_performs_redirect_for_ajax_if_explicitly_requested(self):
"""
The set_language view redirects to the "next" parameter for requests
not accepting HTML response content.
"""
lang_code = self._get_inactive_language_code()
post_data = {"language": lang_code, "next": "/"}
response = self.client.post(
"/i18n/setlang/", post_data, HTTP_ACCEPT="application/json"
)
self.assertRedirects(response, "/")
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
def test_setlang_doesnt_perform_a_redirect_to_referer_for_ajax(self):
"""
The set_language view doesn't redirect to the HTTP referer header if
the request doesn't accept HTML response content.
"""
lang_code = self._get_inactive_language_code()
post_data = {"language": lang_code}
headers = {"HTTP_REFERER": "/", "HTTP_ACCEPT": "application/json"}
response = self.client.post("/i18n/setlang/", post_data, **headers)
self.assertEqual(response.status_code, 204)
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
def test_setlang_doesnt_perform_a_default_redirect_for_ajax(self):
"""
The set_language view returns 204 by default for requests not accepting
HTML response content.
"""
lang_code = self._get_inactive_language_code()
post_data = {"language": lang_code}
response = self.client.post(
"/i18n/setlang/", post_data, HTTP_ACCEPT="application/json"
)
self.assertEqual(response.status_code, 204)
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
def test_setlang_unsafe_next_for_ajax(self):
"""
The fallback to root URL for the set_language view works for requests
not accepting HTML response content.
"""
lang_code = self._get_inactive_language_code()
post_data = {"language": lang_code, "next": "//unsafe/redirection/"}
response = self.client.post(
"/i18n/setlang/", post_data, HTTP_ACCEPT="application/json"
)
self.assertEqual(response.url, "/")
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
def test_setlang_reversal(self):
self.assertEqual(reverse("set_language"), "/i18n/setlang/")
def test_setlang_cookie(self):
# we force saving language to a cookie rather than a session
# by excluding session middleware and those which do require it
test_settings = {
"MIDDLEWARE": ["django.middleware.common.CommonMiddleware"],
"LANGUAGE_COOKIE_NAME": "mylanguage",
"LANGUAGE_COOKIE_AGE": 3600 * 7 * 2,
"LANGUAGE_COOKIE_DOMAIN": ".example.com",
"LANGUAGE_COOKIE_PATH": "/test/",
"LANGUAGE_COOKIE_HTTPONLY": True,
"LANGUAGE_COOKIE_SAMESITE": "Strict",
"LANGUAGE_COOKIE_SECURE": True,
}
with self.settings(**test_settings):
post_data = {"language": "pl", "next": "/views/"}
response = self.client.post("/i18n/setlang/", data=post_data)
language_cookie = response.cookies.get("mylanguage")
self.assertEqual(language_cookie.value, "pl")
self.assertEqual(language_cookie["domain"], ".example.com")
self.assertEqual(language_cookie["path"], "/test/")
self.assertEqual(language_cookie["max-age"], 3600 * 7 * 2)
self.assertIs(language_cookie["httponly"], True)
self.assertEqual(language_cookie["samesite"], "Strict")
self.assertIs(language_cookie["secure"], True)
def test_setlang_decodes_http_referer_url(self):
"""
The set_language view decodes the HTTP_REFERER URL and preserves an
encoded query string.
"""
# The URL & view must exist for this to work as a regression test.
self.assertEqual(
reverse("with_parameter", kwargs={"parameter": "x"}), "/test-setlang/x/"
)
lang_code = self._get_inactive_language_code()
# %C3%A4 decodes to ä, %26 to &.
encoded_url = "/test-setlang/%C3%A4/?foo=bar&baz=alpha%26omega"
response = self.client.post(
"/i18n/setlang/", {"language": lang_code}, HTTP_REFERER=encoded_url
)
self.assertRedirects(response, encoded_url, fetch_redirect_response=False)
self.assertEqual(
self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code
)
@modify_settings(
MIDDLEWARE={
"append": "django.middleware.locale.LocaleMiddleware",
}
)
def test_lang_from_translated_i18n_pattern(self):
response = self.client.post(
"/i18n/setlang/",
data={"language": "nl"},
follow=True,
HTTP_REFERER="/en/translated/",
)
self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, "nl")
self.assertRedirects(response, "/nl/vertaald/")
# And reverse
response = self.client.post(
"/i18n/setlang/",
data={"language": "en"},
follow=True,
HTTP_REFERER="/nl/vertaald/",
)
self.assertRedirects(response, "/en/translated/")
@override_settings(ROOT_URLCONF="view_tests.urls")
class I18NViewTests(SimpleTestCase):
"""Test django.views.i18n views other than set_language."""
@override_settings(LANGUAGE_CODE="de")
def test_get_formats(self):
formats = get_formats()
# Test 3 possible types in get_formats: integer, string, and list.
self.assertEqual(formats["FIRST_DAY_OF_WEEK"], 1)
self.assertEqual(formats["DECIMAL_SEPARATOR"], ",")
self.assertEqual(
formats["TIME_INPUT_FORMATS"], ["%H:%M:%S", "%H:%M:%S.%f", "%H:%M"]
)
def test_jsi18n(self):
"""The javascript_catalog can be deployed with language settings"""
for lang_code in ["es", "fr", "ru"]:
with override(lang_code):
catalog = gettext.translation("djangojs", locale_dir, [lang_code])
trans_txt = catalog.gettext("this is to be translated")
response = self.client.get("/jsi18n/")
self.assertEqual(
response.headers["Content-Type"], 'text/javascript; charset="utf-8"'
)
# response content must include a line like:
# "this is to be translated": <value of trans_txt Python variable>
# json.dumps() is used to be able to check Unicode strings.
self.assertContains(response, json.dumps(trans_txt), 1)
if lang_code == "fr":
# Message with context (msgctxt)
self.assertContains(response, '"month name\\u0004May": "mai"', 1)
@override_settings(USE_I18N=False)
def test_jsi18n_USE_I18N_False(self):
response = self.client.get("/jsi18n/")
# default plural function
self.assertContains(
response,
"django.pluralidx = function(count) { return (count == 1) ? 0 : 1; };",
)
self.assertNotContains(response, "var newcatalog =")
def test_jsoni18n(self):
"""
The json_catalog returns the language catalog and settings as JSON.
"""
with override("de"):
response = self.client.get("/jsoni18n/")
data = json.loads(response.content.decode())
self.assertIn("catalog", data)
self.assertIn("formats", data)
self.assertEqual(
data["formats"]["TIME_INPUT_FORMATS"],
["%H:%M:%S", "%H:%M:%S.%f", "%H:%M"],
)
self.assertEqual(data["formats"]["FIRST_DAY_OF_WEEK"], 1)
self.assertIn("plural", data)
self.assertEqual(data["catalog"]["month name\x04May"], "Mai")
self.assertIn("DATETIME_FORMAT", data["formats"])
self.assertEqual(data["plural"], "(n != 1)")
def test_jsi18n_with_missing_en_files(self):
"""
The javascript_catalog shouldn't load the fallback language in the
case that the current selected language is actually the one translated
from, and hence missing translation files completely.
This happens easily when you're translating from English to other
languages and you've set settings.LANGUAGE_CODE to some other language
than English.
"""
with self.settings(LANGUAGE_CODE="es"), override("en-us"):
response = self.client.get("/jsi18n/")
self.assertNotContains(response, "esto tiene que ser traducido")
def test_jsoni18n_with_missing_en_files(self):
"""
Same as above for the json_catalog view. Here we also check for the
expected JSON format.
"""
with self.settings(LANGUAGE_CODE="es"), override("en-us"):
response = self.client.get("/jsoni18n/")
data = json.loads(response.content.decode())
self.assertIn("catalog", data)
self.assertIn("formats", data)
self.assertIn("plural", data)
self.assertEqual(data["catalog"], {})
self.assertIn("DATETIME_FORMAT", data["formats"])
self.assertIsNone(data["plural"])
def test_jsi18n_fallback_language(self):
"""
Let's make sure that the fallback language is still working properly
in cases where the selected language cannot be found.
"""
with self.settings(LANGUAGE_CODE="fr"), override("fi"):
response = self.client.get("/jsi18n/")
self.assertContains(response, "il faut le traduire")
self.assertNotContains(response, "Untranslated string")
def test_jsi18n_fallback_language_with_custom_locale_dir(self):
"""
The fallback language works when there are several levels of fallback
translation catalogs.
"""
locale_paths = [
path.join(
path.dirname(path.dirname(path.abspath(__file__))),
"custom_locale_path",
),
]
with self.settings(LOCALE_PATHS=locale_paths), override("es_MX"):
response = self.client.get("/jsi18n/")
self.assertContains(
response, "custom_locale_path: esto tiene que ser traducido"
)
response = self.client.get("/jsi18n_no_packages/")
self.assertContains(
response, "custom_locale_path: esto tiene que ser traducido"
)
def test_i18n_fallback_language_plural(self):
"""
The fallback to a language with less plural forms maintains the real
language's number of plural forms and correct translations.
"""
with self.settings(LANGUAGE_CODE="pt"), override("ru"):
response = self.client.get("/jsi18n/")
self.assertEqual(
response.context["catalog"]["{count} plural3"],
["{count} plural3 p3", "{count} plural3 p3s", "{count} plural3 p3t"],
)
self.assertEqual(
response.context["catalog"]["{count} plural2"],
["{count} plural2", "{count} plural2s", ""],
)
with self.settings(LANGUAGE_CODE="ru"), override("pt"):
response = self.client.get("/jsi18n/")
self.assertEqual(
response.context["catalog"]["{count} plural3"],
["{count} plural3", "{count} plural3s"],
)
self.assertEqual(
response.context["catalog"]["{count} plural2"],
["{count} plural2", "{count} plural2s"],
)
def test_i18n_english_variant(self):
with override("en-gb"):
response = self.client.get("/jsi18n/")
self.assertIn(
'"this color is to be translated": "this colour is to be translated"',
response.context["catalog_str"],
)
def test_i18n_language_non_english_default(self):
"""
Check if the JavaScript i18n view returns an empty language catalog
if the default language is non-English, the selected language
is English and there is not 'en' translation available. See #13388,
#3594 and #13726 for more details.
"""
with self.settings(LANGUAGE_CODE="fr"), override("en-us"):
response = self.client.get("/jsi18n/")
self.assertNotContains(response, "Choisir une heure")
@modify_settings(INSTALLED_APPS={"append": "view_tests.app0"})
def test_non_english_default_english_userpref(self):
"""
Same as above with the difference that there IS an 'en' translation
available. The JavaScript i18n view must return a NON empty language catalog
with the proper English translations. See #13726 for more details.
"""
with self.settings(LANGUAGE_CODE="fr"), override("en-us"):
response = self.client.get("/jsi18n_english_translation/")
self.assertContains(response, "this app0 string is to be translated")
def test_i18n_language_non_english_fallback(self):
"""
Makes sure that the fallback language is still working properly
in cases where the selected language cannot be found.
"""
with self.settings(LANGUAGE_CODE="fr"), override("none"):
response = self.client.get("/jsi18n/")
self.assertContains(response, "Choisir une heure")
def test_escaping(self):
# Force a language via GET otherwise the gettext functions are a noop!
response = self.client.get("/jsi18n_admin/?language=de")
self.assertContains(response, "\\x04")
@modify_settings(INSTALLED_APPS={"append": ["view_tests.app5"]})
def test_non_BMP_char(self):
"""
Non-BMP characters should not break the javascript_catalog (#21725).
"""
with self.settings(LANGUAGE_CODE="en-us"), override("fr"):
response = self.client.get("/jsi18n/app5/")
self.assertContains(response, "emoji")
self.assertContains(response, "\\ud83d\\udca9")
@modify_settings(INSTALLED_APPS={"append": ["view_tests.app1", "view_tests.app2"]})
def test_i18n_language_english_default(self):
"""
Check if the JavaScript i18n view returns a complete language catalog
if the default language is en-us, the selected language has a
translation available and a catalog composed by djangojs domain
translations of multiple Python packages is requested. See #13388,
#3594 and #13514 for more details.
"""
base_trans_string = (
"il faut traduire cette cha\\u00eene de caract\\u00e8res de "
)
app1_trans_string = base_trans_string + "app1"
app2_trans_string = base_trans_string + "app2"
with self.settings(LANGUAGE_CODE="en-us"), override("fr"):
response = self.client.get("/jsi18n_multi_packages1/")
self.assertContains(response, app1_trans_string)
self.assertContains(response, app2_trans_string)
response = self.client.get("/jsi18n/app1/")
self.assertContains(response, app1_trans_string)
self.assertNotContains(response, app2_trans_string)
response = self.client.get("/jsi18n/app2/")
self.assertNotContains(response, app1_trans_string)
self.assertContains(response, app2_trans_string)
@modify_settings(INSTALLED_APPS={"append": ["view_tests.app3", "view_tests.app4"]})
def test_i18n_different_non_english_languages(self):
"""
Similar to above but with neither default or requested language being
English.
"""
with self.settings(LANGUAGE_CODE="fr"), override("es-ar"):
response = self.client.get("/jsi18n_multi_packages2/")
self.assertContains(response, "este texto de app3 debe ser traducido")
def test_i18n_with_locale_paths(self):
extended_locale_paths = settings.LOCALE_PATHS + [
path.join(
path.dirname(path.dirname(path.abspath(__file__))),
"app3",
"locale",
),
]
with self.settings(LANGUAGE_CODE="es-ar", LOCALE_PATHS=extended_locale_paths):
with override("es-ar"):
response = self.client.get("/jsi18n/")
self.assertContains(response, "este texto de app3 debe ser traducido")
def test_i18n_unknown_package_error(self):
view = JavaScriptCatalog.as_view()
request = RequestFactory().get("/")
msg = "Invalid package(s) provided to JavaScriptCatalog: unknown_package"
with self.assertRaisesMessage(ValueError, msg):
view(request, packages="unknown_package")
msg += ",unknown_package2"
with self.assertRaisesMessage(ValueError, msg):
view(request, packages="unknown_package+unknown_package2")
@override_settings(ROOT_URLCONF="view_tests.urls")
class I18nSeleniumTests(SeleniumTestCase):
# The test cases use fixtures & translations from these apps.
available_apps = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"view_tests",
]
@override_settings(LANGUAGE_CODE="de")
def test_javascript_gettext(self):
from selenium.webdriver.common.by import By
self.selenium.get(self.live_server_url + "/jsi18n_template/")
elem = self.selenium.find_element(By.ID, "gettext")
self.assertEqual(elem.text, "Entfernen")
elem = self.selenium.find_element(By.ID, "ngettext_sing")
self.assertEqual(elem.text, "1 Element")
elem = self.selenium.find_element(By.ID, "ngettext_plur")
self.assertEqual(elem.text, "455 Elemente")
elem = self.selenium.find_element(By.ID, "ngettext_onnonplural")
self.assertEqual(elem.text, "Bild")
elem = self.selenium.find_element(By.ID, "pgettext")
self.assertEqual(elem.text, "Kann")
elem = self.selenium.find_element(By.ID, "npgettext_sing")
self.assertEqual(elem.text, "1 Resultat")
elem = self.selenium.find_element(By.ID, "npgettext_plur")
self.assertEqual(elem.text, "455 Resultate")
elem = self.selenium.find_element(By.ID, "formats")
self.assertEqual(
elem.text,
"DATE_INPUT_FORMATS is an object; DECIMAL_SEPARATOR is a string; "
"FIRST_DAY_OF_WEEK is a number;",
)
@modify_settings(INSTALLED_APPS={"append": ["view_tests.app1", "view_tests.app2"]})
@override_settings(LANGUAGE_CODE="fr")
def test_multiple_catalogs(self):
from selenium.webdriver.common.by import By
self.selenium.get(self.live_server_url + "/jsi18n_multi_catalogs/")
elem = self.selenium.find_element(By.ID, "app1string")
self.assertEqual(
elem.text, "il faut traduire cette chaîne de caractères de app1"
)
elem = self.selenium.find_element(By.ID, "app2string")
self.assertEqual(
elem.text, "il faut traduire cette chaîne de caractères de app2"
)
|
00e9c1d9fa3bd91b363e19c7617be0179ab01ed642b94a8497b766b905d9b019 | from django.template.defaultfilters import length_is
from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango51Warning
from ..utils import setup
@ignore_warnings(category=RemovedInDjango51Warning)
class LengthIsTests(SimpleTestCase):
@setup({"length_is01": '{% if some_list|length_is:"4" %}Four{% endif %}'})
def test_length_is01(self):
output = self.engine.render_to_string(
"length_is01", {"some_list": ["4", None, True, {}]}
)
self.assertEqual(output, "Four")
@setup(
{
"length_is02": (
'{% if some_list|length_is:"4" %}Four{% else %}Not Four{% endif %}'
)
}
)
def test_length_is02(self):
output = self.engine.render_to_string(
"length_is02", {"some_list": ["4", None, True, {}, 17]}
)
self.assertEqual(output, "Not Four")
@setup({"length_is03": '{% if mystring|length_is:"4" %}Four{% endif %}'})
def test_length_is03(self):
output = self.engine.render_to_string("length_is03", {"mystring": "word"})
self.assertEqual(output, "Four")
@setup(
{
"length_is04": (
'{% if mystring|length_is:"4" %}Four{% else %}Not Four{% endif %}'
)
}
)
def test_length_is04(self):
output = self.engine.render_to_string("length_is04", {"mystring": "Python"})
self.assertEqual(output, "Not Four")
@setup(
{
"length_is05": (
'{% if mystring|length_is:"4" %}Four{% else %}Not Four{% endif %}'
)
}
)
def test_length_is05(self):
output = self.engine.render_to_string("length_is05", {"mystring": ""})
self.assertEqual(output, "Not Four")
@setup(
{
"length_is06": (
"{% with var|length as my_length %}{{ my_length }}{% endwith %}"
)
}
)
def test_length_is06(self):
output = self.engine.render_to_string("length_is06", {"var": "django"})
self.assertEqual(output, "6")
# Boolean return value from length_is should not be coerced to a string
@setup(
{
"length_is07": (
'{% if "X"|length_is:0 %}Length is 0{% else %}Length not 0{% endif %}'
)
}
)
def test_length_is07(self):
output = self.engine.render_to_string("length_is07", {})
self.assertEqual(output, "Length not 0")
@setup(
{
"length_is08": (
'{% if "X"|length_is:1 %}Length is 1{% else %}Length not 1{% endif %}'
)
}
)
def test_length_is08(self):
output = self.engine.render_to_string("length_is08", {})
self.assertEqual(output, "Length is 1")
# Invalid uses that should fail silently.
@setup({"length_is09": '{{ var|length_is:"fish" }}'})
def test_length_is09(self):
output = self.engine.render_to_string("length_is09", {"var": "django"})
self.assertEqual(output, "")
@setup({"length_is10": '{{ int|length_is:"1" }}'})
def test_length_is10(self):
output = self.engine.render_to_string("length_is10", {"int": 7})
self.assertEqual(output, "")
@setup({"length_is11": '{{ none|length_is:"1" }}'})
def test_length_is11(self):
output = self.engine.render_to_string("length_is11", {"none": None})
self.assertEqual(output, "")
@ignore_warnings(category=RemovedInDjango51Warning)
class FunctionTests(SimpleTestCase):
def test_empty_list(self):
self.assertIs(length_is([], 0), True)
self.assertIs(length_is([], 1), False)
def test_string(self):
self.assertIs(length_is("a", 1), True)
self.assertIs(length_is("a", 10), False)
class DeprecationTests(SimpleTestCase):
@setup(
{"length_is_warning": "{{ string|length_is:3 }}"},
test_once=True,
)
def test_length_is_warning(self):
msg = (
"The length_is template filter is deprecated in favor of the length "
"template filter and the == operator within an {% if %} tag."
)
with self.assertRaisesMessage(RemovedInDjango51Warning, msg):
self.engine.render_to_string("length_is_warning", {"string": "good"})
|
dea7c02f042cbec2f26889d01167ea88d749c5b4f51b26ba0edc4ffef43ac8a5 | import copy
import unittest
from io import StringIO
from unittest import mock
from django.core.exceptions import ImproperlyConfigured
from django.db import (
DEFAULT_DB_ALIAS,
DatabaseError,
NotSupportedError,
connection,
connections,
)
from django.db.backends.base.base import BaseDatabaseWrapper
from django.test import TestCase, override_settings
@unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL tests")
class Tests(TestCase):
databases = {"default", "other"}
def test_nodb_cursor(self):
"""
The _nodb_cursor() fallbacks to the default connection database when
access to the 'postgres' database is not granted.
"""
orig_connect = BaseDatabaseWrapper.connect
def mocked_connect(self):
if self.settings_dict["NAME"] is None:
raise DatabaseError()
return orig_connect(self)
with connection._nodb_cursor() as cursor:
self.assertIs(cursor.closed, False)
self.assertIsNotNone(cursor.db.connection)
self.assertIsNone(cursor.db.settings_dict["NAME"])
self.assertIs(cursor.closed, True)
self.assertIsNone(cursor.db.connection)
# Now assume the 'postgres' db isn't available
msg = (
"Normally Django will use a connection to the 'postgres' database "
"to avoid running initialization queries against the production "
"database when it's not needed (for example, when running tests). "
"Django was unable to create a connection to the 'postgres' "
"database and will use the first PostgreSQL database instead."
)
with self.assertWarnsMessage(RuntimeWarning, msg):
with mock.patch(
"django.db.backends.base.base.BaseDatabaseWrapper.connect",
side_effect=mocked_connect,
autospec=True,
):
with mock.patch.object(
connection,
"settings_dict",
{**connection.settings_dict, "NAME": "postgres"},
):
with connection._nodb_cursor() as cursor:
self.assertIs(cursor.closed, False)
self.assertIsNotNone(cursor.db.connection)
self.assertIs(cursor.closed, True)
self.assertIsNone(cursor.db.connection)
self.assertIsNotNone(cursor.db.settings_dict["NAME"])
self.assertEqual(
cursor.db.settings_dict["NAME"], connections["other"].settings_dict["NAME"]
)
# Cursor is yielded only for the first PostgreSQL database.
with self.assertWarnsMessage(RuntimeWarning, msg):
with mock.patch(
"django.db.backends.base.base.BaseDatabaseWrapper.connect",
side_effect=mocked_connect,
autospec=True,
):
with connection._nodb_cursor() as cursor:
self.assertIs(cursor.closed, False)
self.assertIsNotNone(cursor.db.connection)
def test_nodb_cursor_raises_postgres_authentication_failure(self):
"""
_nodb_cursor() re-raises authentication failure to the 'postgres' db
when other connection to the PostgreSQL database isn't available.
"""
def mocked_connect(self):
raise DatabaseError()
def mocked_all(self):
test_connection = copy.copy(connections[DEFAULT_DB_ALIAS])
test_connection.settings_dict = copy.deepcopy(connection.settings_dict)
test_connection.settings_dict["NAME"] = "postgres"
return [test_connection]
msg = (
"Normally Django will use a connection to the 'postgres' database "
"to avoid running initialization queries against the production "
"database when it's not needed (for example, when running tests). "
"Django was unable to create a connection to the 'postgres' "
"database and will use the first PostgreSQL database instead."
)
with self.assertWarnsMessage(RuntimeWarning, msg):
mocker_connections_all = mock.patch(
"django.utils.connection.BaseConnectionHandler.all",
side_effect=mocked_all,
autospec=True,
)
mocker_connect = mock.patch(
"django.db.backends.base.base.BaseDatabaseWrapper.connect",
side_effect=mocked_connect,
autospec=True,
)
with mocker_connections_all, mocker_connect:
with self.assertRaises(DatabaseError):
with connection._nodb_cursor():
pass
def test_nodb_cursor_reraise_exceptions(self):
with self.assertRaisesMessage(DatabaseError, "exception"):
with connection._nodb_cursor():
raise DatabaseError("exception")
def test_database_name_too_long(self):
from django.db.backends.postgresql.base import DatabaseWrapper
settings = connection.settings_dict.copy()
max_name_length = connection.ops.max_name_length()
settings["NAME"] = "a" + (max_name_length * "a")
msg = (
"The database name '%s' (%d characters) is longer than "
"PostgreSQL's limit of %s characters. Supply a shorter NAME in "
"settings.DATABASES."
) % (settings["NAME"], max_name_length + 1, max_name_length)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
DatabaseWrapper(settings).get_connection_params()
def test_database_name_empty(self):
from django.db.backends.postgresql.base import DatabaseWrapper
settings = connection.settings_dict.copy()
settings["NAME"] = ""
msg = (
"settings.DATABASES is improperly configured. Please supply the "
"NAME or OPTIONS['service'] value."
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
DatabaseWrapper(settings).get_connection_params()
def test_service_name(self):
from django.db.backends.postgresql.base import DatabaseWrapper
settings = connection.settings_dict.copy()
settings["OPTIONS"] = {"service": "my_service"}
settings["NAME"] = ""
params = DatabaseWrapper(settings).get_connection_params()
self.assertEqual(params["service"], "my_service")
self.assertNotIn("database", params)
def test_service_name_default_db(self):
# None is used to connect to the default 'postgres' db.
from django.db.backends.postgresql.base import DatabaseWrapper
settings = connection.settings_dict.copy()
settings["NAME"] = None
settings["OPTIONS"] = {"service": "django_test"}
params = DatabaseWrapper(settings).get_connection_params()
self.assertEqual(params["database"], "postgres")
self.assertNotIn("service", params)
def test_connect_and_rollback(self):
"""
PostgreSQL shouldn't roll back SET TIME ZONE, even if the first
transaction is rolled back (#17062).
"""
new_connection = connection.copy()
try:
# Ensure the database default time zone is different than
# the time zone in new_connection.settings_dict. We can
# get the default time zone by reset & show.
with new_connection.cursor() as cursor:
cursor.execute("RESET TIMEZONE")
cursor.execute("SHOW TIMEZONE")
db_default_tz = cursor.fetchone()[0]
new_tz = "Europe/Paris" if db_default_tz == "UTC" else "UTC"
new_connection.close()
# Invalidate timezone name cache, because the setting_changed
# handler cannot know about new_connection.
del new_connection.timezone_name
# Fetch a new connection with the new_tz as default
# time zone, run a query and rollback.
with self.settings(TIME_ZONE=new_tz):
new_connection.set_autocommit(False)
new_connection.rollback()
# Now let's see if the rollback rolled back the SET TIME ZONE.
with new_connection.cursor() as cursor:
cursor.execute("SHOW TIMEZONE")
tz = cursor.fetchone()[0]
self.assertEqual(new_tz, tz)
finally:
new_connection.close()
def test_connect_non_autocommit(self):
"""
The connection wrapper shouldn't believe that autocommit is enabled
after setting the time zone when AUTOCOMMIT is False (#21452).
"""
new_connection = connection.copy()
new_connection.settings_dict["AUTOCOMMIT"] = False
try:
# Open a database connection.
with new_connection.cursor():
self.assertFalse(new_connection.get_autocommit())
finally:
new_connection.close()
def test_connect_isolation_level(self):
"""
The transaction level can be configured with
DATABASES ['OPTIONS']['isolation_level'].
"""
from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE as serializable
# Since this is a django.test.TestCase, a transaction is in progress
# and the isolation level isn't reported as 0. This test assumes that
# PostgreSQL is configured with the default isolation level.
# Check the level on the psycopg2 connection, not the Django wrapper.
self.assertIsNone(connection.connection.isolation_level)
new_connection = connection.copy()
new_connection.settings_dict["OPTIONS"]["isolation_level"] = serializable
try:
# Start a transaction so the isolation level isn't reported as 0.
new_connection.set_autocommit(False)
# Check the level on the psycopg2 connection, not the Django wrapper.
self.assertEqual(new_connection.connection.isolation_level, serializable)
finally:
new_connection.close()
def test_connect_no_is_usable_checks(self):
new_connection = connection.copy()
try:
with mock.patch.object(new_connection, "is_usable") as is_usable:
new_connection.connect()
is_usable.assert_not_called()
finally:
new_connection.close()
def _select(self, val):
with connection.cursor() as cursor:
cursor.execute("SELECT %s", (val,))
return cursor.fetchone()[0]
def test_select_ascii_array(self):
a = ["awef"]
b = self._select(a)
self.assertEqual(a[0], b[0])
def test_select_unicode_array(self):
a = ["ᄲawef"]
b = self._select(a)
self.assertEqual(a[0], b[0])
def test_lookup_cast(self):
from django.db.backends.postgresql.operations import DatabaseOperations
do = DatabaseOperations(connection=None)
lookups = (
"iexact",
"contains",
"icontains",
"startswith",
"istartswith",
"endswith",
"iendswith",
"regex",
"iregex",
)
for lookup in lookups:
with self.subTest(lookup=lookup):
self.assertIn("::text", do.lookup_cast(lookup))
# RemovedInDjango51Warning.
for lookup in lookups:
for field_type in ("CICharField", "CIEmailField", "CITextField"):
with self.subTest(lookup=lookup, field_type=field_type):
self.assertIn(
"::citext", do.lookup_cast(lookup, internal_type=field_type)
)
def test_correct_extraction_psycopg2_version(self):
from django.db.backends.postgresql.base import psycopg2_version
with mock.patch("psycopg2.__version__", "4.2.1 (dt dec pq3 ext lo64)"):
self.assertEqual(psycopg2_version(), (4, 2, 1))
with mock.patch("psycopg2.__version__", "4.2b0.dev1 (dt dec pq3 ext lo64)"):
self.assertEqual(psycopg2_version(), (4, 2))
@override_settings(DEBUG=True)
def test_copy_cursors(self):
out = StringIO()
copy_expert_sql = "COPY django_session TO STDOUT (FORMAT CSV, HEADER)"
with connection.cursor() as cursor:
cursor.copy_expert(copy_expert_sql, out)
cursor.copy_to(out, "django_session")
self.assertEqual(
[q["sql"] for q in connection.queries],
[copy_expert_sql, "COPY django_session TO STDOUT"],
)
def test_get_database_version(self):
new_connection = connection.copy()
new_connection.pg_version = 110009
self.assertEqual(new_connection.get_database_version(), (11, 9))
@mock.patch.object(connection, "get_database_version", return_value=(11,))
def test_check_database_version_supported(self, mocked_get_database_version):
msg = "PostgreSQL 12 or later is required (found 11)."
with self.assertRaisesMessage(NotSupportedError, msg):
connection.check_database_version_supported()
self.assertTrue(mocked_get_database_version.called)
|
4bc3a941a823020227b2d131cdc46371b49f480731981473f1cabffcb909d2f3 | import tempfile
from io import StringIO
from django.contrib.gis import gdal
from django.contrib.gis.db.models import Extent, MakeLine, Union, functions
from django.contrib.gis.geos import (
GeometryCollection,
GEOSGeometry,
LinearRing,
LineString,
MultiLineString,
MultiPoint,
MultiPolygon,
Point,
Polygon,
fromstr,
)
from django.core.management import call_command
from django.db import DatabaseError, NotSupportedError, connection
from django.db.models import F, OuterRef, Subquery
from django.test import TestCase, skipUnlessDBFeature
from django.test.utils import CaptureQueriesContext
from ..utils import skipUnlessGISLookup
from .models import (
City,
Country,
Feature,
MinusOneSRID,
MultiFields,
NonConcreteModel,
PennsylvaniaCity,
State,
Track,
)
class GeoModelTest(TestCase):
fixtures = ["initial"]
def test_fixtures(self):
"Testing geographic model initialization from fixtures."
# Ensuring that data was loaded from initial data fixtures.
self.assertEqual(2, Country.objects.count())
self.assertEqual(8, City.objects.count())
self.assertEqual(2, State.objects.count())
def test_proxy(self):
"Testing Lazy-Geometry support (using the GeometryProxy)."
# Testing on a Point
pnt = Point(0, 0)
nullcity = City(name="NullCity", point=pnt)
nullcity.save()
# Making sure TypeError is thrown when trying to set with an
# incompatible type.
for bad in [5, 2.0, LineString((0, 0), (1, 1))]:
with self.assertRaisesMessage(TypeError, "Cannot set"):
nullcity.point = bad
# Now setting with a compatible GEOS Geometry, saving, and ensuring
# the save took, notice no SRID is explicitly set.
new = Point(5, 23)
nullcity.point = new
# Ensuring that the SRID is automatically set to that of the
# field after assignment, but before saving.
self.assertEqual(4326, nullcity.point.srid)
nullcity.save()
# Ensuring the point was saved correctly after saving
self.assertEqual(new, City.objects.get(name="NullCity").point)
# Setting the X and Y of the Point
nullcity.point.x = 23
nullcity.point.y = 5
# Checking assignments pre & post-save.
self.assertNotEqual(
Point(23, 5, srid=4326), City.objects.get(name="NullCity").point
)
nullcity.save()
self.assertEqual(
Point(23, 5, srid=4326), City.objects.get(name="NullCity").point
)
nullcity.delete()
# Testing on a Polygon
shell = LinearRing((0, 0), (0, 90), (100, 90), (100, 0), (0, 0))
inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40))
# Creating a State object using a built Polygon
ply = Polygon(shell, inner)
nullstate = State(name="NullState", poly=ply)
self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None
nullstate.save()
ns = State.objects.get(name="NullState")
self.assertEqual(connection.ops.Adapter._fix_polygon(ply), ns.poly)
# Testing the `ogr` and `srs` lazy-geometry properties.
self.assertIsInstance(ns.poly.ogr, gdal.OGRGeometry)
self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb)
self.assertIsInstance(ns.poly.srs, gdal.SpatialReference)
self.assertEqual("WGS 84", ns.poly.srs.name)
# Changing the interior ring on the poly attribute.
new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30))
ns.poly[1] = new_inner
ply[1] = new_inner
self.assertEqual(4326, ns.poly.srid)
ns.save()
self.assertEqual(
connection.ops.Adapter._fix_polygon(ply),
State.objects.get(name="NullState").poly,
)
ns.delete()
@skipUnlessDBFeature("supports_transform")
def test_lookup_insert_transform(self):
"Testing automatic transform for lookups and inserts."
# San Antonio in 'WGS84' (SRID 4326)
sa_4326 = "POINT (-98.493183 29.424170)"
wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84
# San Antonio in 'WGS 84 / Pseudo-Mercator' (SRID 3857)
other_srid_pnt = wgs_pnt.transform(3857, clone=True)
# Constructing & querying with a point from a different SRID. Oracle
# `SDO_OVERLAPBDYINTERSECT` operates differently from
# `ST_Intersects`, so contains is used instead.
if connection.ops.oracle:
tx = Country.objects.get(mpoly__contains=other_srid_pnt)
else:
tx = Country.objects.get(mpoly__intersects=other_srid_pnt)
self.assertEqual("Texas", tx.name)
# Creating San Antonio. Remember the Alamo.
sa = City.objects.create(name="San Antonio", point=other_srid_pnt)
# Now verifying that San Antonio was transformed correctly
sa = City.objects.get(name="San Antonio")
self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6)
self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6)
# If the GeometryField SRID is -1, then we shouldn't perform any
# transformation if the SRID of the input geometry is different.
m1 = MinusOneSRID(geom=Point(17, 23, srid=4326))
m1.save()
self.assertEqual(-1, m1.geom.srid)
def test_createnull(self):
"Testing creating a model instance and the geometry being None"
c = City()
self.assertIsNone(c.point)
def test_geometryfield(self):
"Testing the general GeometryField."
Feature(name="Point", geom=Point(1, 1)).save()
Feature(name="LineString", geom=LineString((0, 0), (1, 1), (5, 5))).save()
Feature(
name="Polygon",
geom=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))),
).save()
Feature(
name="GeometryCollection",
geom=GeometryCollection(
Point(2, 2),
LineString((0, 0), (2, 2)),
Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))),
),
).save()
f_1 = Feature.objects.get(name="Point")
self.assertIsInstance(f_1.geom, Point)
self.assertEqual((1.0, 1.0), f_1.geom.tuple)
f_2 = Feature.objects.get(name="LineString")
self.assertIsInstance(f_2.geom, LineString)
self.assertEqual(((0.0, 0.0), (1.0, 1.0), (5.0, 5.0)), f_2.geom.tuple)
f_3 = Feature.objects.get(name="Polygon")
self.assertIsInstance(f_3.geom, Polygon)
f_4 = Feature.objects.get(name="GeometryCollection")
self.assertIsInstance(f_4.geom, GeometryCollection)
self.assertEqual(f_3.geom, f_4.geom[2])
@skipUnlessDBFeature("supports_transform")
def test_inherited_geofields(self):
"Database functions on inherited Geometry fields."
# Creating a Pennsylvanian city.
PennsylvaniaCity.objects.create(
name="Mansfield", county="Tioga", point="POINT(-77.071445 41.823881)"
)
# All transformation SQL will need to be performed on the
# _parent_ table.
qs = PennsylvaniaCity.objects.annotate(
new_point=functions.Transform("point", srid=32128)
)
self.assertEqual(1, qs.count())
for pc in qs:
self.assertEqual(32128, pc.new_point.srid)
def test_raw_sql_query(self):
"Testing raw SQL query."
cities1 = City.objects.all()
point_select = connection.ops.select % "point"
cities2 = list(
City.objects.raw(
"select id, name, %s as point from geoapp_city" % point_select
)
)
self.assertEqual(len(cities1), len(cities2))
with self.assertNumQueries(0): # Ensure point isn't deferred.
self.assertIsInstance(cities2[0].point, Point)
def test_gis_query_as_string(self):
"""GIS queries can be represented as strings."""
query = City.objects.filter(point__within=Polygon.from_bbox((0, 0, 2, 2)))
self.assertIn(
connection.ops.quote_name(City._meta.db_table),
str(query.query),
)
def test_dumpdata_loaddata_cycle(self):
"""
Test a dumpdata/loaddata cycle with geographic data.
"""
out = StringIO()
original_data = list(City.objects.order_by("name"))
call_command("dumpdata", "geoapp.City", stdout=out)
result = out.getvalue()
houston = City.objects.get(name="Houston")
self.assertIn('"point": "%s"' % houston.point.ewkt, result)
# Reload now dumped data
with tempfile.NamedTemporaryFile(mode="w", suffix=".json") as tmp:
tmp.write(result)
tmp.seek(0)
call_command("loaddata", tmp.name, verbosity=0)
self.assertEqual(original_data, list(City.objects.order_by("name")))
@skipUnlessDBFeature("supports_empty_geometries")
def test_empty_geometries(self):
geometry_classes = [
Point,
LineString,
LinearRing,
Polygon,
MultiPoint,
MultiLineString,
MultiPolygon,
GeometryCollection,
]
for klass in geometry_classes:
g = klass(srid=4326)
feature = Feature.objects.create(name="Empty %s" % klass.__name__, geom=g)
feature.refresh_from_db()
if klass is LinearRing:
# LinearRing isn't representable in WKB, so GEOSGeomtry.wkb
# uses LineString instead.
g = LineString(srid=4326)
self.assertEqual(feature.geom, g)
self.assertEqual(feature.geom.srid, g.srid)
class GeoLookupTest(TestCase):
fixtures = ["initial"]
def test_disjoint_lookup(self):
"Testing the `disjoint` lookup type."
ptown = City.objects.get(name="Pueblo")
qs1 = City.objects.filter(point__disjoint=ptown.point)
self.assertEqual(7, qs1.count())
qs2 = State.objects.filter(poly__disjoint=ptown.point)
self.assertEqual(1, qs2.count())
self.assertEqual("Kansas", qs2[0].name)
def test_contains_contained_lookups(self):
"Testing the 'contained', 'contains', and 'bbcontains' lookup types."
# Getting Texas, yes we were a country -- once ;)
texas = Country.objects.get(name="Texas")
# Seeing what cities are in Texas, should get Houston and Dallas,
# and Oklahoma City because 'contained' only checks on the
# _bounding box_ of the Geometries.
if connection.features.supports_contained_lookup:
qs = City.objects.filter(point__contained=texas.mpoly)
self.assertEqual(3, qs.count())
cities = ["Houston", "Dallas", "Oklahoma City"]
for c in qs:
self.assertIn(c.name, cities)
# Pulling out some cities.
houston = City.objects.get(name="Houston")
wellington = City.objects.get(name="Wellington")
pueblo = City.objects.get(name="Pueblo")
okcity = City.objects.get(name="Oklahoma City")
lawrence = City.objects.get(name="Lawrence")
# Now testing contains on the countries using the points for
# Houston and Wellington.
tx = Country.objects.get(mpoly__contains=houston.point) # Query w/GEOSGeometry
nz = Country.objects.get(
mpoly__contains=wellington.point.hex
) # Query w/EWKBHEX
self.assertEqual("Texas", tx.name)
self.assertEqual("New Zealand", nz.name)
# Testing `contains` on the states using the point for Lawrence.
ks = State.objects.get(poly__contains=lawrence.point)
self.assertEqual("Kansas", ks.name)
# Pueblo and Oklahoma City (even though OK City is within the bounding
# box of Texas) are not contained in Texas or New Zealand.
self.assertEqual(
len(Country.objects.filter(mpoly__contains=pueblo.point)), 0
) # Query w/GEOSGeometry object
self.assertEqual(
len(Country.objects.filter(mpoly__contains=okcity.point.wkt)), 0
) # Query w/WKT
# OK City is contained w/in bounding box of Texas.
if connection.features.supports_bbcontains_lookup:
qs = Country.objects.filter(mpoly__bbcontains=okcity.point)
self.assertEqual(1, len(qs))
self.assertEqual("Texas", qs[0].name)
@skipUnlessDBFeature("supports_crosses_lookup")
def test_crosses_lookup(self):
Track.objects.create(name="Line1", line=LineString([(-95, 29), (-60, 0)]))
self.assertEqual(
Track.objects.filter(
line__crosses=LineString([(-95, 0), (-60, 29)])
).count(),
1,
)
self.assertEqual(
Track.objects.filter(
line__crosses=LineString([(-95, 30), (0, 30)])
).count(),
0,
)
@skipUnlessDBFeature("supports_isvalid_lookup")
def test_isvalid_lookup(self):
invalid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))")
State.objects.create(name="invalid", poly=invalid_geom)
qs = State.objects.all()
if connection.ops.oracle:
# Kansas has adjacent vertices with distance 6.99244813842e-12
# which is smaller than the default Oracle tolerance.
qs = qs.exclude(name="Kansas")
self.assertEqual(
State.objects.filter(name="Kansas", poly__isvalid=False).count(), 1
)
self.assertEqual(qs.filter(poly__isvalid=False).count(), 1)
self.assertEqual(qs.filter(poly__isvalid=True).count(), qs.count() - 1)
@skipUnlessGISLookup("left", "right")
def test_left_right_lookups(self):
"Testing the 'left' and 'right' lookup types."
# Left: A << B => true if xmax(A) < xmin(B)
# Right: A >> B => true if xmin(A) > xmax(B)
# See: BOX2D_left() and BOX2D_right() in lwgeom_box2dfloat4.c in PostGIS source.
# Getting the borders for Colorado & Kansas
co_border = State.objects.get(name="Colorado").poly
ks_border = State.objects.get(name="Kansas").poly
# Note: Wellington has an 'X' value of 174, so it will not be considered
# to the left of CO.
# These cities should be strictly to the right of the CO border.
cities = [
"Houston",
"Dallas",
"Oklahoma City",
"Lawrence",
"Chicago",
"Wellington",
]
qs = City.objects.filter(point__right=co_border)
self.assertEqual(6, len(qs))
for c in qs:
self.assertIn(c.name, cities)
# These cities should be strictly to the right of the KS border.
cities = ["Chicago", "Wellington"]
qs = City.objects.filter(point__right=ks_border)
self.assertEqual(2, len(qs))
for c in qs:
self.assertIn(c.name, cities)
# Note: Wellington has an 'X' value of 174, so it will not be considered
# to the left of CO.
vic = City.objects.get(point__left=co_border)
self.assertEqual("Victoria", vic.name)
cities = ["Pueblo", "Victoria"]
qs = City.objects.filter(point__left=ks_border)
self.assertEqual(2, len(qs))
for c in qs:
self.assertIn(c.name, cities)
@skipUnlessGISLookup("strictly_above", "strictly_below")
def test_strictly_above_below_lookups(self):
dallas = City.objects.get(name="Dallas")
self.assertQuerySetEqual(
City.objects.filter(point__strictly_above=dallas.point).order_by("name"),
["Chicago", "Lawrence", "Oklahoma City", "Pueblo", "Victoria"],
lambda b: b.name,
)
self.assertQuerySetEqual(
City.objects.filter(point__strictly_below=dallas.point).order_by("name"),
["Houston", "Wellington"],
lambda b: b.name,
)
def test_equals_lookups(self):
"Testing the 'same_as' and 'equals' lookup types."
pnt = fromstr("POINT (-95.363151 29.763374)", srid=4326)
c1 = City.objects.get(point=pnt)
c2 = City.objects.get(point__same_as=pnt)
c3 = City.objects.get(point__equals=pnt)
for c in [c1, c2, c3]:
self.assertEqual("Houston", c.name)
@skipUnlessDBFeature("supports_null_geometries")
def test_null_geometries(self):
"Testing NULL geometry support, and the `isnull` lookup type."
# Creating a state with a NULL boundary.
State.objects.create(name="Puerto Rico")
# Querying for both NULL and Non-NULL values.
nullqs = State.objects.filter(poly__isnull=True)
validqs = State.objects.filter(poly__isnull=False)
# Puerto Rico should be NULL (it's a commonwealth unincorporated territory)
self.assertEqual(1, len(nullqs))
self.assertEqual("Puerto Rico", nullqs[0].name)
# GeometryField=None is an alias for __isnull=True.
self.assertCountEqual(State.objects.filter(poly=None), nullqs)
self.assertCountEqual(State.objects.exclude(poly=None), validqs)
# The valid states should be Colorado & Kansas
self.assertEqual(2, len(validqs))
state_names = [s.name for s in validqs]
self.assertIn("Colorado", state_names)
self.assertIn("Kansas", state_names)
# Saving another commonwealth w/a NULL geometry.
nmi = State.objects.create(name="Northern Mariana Islands", poly=None)
self.assertIsNone(nmi.poly)
# Assigning a geometry and saving -- then UPDATE back to NULL.
nmi.poly = "POLYGON((0 0,1 0,1 1,1 0,0 0))"
nmi.save()
State.objects.filter(name="Northern Mariana Islands").update(poly=None)
self.assertIsNone(State.objects.get(name="Northern Mariana Islands").poly)
@skipUnlessDBFeature(
"supports_null_geometries", "supports_crosses_lookup", "supports_relate_lookup"
)
def test_null_geometries_excluded_in_lookups(self):
"""NULL features are excluded in spatial lookup functions."""
null = State.objects.create(name="NULL", poly=None)
queries = [
("equals", Point(1, 1)),
("disjoint", Point(1, 1)),
("touches", Point(1, 1)),
("crosses", LineString((0, 0), (1, 1), (5, 5))),
("within", Point(1, 1)),
("overlaps", LineString((0, 0), (1, 1), (5, 5))),
("contains", LineString((0, 0), (1, 1), (5, 5))),
("intersects", LineString((0, 0), (1, 1), (5, 5))),
("relate", (Point(1, 1), "T*T***FF*")),
("same_as", Point(1, 1)),
("exact", Point(1, 1)),
("coveredby", Point(1, 1)),
("covers", Point(1, 1)),
]
for lookup, geom in queries:
with self.subTest(lookup=lookup):
self.assertNotIn(
null, State.objects.filter(**{"poly__%s" % lookup: geom})
)
def test_wkt_string_in_lookup(self):
# Valid WKT strings don't emit error logs.
with self.assertNoLogs("django.contrib.gis", "ERROR"):
State.objects.filter(poly__intersects="LINESTRING(0 0, 1 1, 5 5)")
@skipUnlessDBFeature("supports_relate_lookup")
def test_relate_lookup(self):
"Testing the 'relate' lookup type."
# To make things more interesting, we will have our Texas reference point in
# different SRIDs.
pnt1 = fromstr("POINT (649287.0363174 4177429.4494686)", srid=2847)
pnt2 = fromstr("POINT(-98.4919715741052 29.4333344025053)", srid=4326)
# Not passing in a geometry as first param raises a TypeError when
# initializing the QuerySet.
with self.assertRaises(ValueError):
Country.objects.filter(mpoly__relate=(23, "foo"))
# Making sure the right exception is raised for the given
# bad arguments.
for bad_args, e in [
((pnt1, 0), ValueError),
((pnt2, "T*T***FF*", 0), ValueError),
]:
qs = Country.objects.filter(mpoly__relate=bad_args)
with self.assertRaises(e):
qs.count()
contains_mask = "T*T***FF*"
within_mask = "T*F**F***"
intersects_mask = "T********"
# Relate works differently on Oracle.
if connection.ops.oracle:
contains_mask = "contains"
within_mask = "inside"
# TODO: This is not quite the same as the PostGIS mask above
intersects_mask = "overlapbdyintersect"
# Testing contains relation mask.
if connection.features.supports_transform:
self.assertEqual(
Country.objects.get(mpoly__relate=(pnt1, contains_mask)).name,
"Texas",
)
self.assertEqual(
"Texas", Country.objects.get(mpoly__relate=(pnt2, contains_mask)).name
)
# Testing within relation mask.
ks = State.objects.get(name="Kansas")
self.assertEqual(
"Lawrence", City.objects.get(point__relate=(ks.poly, within_mask)).name
)
# Testing intersection relation mask.
if not connection.ops.oracle:
if connection.features.supports_transform:
self.assertEqual(
Country.objects.get(mpoly__relate=(pnt1, intersects_mask)).name,
"Texas",
)
self.assertEqual(
"Texas", Country.objects.get(mpoly__relate=(pnt2, intersects_mask)).name
)
self.assertEqual(
"Lawrence",
City.objects.get(point__relate=(ks.poly, intersects_mask)).name,
)
# With a complex geometry expression
mask = "anyinteract" if connection.ops.oracle else within_mask
self.assertFalse(
City.objects.exclude(
point__relate=(functions.Union("point", "point"), mask)
)
)
def test_gis_lookups_with_complex_expressions(self):
multiple_arg_lookups = {
"dwithin",
"relate",
} # These lookups are tested elsewhere.
lookups = connection.ops.gis_operators.keys() - multiple_arg_lookups
self.assertTrue(lookups, "No lookups found")
for lookup in lookups:
with self.subTest(lookup):
City.objects.filter(
**{"point__" + lookup: functions.Union("point", "point")}
).exists()
def test_subquery_annotation(self):
multifields = MultiFields.objects.create(
city=City.objects.create(point=Point(1, 1)),
point=Point(2, 2),
poly=Polygon.from_bbox((0, 0, 2, 2)),
)
qs = MultiFields.objects.annotate(
city_point=Subquery(
City.objects.filter(
id=OuterRef("city"),
).values("point")
),
).filter(
city_point__within=F("poly"),
)
self.assertEqual(qs.get(), multifields)
class GeoQuerySetTest(TestCase):
# TODO: GeoQuerySet is removed, organize these test better.
fixtures = ["initial"]
@skipUnlessDBFeature("supports_extent_aggr")
def test_extent(self):
"""
Testing the `Extent` aggregate.
"""
# Reference query:
# SELECT ST_extent(point)
# FROM geoapp_city
# WHERE (name='Houston' or name='Dallas');`
# => BOX(-96.8016128540039 29.7633724212646,-95.3631439208984 32.7820587158203)
expected = (
-96.8016128540039,
29.7633724212646,
-95.3631439208984,
32.782058715820,
)
qs = City.objects.filter(name__in=("Houston", "Dallas"))
extent = qs.aggregate(Extent("point"))["point__extent"]
for val, exp in zip(extent, expected):
self.assertAlmostEqual(exp, val, 4)
self.assertIsNone(
City.objects.filter(name=("Smalltown")).aggregate(Extent("point"))[
"point__extent"
]
)
@skipUnlessDBFeature("supports_extent_aggr")
def test_extent_with_limit(self):
"""
Testing if extent supports limit.
"""
extent1 = City.objects.aggregate(Extent("point"))["point__extent"]
extent2 = City.objects.all()[:3].aggregate(Extent("point"))["point__extent"]
self.assertNotEqual(extent1, extent2)
def test_make_line(self):
"""
Testing the `MakeLine` aggregate.
"""
if not connection.features.supports_make_line_aggr:
with self.assertRaises(NotSupportedError):
City.objects.aggregate(MakeLine("point"))
return
# MakeLine on an inappropriate field returns simply None
self.assertIsNone(State.objects.aggregate(MakeLine("poly"))["poly__makeline"])
# Reference query:
# SELECT AsText(ST_MakeLine(geoapp_city.point)) FROM geoapp_city;
ref_line = GEOSGeometry(
"LINESTRING(-95.363151 29.763374,-96.801611 32.782057,"
"-97.521157 34.464642,174.783117 -41.315268,-104.609252 38.255001,"
"-95.23506 38.971823,-87.650175 41.850385,-123.305196 48.462611)",
srid=4326,
)
# We check for equality with a tolerance of 10e-5 which is a lower bound
# of the precisions of ref_line coordinates
line = City.objects.aggregate(MakeLine("point"))["point__makeline"]
self.assertTrue(
ref_line.equals_exact(line, tolerance=10e-5), "%s != %s" % (ref_line, line)
)
@skipUnlessDBFeature("supports_union_aggr")
def test_unionagg(self):
"""
Testing the `Union` aggregate.
"""
tx = Country.objects.get(name="Texas").mpoly
# Houston, Dallas -- Ordering may differ depending on backend or GEOS version.
union = GEOSGeometry("MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)")
qs = City.objects.filter(point__within=tx)
with self.assertRaises(ValueError):
qs.aggregate(Union("name"))
# Using `field_name` keyword argument in one query and specifying an
# order in the other (which should not be used because this is
# an aggregate method on a spatial column)
u1 = qs.aggregate(Union("point"))["point__union"]
u2 = qs.order_by("name").aggregate(Union("point"))["point__union"]
self.assertTrue(union.equals(u1))
self.assertTrue(union.equals(u2))
qs = City.objects.filter(name="NotACity")
self.assertIsNone(qs.aggregate(Union("point"))["point__union"])
@skipUnlessDBFeature("supports_union_aggr")
def test_geoagg_subquery(self):
tx = Country.objects.get(name="Texas")
union = GEOSGeometry("MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)")
# Use distinct() to force the usage of a subquery for aggregation.
with CaptureQueriesContext(connection) as ctx:
self.assertIs(
union.equals(
City.objects.filter(point__within=tx.mpoly)
.distinct()
.aggregate(
Union("point"),
)["point__union"],
),
True,
)
self.assertIn("subquery", ctx.captured_queries[0]["sql"])
@skipUnlessDBFeature("supports_tolerance_parameter")
def test_unionagg_tolerance(self):
City.objects.create(
point=fromstr("POINT(-96.467222 32.751389)", srid=4326),
name="Forney",
)
tx = Country.objects.get(name="Texas").mpoly
# Tolerance is greater than distance between Forney and Dallas, that's
# why Dallas is ignored.
forney_houston = GEOSGeometry(
"MULTIPOINT(-95.363151 29.763374, -96.467222 32.751389)",
srid=4326,
)
self.assertIs(
forney_houston.equals_exact(
City.objects.filter(point__within=tx).aggregate(
Union("point", tolerance=32000),
)["point__union"],
tolerance=10e-6,
),
True,
)
@skipUnlessDBFeature("supports_tolerance_parameter")
def test_unionagg_tolerance_escaping(self):
tx = Country.objects.get(name="Texas").mpoly
with self.assertRaises(DatabaseError):
City.objects.filter(point__within=tx).aggregate(
Union("point", tolerance="0.05))), (((1"),
)
def test_within_subquery(self):
"""
Using a queryset inside a geo lookup is working (using a subquery)
(#14483).
"""
tex_cities = City.objects.filter(
point__within=Country.objects.filter(name="Texas").values("mpoly")
).order_by("name")
self.assertEqual(
list(tex_cities.values_list("name", flat=True)), ["Dallas", "Houston"]
)
def test_non_concrete_field(self):
NonConcreteModel.objects.create(point=Point(0, 0), name="name")
list(NonConcreteModel.objects.all())
def test_values_srid(self):
for c, v in zip(City.objects.all(), City.objects.values()):
self.assertEqual(c.point.srid, v["point"].srid)
|
7fea3caa310ad1fea862f89d8557594cce1a395f6694c5fdbd9199c7fafdeb08 | import binascii
from django.contrib.gis.geos import (
GEOSGeometry,
Point,
Polygon,
WKBReader,
WKBWriter,
WKTReader,
WKTWriter,
)
from django.contrib.gis.geos.libgeos import geos_version_tuple
from django.test import SimpleTestCase
class GEOSIOTest(SimpleTestCase):
def test01_wktreader(self):
# Creating a WKTReader instance
wkt_r = WKTReader()
wkt = "POINT (5 23)"
# read() should return a GEOSGeometry
ref = GEOSGeometry(wkt)
g1 = wkt_r.read(wkt.encode())
g2 = wkt_r.read(wkt)
for geom in (g1, g2):
self.assertEqual(ref, geom)
# Should only accept string objects.
with self.assertRaises(TypeError):
wkt_r.read(1)
with self.assertRaises(TypeError):
wkt_r.read(memoryview(b"foo"))
def test02_wktwriter(self):
# Creating a WKTWriter instance, testing its ptr property.
wkt_w = WKTWriter()
with self.assertRaises(TypeError):
wkt_w.ptr = WKTReader.ptr_type()
ref = GEOSGeometry("POINT (5 23)")
ref_wkt = "POINT (5.0000000000000000 23.0000000000000000)"
self.assertEqual(ref_wkt, wkt_w.write(ref).decode())
def test_wktwriter_constructor_arguments(self):
wkt_w = WKTWriter(dim=3, trim=True, precision=3)
ref = GEOSGeometry("POINT (5.34562 23 1.5)")
if geos_version_tuple() > (3, 10):
ref_wkt = "POINT Z (5.346 23 1.5)"
else:
ref_wkt = "POINT Z (5.35 23 1.5)"
self.assertEqual(ref_wkt, wkt_w.write(ref).decode())
def test03_wkbreader(self):
# Creating a WKBReader instance
wkb_r = WKBReader()
hex_bin = b"000000000140140000000000004037000000000000"
hex_str = "000000000140140000000000004037000000000000"
wkb = memoryview(binascii.a2b_hex(hex_bin))
ref = GEOSGeometry(hex_bin)
# read() should return a GEOSGeometry on either a hex string or
# a WKB buffer.
g1 = wkb_r.read(wkb)
g2 = wkb_r.read(hex_bin)
g3 = wkb_r.read(hex_str)
for geom in (g1, g2, g3):
self.assertEqual(ref, geom)
bad_input = (1, 5.23, None, False)
for bad_wkb in bad_input:
with self.assertRaises(TypeError):
wkb_r.read(bad_wkb)
def test04_wkbwriter(self):
wkb_w = WKBWriter()
# Representations of 'POINT (5 23)' in hex -- one normal and
# the other with the byte order changed.
g = GEOSGeometry("POINT (5 23)")
hex1 = b"010100000000000000000014400000000000003740"
wkb1 = memoryview(binascii.a2b_hex(hex1))
hex2 = b"000000000140140000000000004037000000000000"
wkb2 = memoryview(binascii.a2b_hex(hex2))
self.assertEqual(hex1, wkb_w.write_hex(g))
self.assertEqual(wkb1, wkb_w.write(g))
# Ensuring bad byteorders are not accepted.
for bad_byteorder in (-1, 2, 523, "foo", None):
# Equivalent of `wkb_w.byteorder = bad_byteorder`
with self.assertRaises(ValueError):
wkb_w._set_byteorder(bad_byteorder)
# Setting the byteorder to 0 (for Big Endian)
wkb_w.byteorder = 0
self.assertEqual(hex2, wkb_w.write_hex(g))
self.assertEqual(wkb2, wkb_w.write(g))
# Back to Little Endian
wkb_w.byteorder = 1
# Now, trying out the 3D and SRID flags.
g = GEOSGeometry("POINT (5 23 17)")
g.srid = 4326
hex3d = b"0101000080000000000000144000000000000037400000000000003140"
wkb3d = memoryview(binascii.a2b_hex(hex3d))
hex3d_srid = (
b"01010000A0E6100000000000000000144000000000000037400000000000003140"
)
wkb3d_srid = memoryview(binascii.a2b_hex(hex3d_srid))
# Ensuring bad output dimensions are not accepted
for bad_outdim in (-1, 0, 1, 4, 423, "foo", None):
with self.assertRaisesMessage(
ValueError, "WKB output dimension must be 2 or 3"
):
wkb_w.outdim = bad_outdim
# Now setting the output dimensions to be 3
wkb_w.outdim = 3
self.assertEqual(hex3d, wkb_w.write_hex(g))
self.assertEqual(wkb3d, wkb_w.write(g))
# Telling the WKBWriter to include the srid in the representation.
wkb_w.srid = True
self.assertEqual(hex3d_srid, wkb_w.write_hex(g))
self.assertEqual(wkb3d_srid, wkb_w.write(g))
def test_wkt_writer_trim(self):
wkt_w = WKTWriter()
self.assertFalse(wkt_w.trim)
self.assertEqual(
wkt_w.write(Point(1, 1)), b"POINT (1.0000000000000000 1.0000000000000000)"
)
wkt_w.trim = True
self.assertTrue(wkt_w.trim)
self.assertEqual(wkt_w.write(Point(1, 1)), b"POINT (1 1)")
self.assertEqual(wkt_w.write(Point(1.1, 1)), b"POINT (1.1 1)")
self.assertEqual(
wkt_w.write(Point(1.0 / 3, 1)), b"POINT (0.3333333333333333 1)"
)
wkt_w.trim = False
self.assertFalse(wkt_w.trim)
self.assertEqual(
wkt_w.write(Point(1, 1)), b"POINT (1.0000000000000000 1.0000000000000000)"
)
def test_wkt_writer_precision(self):
wkt_w = WKTWriter()
self.assertIsNone(wkt_w.precision)
self.assertEqual(
wkt_w.write(Point(1.0 / 3, 2.0 / 3)),
b"POINT (0.3333333333333333 0.6666666666666666)",
)
wkt_w.precision = 1
self.assertEqual(wkt_w.precision, 1)
self.assertEqual(wkt_w.write(Point(1.0 / 3, 2.0 / 3)), b"POINT (0.3 0.7)")
wkt_w.precision = 0
self.assertEqual(wkt_w.precision, 0)
self.assertEqual(wkt_w.write(Point(1.0 / 3, 2.0 / 3)), b"POINT (0 1)")
wkt_w.precision = None
self.assertIsNone(wkt_w.precision)
self.assertEqual(
wkt_w.write(Point(1.0 / 3, 2.0 / 3)),
b"POINT (0.3333333333333333 0.6666666666666666)",
)
with self.assertRaisesMessage(
AttributeError, "WKT output rounding precision must be "
):
wkt_w.precision = "potato"
def test_empty_point_wkb(self):
p = Point(srid=4326)
wkb_w = WKBWriter()
wkb_w.srid = False
with self.assertRaisesMessage(
ValueError, "Empty point is not representable in WKB."
):
wkb_w.write(p)
with self.assertRaisesMessage(
ValueError, "Empty point is not representable in WKB."
):
wkb_w.write_hex(p)
wkb_w.srid = True
for byteorder, hex in enumerate(
[
b"0020000001000010E67FF80000000000007FF8000000000000",
b"0101000020E6100000000000000000F87F000000000000F87F",
]
):
wkb_w.byteorder = byteorder
self.assertEqual(wkb_w.write_hex(p), hex)
self.assertEqual(GEOSGeometry(wkb_w.write_hex(p)), p)
self.assertEqual(wkb_w.write(p), memoryview(binascii.a2b_hex(hex)))
self.assertEqual(GEOSGeometry(wkb_w.write(p)), p)
def test_empty_polygon_wkb(self):
p = Polygon(srid=4326)
p_no_srid = Polygon()
wkb_w = WKBWriter()
wkb_w.srid = True
for byteorder, hexes in enumerate(
[
(b"000000000300000000", b"0020000003000010E600000000"),
(b"010300000000000000", b"0103000020E610000000000000"),
]
):
wkb_w.byteorder = byteorder
for srid, hex in enumerate(hexes):
wkb_w.srid = srid
self.assertEqual(wkb_w.write_hex(p), hex)
self.assertEqual(
GEOSGeometry(wkb_w.write_hex(p)), p if srid else p_no_srid
)
self.assertEqual(wkb_w.write(p), memoryview(binascii.a2b_hex(hex)))
self.assertEqual(GEOSGeometry(wkb_w.write(p)), p if srid else p_no_srid)
|
265a3c5e66b0c01f029f7592dad68db0647297a4e548c0f0c39aa7bde6fa1559 | import os
import shutil
import struct
import tempfile
import zipfile
from pathlib import Path
from unittest import mock
from django.contrib.gis.gdal import GDALRaster, SpatialReference
from django.contrib.gis.gdal.error import GDALException
from django.contrib.gis.gdal.raster.band import GDALBand
from django.contrib.gis.shortcuts import numpy
from django.test import SimpleTestCase
from ..data.rasters.textrasters import JSON_RASTER
class GDALRasterTests(SimpleTestCase):
"""
Test a GDALRaster instance created from a file (GeoTiff).
"""
def setUp(self):
self.rs_path = os.path.join(
os.path.dirname(__file__), "../data/rasters/raster.tif"
)
self.rs = GDALRaster(self.rs_path)
def test_gdalraster_input_as_path(self):
rs_path = Path(__file__).parent.parent / "data" / "rasters" / "raster.tif"
rs = GDALRaster(rs_path)
self.assertEqual(str(rs_path), rs.name)
def test_rs_name_repr(self):
self.assertEqual(self.rs_path, self.rs.name)
self.assertRegex(repr(self.rs), r"<Raster object at 0x\w+>")
def test_rs_driver(self):
self.assertEqual(self.rs.driver.name, "GTiff")
def test_rs_size(self):
self.assertEqual(self.rs.width, 163)
self.assertEqual(self.rs.height, 174)
def test_rs_srs(self):
self.assertEqual(self.rs.srs.srid, 3086)
self.assertEqual(self.rs.srs.units, (1.0, "metre"))
def test_rs_srid(self):
rast = GDALRaster(
{
"width": 16,
"height": 16,
"srid": 4326,
}
)
self.assertEqual(rast.srid, 4326)
rast.srid = 3086
self.assertEqual(rast.srid, 3086)
def test_geotransform_and_friends(self):
# Assert correct values for file based raster
self.assertEqual(
self.rs.geotransform,
[511700.4680706557, 100.0, 0.0, 435103.3771231986, 0.0, -100.0],
)
self.assertEqual(self.rs.origin, [511700.4680706557, 435103.3771231986])
self.assertEqual(self.rs.origin.x, 511700.4680706557)
self.assertEqual(self.rs.origin.y, 435103.3771231986)
self.assertEqual(self.rs.scale, [100.0, -100.0])
self.assertEqual(self.rs.scale.x, 100.0)
self.assertEqual(self.rs.scale.y, -100.0)
self.assertEqual(self.rs.skew, [0, 0])
self.assertEqual(self.rs.skew.x, 0)
self.assertEqual(self.rs.skew.y, 0)
# Create in-memory rasters and change gtvalues
rsmem = GDALRaster(JSON_RASTER)
# geotransform accepts both floats and ints
rsmem.geotransform = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
self.assertEqual(rsmem.geotransform, [0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
rsmem.geotransform = range(6)
self.assertEqual(rsmem.geotransform, [float(x) for x in range(6)])
self.assertEqual(rsmem.origin, [0, 3])
self.assertEqual(rsmem.origin.x, 0)
self.assertEqual(rsmem.origin.y, 3)
self.assertEqual(rsmem.scale, [1, 5])
self.assertEqual(rsmem.scale.x, 1)
self.assertEqual(rsmem.scale.y, 5)
self.assertEqual(rsmem.skew, [2, 4])
self.assertEqual(rsmem.skew.x, 2)
self.assertEqual(rsmem.skew.y, 4)
self.assertEqual(rsmem.width, 5)
self.assertEqual(rsmem.height, 5)
def test_geotransform_bad_inputs(self):
rsmem = GDALRaster(JSON_RASTER)
error_geotransforms = [
[1, 2],
[1, 2, 3, 4, 5, "foo"],
[1, 2, 3, 4, 5, 6, "foo"],
]
msg = "Geotransform must consist of 6 numeric values."
for geotransform in error_geotransforms:
with self.subTest(i=geotransform), self.assertRaisesMessage(
ValueError, msg
):
rsmem.geotransform = geotransform
def test_rs_extent(self):
self.assertEqual(
self.rs.extent,
(
511700.4680706557,
417703.3771231986,
528000.4680706557,
435103.3771231986,
),
)
def test_rs_bands(self):
self.assertEqual(len(self.rs.bands), 1)
self.assertIsInstance(self.rs.bands[0], GDALBand)
def test_memory_based_raster_creation(self):
# Create uint8 raster with full pixel data range (0-255)
rast = GDALRaster(
{
"datatype": 1,
"width": 16,
"height": 16,
"srid": 4326,
"bands": [
{
"data": range(256),
"nodata_value": 255,
}
],
}
)
# Get array from raster
result = rast.bands[0].data()
if numpy:
result = result.flatten().tolist()
# Assert data is same as original input
self.assertEqual(result, list(range(256)))
def test_file_based_raster_creation(self):
# Prepare tempfile
rstfile = tempfile.NamedTemporaryFile(suffix=".tif")
# Create file-based raster from scratch
GDALRaster(
{
"datatype": self.rs.bands[0].datatype(),
"driver": "tif",
"name": rstfile.name,
"width": 163,
"height": 174,
"nr_of_bands": 1,
"srid": self.rs.srs.wkt,
"origin": (self.rs.origin.x, self.rs.origin.y),
"scale": (self.rs.scale.x, self.rs.scale.y),
"skew": (self.rs.skew.x, self.rs.skew.y),
"bands": [
{
"data": self.rs.bands[0].data(),
"nodata_value": self.rs.bands[0].nodata_value,
}
],
}
)
# Reload newly created raster from file
restored_raster = GDALRaster(rstfile.name)
# Presence of TOWGS84 depend on GDAL/Proj versions.
self.assertEqual(
restored_raster.srs.wkt.replace("TOWGS84[0,0,0,0,0,0,0],", ""),
self.rs.srs.wkt.replace("TOWGS84[0,0,0,0,0,0,0],", ""),
)
self.assertEqual(restored_raster.geotransform, self.rs.geotransform)
if numpy:
numpy.testing.assert_equal(
restored_raster.bands[0].data(), self.rs.bands[0].data()
)
else:
self.assertEqual(restored_raster.bands[0].data(), self.rs.bands[0].data())
def test_nonexistent_file(self):
msg = 'Unable to read raster source input "nonexistent.tif".'
with self.assertRaisesMessage(GDALException, msg):
GDALRaster("nonexistent.tif")
def test_vsi_raster_creation(self):
# Open a raster as a file object.
with open(self.rs_path, "rb") as dat:
# Instantiate a raster from the file binary buffer.
vsimem = GDALRaster(dat.read())
# The data of the in-memory file is equal to the source file.
result = vsimem.bands[0].data()
target = self.rs.bands[0].data()
if numpy:
result = result.flatten().tolist()
target = target.flatten().tolist()
self.assertEqual(result, target)
def test_vsi_raster_deletion(self):
path = "/vsimem/raster.tif"
# Create a vsi-based raster from scratch.
vsimem = GDALRaster(
{
"name": path,
"driver": "tif",
"width": 4,
"height": 4,
"srid": 4326,
"bands": [
{
"data": range(16),
}
],
}
)
# The virtual file exists.
rst = GDALRaster(path)
self.assertEqual(rst.width, 4)
# Delete GDALRaster.
del vsimem
del rst
# The virtual file has been removed.
msg = 'Could not open the datasource at "/vsimem/raster.tif"'
with self.assertRaisesMessage(GDALException, msg):
GDALRaster(path)
def test_vsi_invalid_buffer_error(self):
msg = "Failed creating VSI raster from the input buffer."
with self.assertRaisesMessage(GDALException, msg):
GDALRaster(b"not-a-raster-buffer")
def test_vsi_buffer_property(self):
# Create a vsi-based raster from scratch.
rast = GDALRaster(
{
"name": "/vsimem/raster.tif",
"driver": "tif",
"width": 4,
"height": 4,
"srid": 4326,
"bands": [
{
"data": range(16),
}
],
}
)
# Do a round trip from raster to buffer to raster.
result = GDALRaster(rast.vsi_buffer).bands[0].data()
if numpy:
result = result.flatten().tolist()
# Band data is equal to nodata value except on input block of ones.
self.assertEqual(result, list(range(16)))
# The vsi buffer is None for rasters that are not vsi based.
self.assertIsNone(self.rs.vsi_buffer)
def test_vsi_vsizip_filesystem(self):
rst_zipfile = tempfile.NamedTemporaryFile(suffix=".zip")
with zipfile.ZipFile(rst_zipfile, mode="w") as zf:
zf.write(self.rs_path, "raster.tif")
rst_path = "/vsizip/" + os.path.join(rst_zipfile.name, "raster.tif")
rst = GDALRaster(rst_path)
self.assertEqual(rst.driver.name, self.rs.driver.name)
self.assertEqual(rst.name, rst_path)
self.assertIs(rst.is_vsi_based, True)
self.assertIsNone(rst.vsi_buffer)
def test_offset_size_and_shape_on_raster_creation(self):
rast = GDALRaster(
{
"datatype": 1,
"width": 4,
"height": 4,
"srid": 4326,
"bands": [
{
"data": (1,),
"offset": (1, 1),
"size": (2, 2),
"shape": (1, 1),
"nodata_value": 2,
}
],
}
)
# Get array from raster.
result = rast.bands[0].data()
if numpy:
result = result.flatten().tolist()
# Band data is equal to nodata value except on input block of ones.
self.assertEqual(result, [2, 2, 2, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 2, 2, 2])
def test_set_nodata_value_on_raster_creation(self):
# Create raster filled with nodata values.
rast = GDALRaster(
{
"datatype": 1,
"width": 2,
"height": 2,
"srid": 4326,
"bands": [{"nodata_value": 23}],
}
)
# Get array from raster.
result = rast.bands[0].data()
if numpy:
result = result.flatten().tolist()
# All band data is equal to nodata value.
self.assertEqual(result, [23] * 4)
def test_set_nodata_none_on_raster_creation(self):
# Create raster without data and without nodata value.
rast = GDALRaster(
{
"datatype": 1,
"width": 2,
"height": 2,
"srid": 4326,
"bands": [{"nodata_value": None}],
}
)
# Get array from raster.
result = rast.bands[0].data()
if numpy:
result = result.flatten().tolist()
# Band data is equal to zero because no nodata value has been specified.
self.assertEqual(result, [0] * 4)
def test_raster_metadata_property(self):
data = self.rs.metadata
self.assertEqual(data["DEFAULT"], {"AREA_OR_POINT": "Area"})
self.assertEqual(data["IMAGE_STRUCTURE"], {"INTERLEAVE": "BAND"})
# Create file-based raster from scratch
source = GDALRaster(
{
"datatype": 1,
"width": 2,
"height": 2,
"srid": 4326,
"bands": [{"data": range(4), "nodata_value": 99}],
}
)
# Set metadata on raster and on a band.
metadata = {
"DEFAULT": {"OWNER": "Django", "VERSION": "1.0", "AREA_OR_POINT": "Point"},
}
source.metadata = metadata
source.bands[0].metadata = metadata
self.assertEqual(source.metadata["DEFAULT"], metadata["DEFAULT"])
self.assertEqual(source.bands[0].metadata["DEFAULT"], metadata["DEFAULT"])
# Update metadata on raster.
metadata = {
"DEFAULT": {"VERSION": "2.0"},
}
source.metadata = metadata
self.assertEqual(source.metadata["DEFAULT"]["VERSION"], "2.0")
# Remove metadata on raster.
metadata = {
"DEFAULT": {"OWNER": None},
}
source.metadata = metadata
self.assertNotIn("OWNER", source.metadata["DEFAULT"])
def test_raster_info_accessor(self):
infos = self.rs.info
# Data
info_lines = [line.strip() for line in infos.split("\n") if line.strip() != ""]
for line in [
"Driver: GTiff/GeoTIFF",
"Files: {}".format(self.rs_path),
"Size is 163, 174",
"Origin = (511700.468070655711927,435103.377123198588379)",
"Pixel Size = (100.000000000000000,-100.000000000000000)",
"Metadata:",
"AREA_OR_POINT=Area",
"Image Structure Metadata:",
"INTERLEAVE=BAND",
"Band 1 Block=163x50 Type=Byte, ColorInterp=Gray",
"NoData Value=15",
]:
self.assertIn(line, info_lines)
for line in [
r"Upper Left \( 511700.468, 435103.377\) "
r'\( 82d51\'46.1\d"W, 27d55\' 1.5\d"N\)',
r"Lower Left \( 511700.468, 417703.377\) "
r'\( 82d51\'52.0\d"W, 27d45\'37.5\d"N\)',
r"Upper Right \( 528000.468, 435103.377\) "
r'\( 82d41\'48.8\d"W, 27d54\'56.3\d"N\)',
r"Lower Right \( 528000.468, 417703.377\) "
r'\( 82d41\'55.5\d"W, 27d45\'32.2\d"N\)',
r"Center \( 519850.468, 426403.377\) "
r'\( 82d46\'50.6\d"W, 27d50\'16.9\d"N\)',
]:
self.assertRegex(infos, line)
# CRS (skip the name because string depends on the GDAL/Proj versions).
self.assertIn("NAD83 / Florida GDL Albers", infos)
def test_compressed_file_based_raster_creation(self):
rstfile = tempfile.NamedTemporaryFile(suffix=".tif")
# Make a compressed copy of an existing raster.
compressed = self.rs.warp(
{"papsz_options": {"compress": "packbits"}, "name": rstfile.name}
)
# Check physically if compression worked.
self.assertLess(os.path.getsize(compressed.name), os.path.getsize(self.rs.name))
# Create file-based raster with options from scratch.
compressed = GDALRaster(
{
"datatype": 1,
"driver": "tif",
"name": rstfile.name,
"width": 40,
"height": 40,
"srid": 3086,
"origin": (500000, 400000),
"scale": (100, -100),
"skew": (0, 0),
"bands": [
{
"data": range(40 ^ 2),
"nodata_value": 255,
}
],
"papsz_options": {
"compress": "packbits",
"pixeltype": "signedbyte",
"blockxsize": 23,
"blockysize": 23,
},
}
)
# Check if options used on creation are stored in metadata.
# Reopening the raster ensures that all metadata has been written
# to the file.
compressed = GDALRaster(compressed.name)
self.assertEqual(
compressed.metadata["IMAGE_STRUCTURE"]["COMPRESSION"],
"PACKBITS",
)
self.assertEqual(
compressed.bands[0].metadata["IMAGE_STRUCTURE"]["PIXELTYPE"], "SIGNEDBYTE"
)
self.assertIn("Block=40x23", compressed.info)
def test_raster_warp(self):
# Create in memory raster
source = GDALRaster(
{
"datatype": 1,
"driver": "MEM",
"name": "sourceraster",
"width": 4,
"height": 4,
"nr_of_bands": 1,
"srid": 3086,
"origin": (500000, 400000),
"scale": (100, -100),
"skew": (0, 0),
"bands": [
{
"data": range(16),
"nodata_value": 255,
}
],
}
)
# Test altering the scale, width, and height of a raster
data = {
"scale": [200, -200],
"width": 2,
"height": 2,
}
target = source.warp(data)
self.assertEqual(target.width, data["width"])
self.assertEqual(target.height, data["height"])
self.assertEqual(target.scale, data["scale"])
self.assertEqual(target.bands[0].datatype(), source.bands[0].datatype())
self.assertEqual(target.name, "sourceraster_copy.MEM")
result = target.bands[0].data()
if numpy:
result = result.flatten().tolist()
self.assertEqual(result, [5, 7, 13, 15])
# Test altering the name and datatype (to float)
data = {
"name": "/path/to/targetraster.tif",
"datatype": 6,
}
target = source.warp(data)
self.assertEqual(target.bands[0].datatype(), 6)
self.assertEqual(target.name, "/path/to/targetraster.tif")
self.assertEqual(target.driver.name, "MEM")
result = target.bands[0].data()
if numpy:
result = result.flatten().tolist()
self.assertEqual(
result,
[
0.0,
1.0,
2.0,
3.0,
4.0,
5.0,
6.0,
7.0,
8.0,
9.0,
10.0,
11.0,
12.0,
13.0,
14.0,
15.0,
],
)
def test_raster_warp_nodata_zone(self):
# Create in memory raster.
source = GDALRaster(
{
"datatype": 1,
"driver": "MEM",
"width": 4,
"height": 4,
"srid": 3086,
"origin": (500000, 400000),
"scale": (100, -100),
"skew": (0, 0),
"bands": [
{
"data": range(16),
"nodata_value": 23,
}
],
}
)
# Warp raster onto a location that does not cover any pixels of the original.
result = source.warp({"origin": (200000, 200000)}).bands[0].data()
if numpy:
result = result.flatten().tolist()
# The result is an empty raster filled with the correct nodata value.
self.assertEqual(result, [23] * 16)
def test_raster_clone(self):
rstfile = tempfile.NamedTemporaryFile(suffix=".tif")
tests = [
("MEM", "", 23), # In memory raster.
("tif", rstfile.name, 99), # In file based raster.
]
for driver, name, nodata_value in tests:
with self.subTest(driver=driver):
source = GDALRaster(
{
"datatype": 1,
"driver": driver,
"name": name,
"width": 4,
"height": 4,
"srid": 3086,
"origin": (500000, 400000),
"scale": (100, -100),
"skew": (0, 0),
"bands": [
{
"data": range(16),
"nodata_value": nodata_value,
}
],
}
)
clone = source.clone()
self.assertNotEqual(clone.name, source.name)
self.assertEqual(clone._write, source._write)
self.assertEqual(clone.srs.srid, source.srs.srid)
self.assertEqual(clone.width, source.width)
self.assertEqual(clone.height, source.height)
self.assertEqual(clone.origin, source.origin)
self.assertEqual(clone.scale, source.scale)
self.assertEqual(clone.skew, source.skew)
self.assertIsNot(clone, source)
def test_raster_transform(self):
tests = [
3086,
"3086",
SpatialReference(3086),
]
for srs in tests:
with self.subTest(srs=srs):
# Prepare tempfile and nodata value.
rstfile = tempfile.NamedTemporaryFile(suffix=".tif")
ndv = 99
# Create in file based raster.
source = GDALRaster(
{
"datatype": 1,
"driver": "tif",
"name": rstfile.name,
"width": 5,
"height": 5,
"nr_of_bands": 1,
"srid": 4326,
"origin": (-5, 5),
"scale": (2, -2),
"skew": (0, 0),
"bands": [
{
"data": range(25),
"nodata_value": ndv,
}
],
}
)
target = source.transform(srs)
# Reload data from disk.
target = GDALRaster(target.name)
self.assertEqual(target.srs.srid, 3086)
self.assertEqual(target.width, 7)
self.assertEqual(target.height, 7)
self.assertEqual(target.bands[0].datatype(), source.bands[0].datatype())
self.assertAlmostEqual(target.origin[0], 9124842.791079799, 3)
self.assertAlmostEqual(target.origin[1], 1589911.6476407414, 3)
self.assertAlmostEqual(target.scale[0], 223824.82664250192, 3)
self.assertAlmostEqual(target.scale[1], -223824.82664250192, 3)
self.assertEqual(target.skew, [0, 0])
result = target.bands[0].data()
if numpy:
result = result.flatten().tolist()
# The reprojection of a raster that spans over a large area
# skews the data matrix and might introduce nodata values.
self.assertEqual(
result,
[
ndv,
ndv,
ndv,
ndv,
4,
ndv,
ndv,
ndv,
ndv,
2,
3,
9,
ndv,
ndv,
ndv,
1,
2,
8,
13,
19,
ndv,
0,
6,
6,
12,
18,
18,
24,
ndv,
10,
11,
16,
22,
23,
ndv,
ndv,
ndv,
15,
21,
22,
ndv,
ndv,
ndv,
ndv,
20,
ndv,
ndv,
ndv,
ndv,
],
)
def test_raster_transform_clone(self):
with mock.patch.object(GDALRaster, "clone") as mocked_clone:
# Create in file based raster.
rstfile = tempfile.NamedTemporaryFile(suffix=".tif")
source = GDALRaster(
{
"datatype": 1,
"driver": "tif",
"name": rstfile.name,
"width": 5,
"height": 5,
"nr_of_bands": 1,
"srid": 4326,
"origin": (-5, 5),
"scale": (2, -2),
"skew": (0, 0),
"bands": [
{
"data": range(25),
"nodata_value": 99,
}
],
}
)
# transform() returns a clone because it is the same SRID and
# driver.
source.transform(4326)
self.assertEqual(mocked_clone.call_count, 1)
def test_raster_transform_clone_name(self):
# Create in file based raster.
rstfile = tempfile.NamedTemporaryFile(suffix=".tif")
source = GDALRaster(
{
"datatype": 1,
"driver": "tif",
"name": rstfile.name,
"width": 5,
"height": 5,
"nr_of_bands": 1,
"srid": 4326,
"origin": (-5, 5),
"scale": (2, -2),
"skew": (0, 0),
"bands": [
{
"data": range(25),
"nodata_value": 99,
}
],
}
)
clone_name = rstfile.name + "_respect_name.GTiff"
target = source.transform(4326, name=clone_name)
self.assertEqual(target.name, clone_name)
class GDALBandTests(SimpleTestCase):
rs_path = os.path.join(os.path.dirname(__file__), "../data/rasters/raster.tif")
def test_band_data(self):
rs = GDALRaster(self.rs_path)
band = rs.bands[0]
self.assertEqual(band.width, 163)
self.assertEqual(band.height, 174)
self.assertEqual(band.description, "")
self.assertEqual(band.datatype(), 1)
self.assertEqual(band.datatype(as_string=True), "GDT_Byte")
self.assertEqual(band.color_interp(), 1)
self.assertEqual(band.color_interp(as_string=True), "GCI_GrayIndex")
self.assertEqual(band.nodata_value, 15)
if numpy:
data = band.data()
assert_array = numpy.loadtxt(
os.path.join(
os.path.dirname(__file__), "../data/rasters/raster.numpy.txt"
)
)
numpy.testing.assert_equal(data, assert_array)
self.assertEqual(data.shape, (band.height, band.width))
def test_band_statistics(self):
with tempfile.TemporaryDirectory() as tmp_dir:
rs_path = os.path.join(tmp_dir, "raster.tif")
shutil.copyfile(self.rs_path, rs_path)
rs = GDALRaster(rs_path)
band = rs.bands[0]
pam_file = rs_path + ".aux.xml"
smin, smax, smean, sstd = band.statistics(approximate=True)
self.assertEqual(smin, 0)
self.assertEqual(smax, 9)
self.assertAlmostEqual(smean, 2.842331288343558)
self.assertAlmostEqual(sstd, 2.3965567248965356)
smin, smax, smean, sstd = band.statistics(approximate=False, refresh=True)
self.assertEqual(smin, 0)
self.assertEqual(smax, 9)
self.assertAlmostEqual(smean, 2.828326634228898)
self.assertAlmostEqual(sstd, 2.4260526986669095)
self.assertEqual(band.min, 0)
self.assertEqual(band.max, 9)
self.assertAlmostEqual(band.mean, 2.828326634228898)
self.assertAlmostEqual(band.std, 2.4260526986669095)
# Statistics are persisted into PAM file on band close
rs = band = None
self.assertTrue(os.path.isfile(pam_file))
def _remove_aux_file(self):
pam_file = self.rs_path + ".aux.xml"
if os.path.isfile(pam_file):
os.remove(pam_file)
def test_read_mode_error(self):
# Open raster in read mode
rs = GDALRaster(self.rs_path, write=False)
band = rs.bands[0]
self.addCleanup(self._remove_aux_file)
# Setting attributes in write mode raises exception in the _flush method
with self.assertRaises(GDALException):
setattr(band, "nodata_value", 10)
def test_band_data_setters(self):
# Create in-memory raster and get band
rsmem = GDALRaster(
{
"datatype": 1,
"driver": "MEM",
"name": "mem_rst",
"width": 10,
"height": 10,
"nr_of_bands": 1,
"srid": 4326,
}
)
bandmem = rsmem.bands[0]
# Set nodata value
bandmem.nodata_value = 99
self.assertEqual(bandmem.nodata_value, 99)
# Set data for entire dataset
bandmem.data(range(100))
if numpy:
numpy.testing.assert_equal(
bandmem.data(), numpy.arange(100).reshape(10, 10)
)
else:
self.assertEqual(bandmem.data(), list(range(100)))
# Prepare data for setting values in subsequent tests
block = list(range(100, 104))
packed_block = struct.pack("<" + "B B B B", *block)
# Set data from list
bandmem.data(block, (1, 1), (2, 2))
result = bandmem.data(offset=(1, 1), size=(2, 2))
if numpy:
numpy.testing.assert_equal(result, numpy.array(block).reshape(2, 2))
else:
self.assertEqual(result, block)
# Set data from packed block
bandmem.data(packed_block, (1, 1), (2, 2))
result = bandmem.data(offset=(1, 1), size=(2, 2))
if numpy:
numpy.testing.assert_equal(result, numpy.array(block).reshape(2, 2))
else:
self.assertEqual(result, block)
# Set data from bytes
bandmem.data(bytes(packed_block), (1, 1), (2, 2))
result = bandmem.data(offset=(1, 1), size=(2, 2))
if numpy:
numpy.testing.assert_equal(result, numpy.array(block).reshape(2, 2))
else:
self.assertEqual(result, block)
# Set data from bytearray
bandmem.data(bytearray(packed_block), (1, 1), (2, 2))
result = bandmem.data(offset=(1, 1), size=(2, 2))
if numpy:
numpy.testing.assert_equal(result, numpy.array(block).reshape(2, 2))
else:
self.assertEqual(result, block)
# Set data from memoryview
bandmem.data(memoryview(packed_block), (1, 1), (2, 2))
result = bandmem.data(offset=(1, 1), size=(2, 2))
if numpy:
numpy.testing.assert_equal(result, numpy.array(block).reshape(2, 2))
else:
self.assertEqual(result, block)
# Set data from numpy array
if numpy:
bandmem.data(numpy.array(block, dtype="int8").reshape(2, 2), (1, 1), (2, 2))
numpy.testing.assert_equal(
bandmem.data(offset=(1, 1), size=(2, 2)),
numpy.array(block).reshape(2, 2),
)
# Test json input data
rsmemjson = GDALRaster(JSON_RASTER)
bandmemjson = rsmemjson.bands[0]
if numpy:
numpy.testing.assert_equal(
bandmemjson.data(), numpy.array(range(25)).reshape(5, 5)
)
else:
self.assertEqual(bandmemjson.data(), list(range(25)))
def test_band_statistics_automatic_refresh(self):
rsmem = GDALRaster(
{
"srid": 4326,
"width": 2,
"height": 2,
"bands": [{"data": [0] * 4, "nodata_value": 99}],
}
)
band = rsmem.bands[0]
# Populate statistics cache
self.assertEqual(band.statistics(), (0, 0, 0, 0))
# Change data
band.data([1, 1, 0, 0])
# Statistics are properly updated
self.assertEqual(band.statistics(), (0.0, 1.0, 0.5, 0.5))
# Change nodata_value
band.nodata_value = 0
# Statistics are properly updated
self.assertEqual(band.statistics(), (1.0, 1.0, 1.0, 0.0))
def test_band_statistics_empty_band(self):
rsmem = GDALRaster(
{
"srid": 4326,
"width": 1,
"height": 1,
"bands": [{"data": [0], "nodata_value": 0}],
}
)
self.assertEqual(rsmem.bands[0].statistics(), (None, None, None, None))
def test_band_delete_nodata(self):
rsmem = GDALRaster(
{
"srid": 4326,
"width": 1,
"height": 1,
"bands": [{"data": [0], "nodata_value": 1}],
}
)
rsmem.bands[0].nodata_value = None
self.assertIsNone(rsmem.bands[0].nodata_value)
def test_band_data_replication(self):
band = GDALRaster(
{
"srid": 4326,
"width": 3,
"height": 3,
"bands": [{"data": range(10, 19), "nodata_value": 0}],
}
).bands[0]
# Variations for input (data, shape, expected result).
combos = (
([1], (1, 1), [1] * 9),
(range(3), (1, 3), [0, 0, 0, 1, 1, 1, 2, 2, 2]),
(range(3), (3, 1), [0, 1, 2, 0, 1, 2, 0, 1, 2]),
)
for combo in combos:
band.data(combo[0], shape=combo[1])
if numpy:
numpy.testing.assert_equal(
band.data(), numpy.array(combo[2]).reshape(3, 3)
)
else:
self.assertEqual(band.data(), list(combo[2]))
|
4318c64584d500e875341ed08ca1bce84cdb75468588806bb3bf3f4f9636c59c | from django.contrib.gis.geos import Point
from django.test import SimpleTestCase, override_settings
from .models import City, site, site_gis, site_gis_custom
@override_settings(ROOT_URLCONF="django.contrib.gis.tests.geoadmin.urls")
class GeoAdminTest(SimpleTestCase):
admin_site = site # ModelAdmin
def test_widget_empty_string(self):
geoadmin = self.admin_site._registry[City]
form = geoadmin.get_changelist_form(None)({"point": ""})
with self.assertRaisesMessage(AssertionError, "no logs"):
with self.assertLogs("django.contrib.gis", "ERROR"):
output = str(form["point"])
self.assertInHTML(
'<textarea id="id_point" class="vSerializedField required" cols="150"'
' rows="10" name="point" hidden></textarea>',
output,
)
def test_widget_invalid_string(self):
geoadmin = self.admin_site._registry[City]
form = geoadmin.get_changelist_form(None)({"point": "INVALID()"})
with self.assertLogs("django.contrib.gis", "ERROR") as cm:
output = str(form["point"])
self.assertInHTML(
'<textarea id="id_point" class="vSerializedField required" cols="150"'
' rows="10" name="point" hidden></textarea>',
output,
)
self.assertEqual(len(cm.records), 1)
self.assertEqual(
cm.records[0].getMessage(),
"Error creating geometry from value 'INVALID()' (String input "
"unrecognized as WKT EWKT, and HEXEWKB.)",
)
def test_widget_has_changed(self):
geoadmin = self.admin_site._registry[City]
form = geoadmin.get_changelist_form(None)()
has_changed = form.fields["point"].has_changed
initial = Point(13.4197458572965953, 52.5194108501149799, srid=4326)
data_same = "SRID=3857;POINT(1493879.2754093995 6894592.019687599)"
data_almost_same = "SRID=3857;POINT(1493879.2754093990 6894592.019687590)"
data_changed = "SRID=3857;POINT(1493884.0527237 6894593.8111804)"
self.assertIs(has_changed(None, data_changed), True)
self.assertIs(has_changed(initial, ""), True)
self.assertIs(has_changed(None, ""), False)
self.assertIs(has_changed(initial, data_same), False)
self.assertIs(has_changed(initial, data_almost_same), False)
self.assertIs(has_changed(initial, data_changed), True)
class GISAdminTests(GeoAdminTest):
admin_site = site_gis # GISModelAdmin
def test_default_gis_widget_kwargs(self):
geoadmin = self.admin_site._registry[City]
form = geoadmin.get_changelist_form(None)()
widget = form["point"].field.widget
self.assertEqual(widget.attrs["default_lat"], 47)
self.assertEqual(widget.attrs["default_lon"], 5)
self.assertEqual(widget.attrs["default_zoom"], 12)
def test_custom_gis_widget_kwargs(self):
geoadmin = site_gis_custom._registry[City]
form = geoadmin.get_changelist_form(None)()
widget = form["point"].field.widget
self.assertEqual(widget.attrs["default_lat"], 55)
self.assertEqual(widget.attrs["default_lon"], 37)
self.assertEqual(widget.attrs["default_zoom"], 12)
|
59197bbec299664bd48248c5919419e00df122a59822907338f4359bb02c2ba9 | from django.db.models import Value
from django.db.models.functions import StrIndex
from django.test import TestCase
from django.utils import timezone
from ..models import Article, Author
class StrIndexTests(TestCase):
def test_annotate_charfield(self):
Author.objects.create(name="George. R. R. Martin")
Author.objects.create(name="J. R. R. Tolkien")
Author.objects.create(name="Terry Pratchett")
authors = Author.objects.annotate(fullstop=StrIndex("name", Value("R.")))
self.assertQuerySetEqual(
authors.order_by("name"), [9, 4, 0], lambda a: a.fullstop
)
def test_annotate_textfield(self):
Article.objects.create(
title="How to Django",
text="This is about How to Django.",
written=timezone.now(),
)
Article.objects.create(
title="How to Tango",
text="Won't find anything here.",
written=timezone.now(),
)
articles = Article.objects.annotate(title_pos=StrIndex("text", "title"))
self.assertQuerySetEqual(
articles.order_by("title"), [15, 0], lambda a: a.title_pos
)
def test_order_by(self):
Author.objects.create(name="Terry Pratchett")
Author.objects.create(name="J. R. R. Tolkien")
Author.objects.create(name="George. R. R. Martin")
self.assertQuerySetEqual(
Author.objects.order_by(StrIndex("name", Value("R.")).asc()),
[
"Terry Pratchett",
"J. R. R. Tolkien",
"George. R. R. Martin",
],
lambda a: a.name,
)
self.assertQuerySetEqual(
Author.objects.order_by(StrIndex("name", Value("R.")).desc()),
[
"George. R. R. Martin",
"J. R. R. Tolkien",
"Terry Pratchett",
],
lambda a: a.name,
)
def test_unicode_values(self):
Author.objects.create(name="ツリー")
Author.objects.create(name="皇帝")
Author.objects.create(name="皇帝 ツリー")
authors = Author.objects.annotate(sb=StrIndex("name", Value("リ")))
self.assertQuerySetEqual(authors.order_by("name"), [2, 0, 5], lambda a: a.sb)
def test_filtering(self):
Author.objects.create(name="George. R. R. Martin")
Author.objects.create(name="Terry Pratchett")
self.assertQuerySetEqual(
Author.objects.annotate(middle_name=StrIndex("name", Value("R."))).filter(
middle_name__gt=0
),
["George. R. R. Martin"],
lambda a: a.name,
)
|
ff75366f66c71db5c7df4f38d9881c38bcd3b27305d765d8c4195b0ca3a48938 | from django.db import connection
from django.db.models import CharField
from django.db.models.functions import Length, Reverse, Trim
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class ReverseTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.john = Author.objects.create(name="John Smith", alias="smithj")
cls.elena = Author.objects.create(name="Élena Jordan", alias="elena")
cls.python = Author.objects.create(name="パイソン")
def test_null(self):
author = Author.objects.annotate(backward=Reverse("alias")).get(
pk=self.python.pk
)
self.assertEqual(
author.backward,
"" if connection.features.interprets_empty_strings_as_nulls else None,
)
def test_basic(self):
authors = Author.objects.annotate(backward=Reverse("name"))
self.assertQuerySetEqual(
authors,
[
("John Smith", "htimS nhoJ"),
("Élena Jordan", "nadroJ anelÉ"),
("パイソン", "ンソイパ"),
],
lambda a: (a.name, a.backward),
ordered=False,
)
def test_transform(self):
with register_lookup(CharField, Reverse):
authors = Author.objects.all()
self.assertCountEqual(
authors.filter(name__reverse=self.john.name[::-1]), [self.john]
)
self.assertCountEqual(
authors.exclude(name__reverse=self.john.name[::-1]),
[self.elena, self.python],
)
def test_expressions(self):
author = Author.objects.annotate(backward=Reverse(Trim("name"))).get(
pk=self.john.pk
)
self.assertEqual(author.backward, self.john.name[::-1])
with register_lookup(CharField, Reverse), register_lookup(CharField, Length):
authors = Author.objects.all()
self.assertCountEqual(
authors.filter(name__reverse__length__gt=7), [self.john, self.elena]
)
self.assertCountEqual(
authors.exclude(name__reverse__length__gt=7), [self.python]
)
|
a2100e5a2e6661f741bebb4c82e10185f93a891f9ac61223eac02b26a2d605a2 | from django.db import connection
from django.db.models import Value
from django.db.models.functions import Length, Repeat
from django.test import TestCase
from ..models import Author
class RepeatTests(TestCase):
def test_basic(self):
Author.objects.create(name="John", alias="xyz")
none_value = (
"" if connection.features.interprets_empty_strings_as_nulls else None
)
tests = (
(Repeat("name", 0), ""),
(Repeat("name", 2), "JohnJohn"),
(Repeat("name", Length("alias")), "JohnJohnJohn"),
(Repeat(Value("x"), 3), "xxx"),
(Repeat("name", None), none_value),
(Repeat(Value(None), 4), none_value),
(Repeat("goes_by", 1), none_value),
)
for function, repeated_text in tests:
with self.subTest(function=function):
authors = Author.objects.annotate(repeated_text=function)
self.assertQuerySetEqual(
authors, [repeated_text], lambda a: a.repeated_text, ordered=False
)
def test_negative_number(self):
with self.assertRaisesMessage(
ValueError, "'number' must be greater or equal to 0."
):
Repeat("name", -1)
|
c8ef066d1a90a41d555bd02b6be9d0ffa566651c7a95d34dad68bacd65e7c19f | from django.db.models import CharField
from django.db.models.functions import Lower
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class LowerTests(TestCase):
def test_basic(self):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
authors = Author.objects.annotate(lower_name=Lower("name"))
self.assertQuerySetEqual(
authors.order_by("name"), ["john smith", "rhonda"], lambda a: a.lower_name
)
Author.objects.update(name=Lower("name"))
self.assertQuerySetEqual(
authors.order_by("name"),
[
("john smith", "john smith"),
("rhonda", "rhonda"),
],
lambda a: (a.lower_name, a.name),
)
def test_num_args(self):
with self.assertRaisesMessage(
TypeError, "'Lower' takes exactly 1 argument (2 given)"
):
Author.objects.update(name=Lower("name", "name"))
def test_transform(self):
with register_lookup(CharField, Lower):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
authors = Author.objects.filter(name__lower__exact="john smith")
self.assertQuerySetEqual(
authors.order_by("name"), ["John Smith"], lambda a: a.name
)
|
f046c084287a75b53202f11528ab06d7148dd2001d966555a26f68c29a218ed1 | from django.db.models import IntegerField, Value
from django.db.models.functions import Lower, Right
from django.test import TestCase
from ..models import Author
class RightTests(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
def test_basic(self):
authors = Author.objects.annotate(name_part=Right("name", 5))
self.assertQuerySetEqual(
authors.order_by("name"), ["Smith", "honda"], lambda a: a.name_part
)
# If alias is null, set it to the first 2 lower characters of the name.
Author.objects.filter(alias__isnull=True).update(alias=Lower(Right("name", 2)))
self.assertQuerySetEqual(
authors.order_by("name"), ["smithj", "da"], lambda a: a.alias
)
def test_invalid_length(self):
with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"):
Author.objects.annotate(raises=Right("name", 0))
def test_expressions(self):
authors = Author.objects.annotate(
name_part=Right("name", Value(3, output_field=IntegerField()))
)
self.assertQuerySetEqual(
authors.order_by("name"), ["ith", "nda"], lambda a: a.name_part
)
|
ede5104145052a09faa98b443cff25d72df9d75c3bab6183930b8c604b8f308b | from django.db.models import F, Value
from django.db.models.functions import Concat, Replace
from django.test import TestCase
from ..models import Author
class ReplaceTests(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.create(name="George R. R. Martin")
Author.objects.create(name="J. R. R. Tolkien")
def test_replace_with_empty_string(self):
qs = Author.objects.annotate(
without_middlename=Replace(F("name"), Value("R. R. "), Value("")),
)
self.assertQuerySetEqual(
qs,
[
("George R. R. Martin", "George Martin"),
("J. R. R. Tolkien", "J. Tolkien"),
],
transform=lambda x: (x.name, x.without_middlename),
ordered=False,
)
def test_case_sensitive(self):
qs = Author.objects.annotate(
same_name=Replace(F("name"), Value("r. r."), Value(""))
)
self.assertQuerySetEqual(
qs,
[
("George R. R. Martin", "George R. R. Martin"),
("J. R. R. Tolkien", "J. R. R. Tolkien"),
],
transform=lambda x: (x.name, x.same_name),
ordered=False,
)
def test_replace_expression(self):
qs = Author.objects.annotate(
same_name=Replace(
Concat(Value("Author: "), F("name")), Value("Author: "), Value("")
),
)
self.assertQuerySetEqual(
qs,
[
("George R. R. Martin", "George R. R. Martin"),
("J. R. R. Tolkien", "J. R. R. Tolkien"),
],
transform=lambda x: (x.name, x.same_name),
ordered=False,
)
def test_update(self):
Author.objects.update(
name=Replace(F("name"), Value("R. R. "), Value("")),
)
self.assertQuerySetEqual(
Author.objects.all(),
[
("George Martin"),
("J. Tolkien"),
],
transform=lambda x: x.name,
ordered=False,
)
def test_replace_with_default_arg(self):
# The default replacement is an empty string.
qs = Author.objects.annotate(same_name=Replace(F("name"), Value("R. R. ")))
self.assertQuerySetEqual(
qs,
[
("George R. R. Martin", "George Martin"),
("J. R. R. Tolkien", "J. Tolkien"),
],
transform=lambda x: (x.name, x.same_name),
ordered=False,
)
|
67703df457b3b222188aa91bcb5ab16ae066b6aa4bdc54b079843933e05e7efa | from django.db.models import IntegerField, Value
from django.db.models.functions import Left, Lower
from django.test import TestCase
from ..models import Author
class LeftTests(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
def test_basic(self):
authors = Author.objects.annotate(name_part=Left("name", 5))
self.assertQuerySetEqual(
authors.order_by("name"), ["John ", "Rhond"], lambda a: a.name_part
)
# If alias is null, set it to the first 2 lower characters of the name.
Author.objects.filter(alias__isnull=True).update(alias=Lower(Left("name", 2)))
self.assertQuerySetEqual(
authors.order_by("name"), ["smithj", "rh"], lambda a: a.alias
)
def test_invalid_length(self):
with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"):
Author.objects.annotate(raises=Left("name", 0))
def test_expressions(self):
authors = Author.objects.annotate(
name_part=Left("name", Value(3, output_field=IntegerField()))
)
self.assertQuerySetEqual(
authors.order_by("name"), ["Joh", "Rho"], lambda a: a.name_part
)
|
1d820a60e835e1765a041ea1097243f3f56bd2dcc2056c77e884cc2199cca0a1 | from unittest import skipUnless
from django.db import connection
from django.db.models import CharField, TextField
from django.db.models import Value as V
from django.db.models.functions import Concat, ConcatPair, Upper
from django.test import TestCase
from django.utils import timezone
from ..models import Article, Author
lorem_ipsum = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua."""
class ConcatTests(TestCase):
def test_basic(self):
Author.objects.create(name="Jayden")
Author.objects.create(name="John Smith", alias="smithj", goes_by="John")
Author.objects.create(name="Margaret", goes_by="Maggie")
Author.objects.create(name="Rhonda", alias="adnohR")
authors = Author.objects.annotate(joined=Concat("alias", "goes_by"))
self.assertQuerySetEqual(
authors.order_by("name"),
[
"",
"smithjJohn",
"Maggie",
"adnohR",
],
lambda a: a.joined,
)
def test_gt_two_expressions(self):
with self.assertRaisesMessage(
ValueError, "Concat must take at least two expressions"
):
Author.objects.annotate(joined=Concat("alias"))
def test_many(self):
Author.objects.create(name="Jayden")
Author.objects.create(name="John Smith", alias="smithj", goes_by="John")
Author.objects.create(name="Margaret", goes_by="Maggie")
Author.objects.create(name="Rhonda", alias="adnohR")
authors = Author.objects.annotate(
joined=Concat("name", V(" ("), "goes_by", V(")"), output_field=CharField()),
)
self.assertQuerySetEqual(
authors.order_by("name"),
[
"Jayden ()",
"John Smith (John)",
"Margaret (Maggie)",
"Rhonda ()",
],
lambda a: a.joined,
)
def test_mixed_char_text(self):
Article.objects.create(
title="The Title", text=lorem_ipsum, written=timezone.now()
)
article = Article.objects.annotate(
title_text=Concat("title", V(" - "), "text", output_field=TextField()),
).get(title="The Title")
self.assertEqual(article.title + " - " + article.text, article.title_text)
# Wrap the concat in something else to ensure that text is returned
# rather than bytes.
article = Article.objects.annotate(
title_text=Upper(
Concat("title", V(" - "), "text", output_field=TextField())
),
).get(title="The Title")
expected = article.title + " - " + article.text
self.assertEqual(expected.upper(), article.title_text)
@skipUnless(connection.vendor == "sqlite", "sqlite specific implementation detail.")
def test_coalesce_idempotent(self):
pair = ConcatPair(V("a"), V("b"))
# Check nodes counts
self.assertEqual(len(list(pair.flatten())), 3)
self.assertEqual(
len(list(pair.coalesce().flatten())), 7
) # + 2 Coalesce + 2 Value()
self.assertEqual(len(list(pair.flatten())), 3)
def test_sql_generation_idempotency(self):
qs = Article.objects.annotate(description=Concat("title", V(": "), "summary"))
# Multiple compilations should not alter the generated query.
self.assertEqual(str(qs.query), str(qs.all().query))
|
4aa419e5509d7e68be6ee25ae89085c5324d64371023961f20c8ff9da0f75529 | from django.db.models import CharField
from django.db.models.functions import Length
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class LengthTests(TestCase):
def test_basic(self):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
authors = Author.objects.annotate(
name_length=Length("name"),
alias_length=Length("alias"),
)
self.assertQuerySetEqual(
authors.order_by("name"),
[(10, 6), (6, None)],
lambda a: (a.name_length, a.alias_length),
)
self.assertEqual(authors.filter(alias_length__lte=Length("name")).count(), 1)
def test_ordering(self):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="John Smith", alias="smithj1")
Author.objects.create(name="Rhonda", alias="ronny")
authors = Author.objects.order_by(Length("name"), Length("alias"))
self.assertQuerySetEqual(
authors,
[
("Rhonda", "ronny"),
("John Smith", "smithj"),
("John Smith", "smithj1"),
],
lambda a: (a.name, a.alias),
)
def test_transform(self):
with register_lookup(CharField, Length):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
authors = Author.objects.filter(name__length__gt=7)
self.assertQuerySetEqual(
authors.order_by("name"), ["John Smith"], lambda a: a.name
)
|
c82d32db807eb5f177b54b88811f3b8359eb74fb091d21b001fa50a860b69537 | from django.db.models import CharField
from django.db.models.functions import Upper
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class UpperTests(TestCase):
def test_basic(self):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
authors = Author.objects.annotate(upper_name=Upper("name"))
self.assertQuerySetEqual(
authors.order_by("name"),
[
"JOHN SMITH",
"RHONDA",
],
lambda a: a.upper_name,
)
Author.objects.update(name=Upper("name"))
self.assertQuerySetEqual(
authors.order_by("name"),
[
("JOHN SMITH", "JOHN SMITH"),
("RHONDA", "RHONDA"),
],
lambda a: (a.upper_name, a.name),
)
def test_transform(self):
with register_lookup(CharField, Upper):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
authors = Author.objects.filter(name__upper__exact="JOHN SMITH")
self.assertQuerySetEqual(
authors.order_by("name"),
[
"John Smith",
],
lambda a: a.name,
)
|
66cfddc86299f9bb4cd5c80ebbf67d3f1d110f2e1ad3334f7fab46dc564a3ecd | from django.db.models import Value as V
from django.db.models.functions import Lower, StrIndex, Substr, Upper
from django.test import TestCase
from ..models import Author
class SubstrTests(TestCase):
def test_basic(self):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
authors = Author.objects.annotate(name_part=Substr("name", 5, 3))
self.assertQuerySetEqual(
authors.order_by("name"), [" Sm", "da"], lambda a: a.name_part
)
authors = Author.objects.annotate(name_part=Substr("name", 2))
self.assertQuerySetEqual(
authors.order_by("name"), ["ohn Smith", "honda"], lambda a: a.name_part
)
# If alias is null, set to first 5 lower characters of the name.
Author.objects.filter(alias__isnull=True).update(
alias=Lower(Substr("name", 1, 5)),
)
self.assertQuerySetEqual(
authors.order_by("name"), ["smithj", "rhond"], lambda a: a.alias
)
def test_start(self):
Author.objects.create(name="John Smith", alias="smithj")
a = Author.objects.annotate(
name_part_1=Substr("name", 1),
name_part_2=Substr("name", 2),
).get(alias="smithj")
self.assertEqual(a.name_part_1[1:], a.name_part_2)
def test_pos_gt_zero(self):
with self.assertRaisesMessage(ValueError, "'pos' must be greater than 0"):
Author.objects.annotate(raises=Substr("name", 0))
def test_expressions(self):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
substr = Substr(Upper("name"), StrIndex("name", V("h")), 5)
authors = Author.objects.annotate(name_part=substr)
self.assertQuerySetEqual(
authors.order_by("name"), ["HN SM", "HONDA"], lambda a: a.name_part
)
|
2b19c01a06fab1a2e8eed2f341cb1adf44088b05023a6ceea992fba1718830e8 | from django.db.models import CharField
from django.db.models.functions import LTrim, RTrim, Trim
from django.test import TestCase
from django.test.utils import register_lookup
from ..models import Author
class TrimTests(TestCase):
def test_trim(self):
Author.objects.create(name=" John ", alias="j")
Author.objects.create(name="Rhonda", alias="r")
authors = Author.objects.annotate(
ltrim=LTrim("name"),
rtrim=RTrim("name"),
trim=Trim("name"),
)
self.assertQuerySetEqual(
authors.order_by("alias"),
[
("John ", " John", "John"),
("Rhonda", "Rhonda", "Rhonda"),
],
lambda a: (a.ltrim, a.rtrim, a.trim),
)
def test_trim_transform(self):
Author.objects.create(name=" John ")
Author.objects.create(name="Rhonda")
tests = (
(LTrim, "John "),
(RTrim, " John"),
(Trim, "John"),
)
for transform, trimmed_name in tests:
with self.subTest(transform=transform):
with register_lookup(CharField, transform):
authors = Author.objects.filter(
**{"name__%s" % transform.lookup_name: trimmed_name}
)
self.assertQuerySetEqual(authors, [" John "], lambda a: a.name)
|
c2b242ab980799f870259d69ef6796f7542657f1a81758bc95be4520c2f64052 | from django.db import connection
from django.db.models import Value
from django.db.models.functions import Length, LPad, RPad
from django.test import TestCase
from ..models import Author
class PadTests(TestCase):
def test_pad(self):
Author.objects.create(name="John", alias="j")
none_value = (
"" if connection.features.interprets_empty_strings_as_nulls else None
)
tests = (
(LPad("name", 7, Value("xy")), "xyxJohn"),
(RPad("name", 7, Value("xy")), "Johnxyx"),
(LPad("name", 6, Value("x")), "xxJohn"),
(RPad("name", 6, Value("x")), "Johnxx"),
# The default pad string is a space.
(LPad("name", 6), " John"),
(RPad("name", 6), "John "),
# If string is longer than length it is truncated.
(LPad("name", 2), "Jo"),
(RPad("name", 2), "Jo"),
(LPad("name", 0), ""),
(RPad("name", 0), ""),
(LPad("name", None), none_value),
(RPad("name", None), none_value),
(LPad(Value(None), 1), none_value),
(RPad(Value(None), 1), none_value),
(LPad("goes_by", 1), none_value),
(RPad("goes_by", 1), none_value),
)
for function, padded_name in tests:
with self.subTest(function=function):
authors = Author.objects.annotate(padded_name=function)
self.assertQuerySetEqual(
authors, [padded_name], lambda a: a.padded_name, ordered=False
)
def test_pad_negative_length(self):
for function in (LPad, RPad):
with self.subTest(function=function):
with self.assertRaisesMessage(
ValueError, "'length' must be greater or equal to 0."
):
function("name", -1)
def test_combined_with_length(self):
Author.objects.create(name="Rhonda", alias="john_smith")
Author.objects.create(name="♥♣♠", alias="bytes")
authors = Author.objects.annotate(filled=LPad("name", Length("alias")))
self.assertQuerySetEqual(
authors.order_by("alias"),
[" ♥♣♠", " Rhonda"],
lambda a: a.filled,
)
|
63ee686f6ae79031ac02585176686487b7941d16aae2e1332bd0455bf760c2ed | from datetime import datetime, timedelta
from django.db import connection
from django.db.models import TextField
from django.db.models.functions import Cast, Now
from django.test import TestCase
from django.utils import timezone
from ..models import Article
lorem_ipsum = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua."""
class NowTests(TestCase):
def test_basic(self):
a1 = Article.objects.create(
title="How to Django",
text=lorem_ipsum,
written=timezone.now(),
)
a2 = Article.objects.create(
title="How to Time Travel",
text=lorem_ipsum,
written=timezone.now(),
)
num_updated = Article.objects.filter(id=a1.id, published=None).update(
published=Now()
)
self.assertEqual(num_updated, 1)
num_updated = Article.objects.filter(id=a1.id, published=None).update(
published=Now()
)
self.assertEqual(num_updated, 0)
a1.refresh_from_db()
self.assertIsInstance(a1.published, datetime)
a2.published = Now() + timedelta(days=2)
a2.save()
a2.refresh_from_db()
self.assertIsInstance(a2.published, datetime)
self.assertQuerySetEqual(
Article.objects.filter(published__lte=Now()),
["How to Django"],
lambda a: a.title,
)
self.assertQuerySetEqual(
Article.objects.filter(published__gt=Now()),
["How to Time Travel"],
lambda a: a.title,
)
def test_microseconds(self):
Article.objects.create(
title="How to Django",
text=lorem_ipsum,
written=timezone.now(),
)
now_string = (
Article.objects.annotate(now_string=Cast(Now(), TextField()))
.get()
.now_string
)
precision = connection.features.time_cast_precision
self.assertRegex(now_string, rf"^.*\.\d{{1,{precision}}}")
|
494e77680a9bebb972ce3243f7fb85f26b97028f10f560cd69489c2f66ac9a3e | import unittest
from datetime import datetime, timedelta
from datetime import timezone as datetime_timezone
try:
import zoneinfo
except ImportError:
from backports import zoneinfo
try:
import pytz
except ImportError:
pytz = None
from django.conf import settings
from django.db import DataError, OperationalError
from django.db.models import (
DateField,
DateTimeField,
F,
IntegerField,
Max,
OuterRef,
Subquery,
TimeField,
)
from django.db.models.functions import (
Extract,
ExtractDay,
ExtractHour,
ExtractIsoWeekDay,
ExtractIsoYear,
ExtractMinute,
ExtractMonth,
ExtractQuarter,
ExtractSecond,
ExtractWeek,
ExtractWeekDay,
ExtractYear,
Trunc,
TruncDate,
TruncDay,
TruncHour,
TruncMinute,
TruncMonth,
TruncQuarter,
TruncSecond,
TruncTime,
TruncWeek,
TruncYear,
)
from django.test import (
TestCase,
ignore_warnings,
override_settings,
skipIfDBFeature,
skipUnlessDBFeature,
)
from django.utils import timezone
from django.utils.deprecation import RemovedInDjango50Warning
from ..models import Author, DTModel, Fan
HAS_PYTZ = pytz is not None
if not HAS_PYTZ:
needs_pytz = unittest.skip("Test requires pytz")
else:
def needs_pytz(f):
return f
ZONE_CONSTRUCTORS = (zoneinfo.ZoneInfo,)
if HAS_PYTZ:
ZONE_CONSTRUCTORS += (pytz.timezone,)
def truncate_to(value, kind, tzinfo=None):
# Convert to target timezone before truncation
if tzinfo is not None:
value = value.astimezone(tzinfo)
def truncate(value, kind):
if kind == "second":
return value.replace(microsecond=0)
if kind == "minute":
return value.replace(second=0, microsecond=0)
if kind == "hour":
return value.replace(minute=0, second=0, microsecond=0)
if kind == "day":
if isinstance(value, datetime):
return value.replace(hour=0, minute=0, second=0, microsecond=0)
return value
if kind == "week":
if isinstance(value, datetime):
return (value - timedelta(days=value.weekday())).replace(
hour=0, minute=0, second=0, microsecond=0
)
return value - timedelta(days=value.weekday())
if kind == "month":
if isinstance(value, datetime):
return value.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
return value.replace(day=1)
if kind == "quarter":
month_in_quarter = value.month - (value.month - 1) % 3
if isinstance(value, datetime):
return value.replace(
month=month_in_quarter,
day=1,
hour=0,
minute=0,
second=0,
microsecond=0,
)
return value.replace(month=month_in_quarter, day=1)
# otherwise, truncate to year
if isinstance(value, datetime):
return value.replace(
month=1, day=1, hour=0, minute=0, second=0, microsecond=0
)
return value.replace(month=1, day=1)
value = truncate(value, kind)
if tzinfo is not None:
# If there was a daylight saving transition, then reset the timezone.
value = timezone.make_aware(value.replace(tzinfo=None), tzinfo)
return value
@override_settings(USE_TZ=False)
class DateFunctionTests(TestCase):
def create_model(self, start_datetime, end_datetime):
return DTModel.objects.create(
name=start_datetime.isoformat() if start_datetime else "None",
start_datetime=start_datetime,
end_datetime=end_datetime,
start_date=start_datetime.date() if start_datetime else None,
end_date=end_datetime.date() if end_datetime else None,
start_time=start_datetime.time() if start_datetime else None,
end_time=end_datetime.time() if end_datetime else None,
duration=(end_datetime - start_datetime)
if start_datetime and end_datetime
else None,
)
def test_extract_year_exact_lookup(self):
"""
Extract year uses a BETWEEN filter to compare the year to allow indexes
to be used.
"""
start_datetime = datetime(2015, 6, 15, 14, 10)
end_datetime = datetime(2016, 6, 15, 14, 10)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
for lookup in ("year", "iso_year"):
with self.subTest(lookup):
qs = DTModel.objects.filter(
**{"start_datetime__%s__exact" % lookup: 2015}
)
self.assertEqual(qs.count(), 1)
query_string = str(qs.query).lower()
self.assertEqual(query_string.count(" between "), 1)
self.assertEqual(query_string.count("extract"), 0)
# exact is implied and should be the same
qs = DTModel.objects.filter(**{"start_datetime__%s" % lookup: 2015})
self.assertEqual(qs.count(), 1)
query_string = str(qs.query).lower()
self.assertEqual(query_string.count(" between "), 1)
self.assertEqual(query_string.count("extract"), 0)
# date and datetime fields should behave the same
qs = DTModel.objects.filter(**{"start_date__%s" % lookup: 2015})
self.assertEqual(qs.count(), 1)
query_string = str(qs.query).lower()
self.assertEqual(query_string.count(" between "), 1)
self.assertEqual(query_string.count("extract"), 0)
# an expression rhs cannot use the between optimization.
qs = DTModel.objects.annotate(
start_year=ExtractYear("start_datetime"),
).filter(end_datetime__year=F("start_year") + 1)
self.assertEqual(qs.count(), 1)
query_string = str(qs.query).lower()
self.assertEqual(query_string.count(" between "), 0)
self.assertEqual(query_string.count("extract"), 3)
def test_extract_year_greaterthan_lookup(self):
start_datetime = datetime(2015, 6, 15, 14, 10)
end_datetime = datetime(2016, 6, 15, 14, 10)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
for lookup in ("year", "iso_year"):
with self.subTest(lookup):
qs = DTModel.objects.filter(**{"start_datetime__%s__gt" % lookup: 2015})
self.assertEqual(qs.count(), 1)
self.assertEqual(str(qs.query).lower().count("extract"), 0)
qs = DTModel.objects.filter(
**{"start_datetime__%s__gte" % lookup: 2015}
)
self.assertEqual(qs.count(), 2)
self.assertEqual(str(qs.query).lower().count("extract"), 0)
qs = DTModel.objects.annotate(
start_year=ExtractYear("start_datetime"),
).filter(**{"end_datetime__%s__gte" % lookup: F("start_year")})
self.assertEqual(qs.count(), 1)
self.assertGreaterEqual(str(qs.query).lower().count("extract"), 2)
def test_extract_year_lessthan_lookup(self):
start_datetime = datetime(2015, 6, 15, 14, 10)
end_datetime = datetime(2016, 6, 15, 14, 10)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
for lookup in ("year", "iso_year"):
with self.subTest(lookup):
qs = DTModel.objects.filter(**{"start_datetime__%s__lt" % lookup: 2016})
self.assertEqual(qs.count(), 1)
self.assertEqual(str(qs.query).count("extract"), 0)
qs = DTModel.objects.filter(
**{"start_datetime__%s__lte" % lookup: 2016}
)
self.assertEqual(qs.count(), 2)
self.assertEqual(str(qs.query).count("extract"), 0)
qs = DTModel.objects.annotate(
end_year=ExtractYear("end_datetime"),
).filter(**{"start_datetime__%s__lte" % lookup: F("end_year")})
self.assertEqual(qs.count(), 1)
self.assertGreaterEqual(str(qs.query).lower().count("extract"), 2)
def test_extract_lookup_name_sql_injection(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
with self.assertRaises((DataError, OperationalError, ValueError)):
DTModel.objects.filter(
start_datetime__year=Extract(
"start_datetime", "day' FROM start_datetime)) OR 1=1;--"
)
).exists()
def test_extract_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
with self.assertRaisesMessage(ValueError, "lookup_name must be provided"):
Extract("start_datetime")
msg = (
"Extract input expression must be DateField, DateTimeField, TimeField, or "
"DurationField."
)
with self.assertRaisesMessage(ValueError, msg):
list(DTModel.objects.annotate(extracted=Extract("name", "hour")))
with self.assertRaisesMessage(
ValueError,
"Cannot extract time component 'second' from DateField 'start_date'.",
):
list(DTModel.objects.annotate(extracted=Extract("start_date", "second")))
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=Extract("start_datetime", "year")
).order_by("start_datetime"),
[(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=Extract("start_datetime", "quarter")
).order_by("start_datetime"),
[(start_datetime, 2), (end_datetime, 2)],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=Extract("start_datetime", "month")
).order_by("start_datetime"),
[
(start_datetime, start_datetime.month),
(end_datetime, end_datetime.month),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=Extract("start_datetime", "day")
).order_by("start_datetime"),
[(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=Extract("start_datetime", "week")
).order_by("start_datetime"),
[(start_datetime, 25), (end_datetime, 24)],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=Extract("start_datetime", "week_day")
).order_by("start_datetime"),
[
(start_datetime, (start_datetime.isoweekday() % 7) + 1),
(end_datetime, (end_datetime.isoweekday() % 7) + 1),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=Extract("start_datetime", "iso_week_day"),
).order_by("start_datetime"),
[
(start_datetime, start_datetime.isoweekday()),
(end_datetime, end_datetime.isoweekday()),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=Extract("start_datetime", "hour")
).order_by("start_datetime"),
[(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=Extract("start_datetime", "minute")
).order_by("start_datetime"),
[
(start_datetime, start_datetime.minute),
(end_datetime, end_datetime.minute),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=Extract("start_datetime", "second")
).order_by("start_datetime"),
[
(start_datetime, start_datetime.second),
(end_datetime, end_datetime.second),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(
start_datetime__year=Extract("start_datetime", "year")
).count(),
2,
)
self.assertEqual(
DTModel.objects.filter(
start_datetime__hour=Extract("start_datetime", "hour")
).count(),
2,
)
self.assertEqual(
DTModel.objects.filter(
start_date__month=Extract("start_date", "month")
).count(),
2,
)
self.assertEqual(
DTModel.objects.filter(
start_time__hour=Extract("start_time", "hour")
).count(),
2,
)
def test_extract_none(self):
self.create_model(None, None)
for t in (
Extract("start_datetime", "year"),
Extract("start_date", "year"),
Extract("start_time", "hour"),
):
with self.subTest(t):
self.assertIsNone(
DTModel.objects.annotate(extracted=t).first().extracted
)
def test_extract_outerref_validation(self):
inner_qs = DTModel.objects.filter(name=ExtractMonth(OuterRef("name")))
msg = (
"Extract input expression must be DateField, DateTimeField, "
"TimeField, or DurationField."
)
with self.assertRaisesMessage(ValueError, msg):
DTModel.objects.annotate(related_name=Subquery(inner_qs.values("name")[:1]))
@skipUnlessDBFeature("has_native_duration_field")
def test_extract_duration(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=Extract("duration", "second")).order_by(
"start_datetime"
),
[
(start_datetime, (end_datetime - start_datetime).seconds % 60),
(end_datetime, (start_datetime - end_datetime).seconds % 60),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.annotate(
duration_days=Extract("duration", "day"),
)
.filter(duration_days__gt=200)
.count(),
1,
)
@skipIfDBFeature("has_native_duration_field")
def test_extract_duration_without_native_duration_field(self):
msg = "Extract requires native DurationField database support."
with self.assertRaisesMessage(ValueError, msg):
list(DTModel.objects.annotate(extracted=Extract("duration", "second")))
def test_extract_duration_unsupported_lookups(self):
msg = "Cannot extract component '%s' from DurationField 'duration'."
for lookup in (
"year",
"iso_year",
"month",
"week",
"week_day",
"iso_week_day",
"quarter",
):
with self.subTest(lookup):
with self.assertRaisesMessage(ValueError, msg % lookup):
DTModel.objects.annotate(extracted=Extract("duration", lookup))
def test_extract_year_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=ExtractYear("start_datetime")).order_by(
"start_datetime"
),
[(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=ExtractYear("start_date")).order_by(
"start_datetime"
),
[(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(
start_datetime__year=ExtractYear("start_datetime")
).count(),
2,
)
def test_extract_iso_year_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=ExtractIsoYear("start_datetime")
).order_by("start_datetime"),
[(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=ExtractIsoYear("start_date")).order_by(
"start_datetime"
),
[(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)],
lambda m: (m.start_datetime, m.extracted),
)
# Both dates are from the same week year.
self.assertEqual(
DTModel.objects.filter(
start_datetime__iso_year=ExtractIsoYear("start_datetime")
).count(),
2,
)
def test_extract_iso_year_func_boundaries(self):
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
end_datetime = timezone.make_aware(end_datetime)
week_52_day_2014 = datetime(2014, 12, 27, 13, 0) # Sunday
week_1_day_2014_2015 = datetime(2014, 12, 31, 13, 0) # Wednesday
week_53_day_2015 = datetime(2015, 12, 31, 13, 0) # Thursday
if settings.USE_TZ:
week_1_day_2014_2015 = timezone.make_aware(week_1_day_2014_2015)
week_52_day_2014 = timezone.make_aware(week_52_day_2014)
week_53_day_2015 = timezone.make_aware(week_53_day_2015)
days = [week_52_day_2014, week_1_day_2014_2015, week_53_day_2015]
obj_1_iso_2014 = self.create_model(week_52_day_2014, end_datetime)
obj_1_iso_2015 = self.create_model(week_1_day_2014_2015, end_datetime)
obj_2_iso_2015 = self.create_model(week_53_day_2015, end_datetime)
qs = (
DTModel.objects.filter(start_datetime__in=days)
.annotate(
extracted=ExtractIsoYear("start_datetime"),
)
.order_by("start_datetime")
)
self.assertQuerySetEqual(
qs,
[
(week_52_day_2014, 2014),
(week_1_day_2014_2015, 2015),
(week_53_day_2015, 2015),
],
lambda m: (m.start_datetime, m.extracted),
)
qs = DTModel.objects.filter(
start_datetime__iso_year=2015,
).order_by("start_datetime")
self.assertSequenceEqual(qs, [obj_1_iso_2015, obj_2_iso_2015])
qs = DTModel.objects.filter(
start_datetime__iso_year__gt=2014,
).order_by("start_datetime")
self.assertSequenceEqual(qs, [obj_1_iso_2015, obj_2_iso_2015])
qs = DTModel.objects.filter(
start_datetime__iso_year__lte=2014,
).order_by("start_datetime")
self.assertSequenceEqual(qs, [obj_1_iso_2014])
def test_extract_month_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=ExtractMonth("start_datetime")).order_by(
"start_datetime"
),
[
(start_datetime, start_datetime.month),
(end_datetime, end_datetime.month),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=ExtractMonth("start_date")).order_by(
"start_datetime"
),
[
(start_datetime, start_datetime.month),
(end_datetime, end_datetime.month),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(
start_datetime__month=ExtractMonth("start_datetime")
).count(),
2,
)
def test_extract_day_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=ExtractDay("start_datetime")).order_by(
"start_datetime"
),
[(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=ExtractDay("start_date")).order_by(
"start_datetime"
),
[(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(
start_datetime__day=ExtractDay("start_datetime")
).count(),
2,
)
def test_extract_week_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=ExtractWeek("start_datetime")).order_by(
"start_datetime"
),
[(start_datetime, 25), (end_datetime, 24)],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=ExtractWeek("start_date")).order_by(
"start_datetime"
),
[(start_datetime, 25), (end_datetime, 24)],
lambda m: (m.start_datetime, m.extracted),
)
# both dates are from the same week.
self.assertEqual(
DTModel.objects.filter(
start_datetime__week=ExtractWeek("start_datetime")
).count(),
2,
)
def test_extract_quarter_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 8, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=ExtractQuarter("start_datetime")
).order_by("start_datetime"),
[(start_datetime, 2), (end_datetime, 3)],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=ExtractQuarter("start_date")).order_by(
"start_datetime"
),
[(start_datetime, 2), (end_datetime, 3)],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(
start_datetime__quarter=ExtractQuarter("start_datetime")
).count(),
2,
)
def test_extract_quarter_func_boundaries(self):
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
end_datetime = timezone.make_aware(end_datetime)
last_quarter_2014 = datetime(2014, 12, 31, 13, 0)
first_quarter_2015 = datetime(2015, 1, 1, 13, 0)
if settings.USE_TZ:
last_quarter_2014 = timezone.make_aware(last_quarter_2014)
first_quarter_2015 = timezone.make_aware(first_quarter_2015)
dates = [last_quarter_2014, first_quarter_2015]
self.create_model(last_quarter_2014, end_datetime)
self.create_model(first_quarter_2015, end_datetime)
qs = (
DTModel.objects.filter(start_datetime__in=dates)
.annotate(
extracted=ExtractQuarter("start_datetime"),
)
.order_by("start_datetime")
)
self.assertQuerySetEqual(
qs,
[
(last_quarter_2014, 4),
(first_quarter_2015, 1),
],
lambda m: (m.start_datetime, m.extracted),
)
def test_extract_week_func_boundaries(self):
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
end_datetime = timezone.make_aware(end_datetime)
week_52_day_2014 = datetime(2014, 12, 27, 13, 0) # Sunday
week_1_day_2014_2015 = datetime(2014, 12, 31, 13, 0) # Wednesday
week_53_day_2015 = datetime(2015, 12, 31, 13, 0) # Thursday
if settings.USE_TZ:
week_1_day_2014_2015 = timezone.make_aware(week_1_day_2014_2015)
week_52_day_2014 = timezone.make_aware(week_52_day_2014)
week_53_day_2015 = timezone.make_aware(week_53_day_2015)
days = [week_52_day_2014, week_1_day_2014_2015, week_53_day_2015]
self.create_model(week_53_day_2015, end_datetime)
self.create_model(week_52_day_2014, end_datetime)
self.create_model(week_1_day_2014_2015, end_datetime)
qs = (
DTModel.objects.filter(start_datetime__in=days)
.annotate(
extracted=ExtractWeek("start_datetime"),
)
.order_by("start_datetime")
)
self.assertQuerySetEqual(
qs,
[
(week_52_day_2014, 52),
(week_1_day_2014_2015, 1),
(week_53_day_2015, 53),
],
lambda m: (m.start_datetime, m.extracted),
)
def test_extract_weekday_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=ExtractWeekDay("start_datetime")
).order_by("start_datetime"),
[
(start_datetime, (start_datetime.isoweekday() % 7) + 1),
(end_datetime, (end_datetime.isoweekday() % 7) + 1),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=ExtractWeekDay("start_date")).order_by(
"start_datetime"
),
[
(start_datetime, (start_datetime.isoweekday() % 7) + 1),
(end_datetime, (end_datetime.isoweekday() % 7) + 1),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(
start_datetime__week_day=ExtractWeekDay("start_datetime")
).count(),
2,
)
def test_extract_iso_weekday_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=ExtractIsoWeekDay("start_datetime"),
).order_by("start_datetime"),
[
(start_datetime, start_datetime.isoweekday()),
(end_datetime, end_datetime.isoweekday()),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=ExtractIsoWeekDay("start_date"),
).order_by("start_datetime"),
[
(start_datetime, start_datetime.isoweekday()),
(end_datetime, end_datetime.isoweekday()),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(
start_datetime__week_day=ExtractWeekDay("start_datetime"),
).count(),
2,
)
def test_extract_hour_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=ExtractHour("start_datetime")).order_by(
"start_datetime"
),
[(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=ExtractHour("start_time")).order_by(
"start_datetime"
),
[(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(
start_datetime__hour=ExtractHour("start_datetime")
).count(),
2,
)
def test_extract_minute_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=ExtractMinute("start_datetime")
).order_by("start_datetime"),
[
(start_datetime, start_datetime.minute),
(end_datetime, end_datetime.minute),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=ExtractMinute("start_time")).order_by(
"start_datetime"
),
[
(start_datetime, start_datetime.minute),
(end_datetime, end_datetime.minute),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(
start_datetime__minute=ExtractMinute("start_datetime")
).count(),
2,
)
def test_extract_second_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(
extracted=ExtractSecond("start_datetime")
).order_by("start_datetime"),
[
(start_datetime, start_datetime.second),
(end_datetime, end_datetime.second),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=ExtractSecond("start_time")).order_by(
"start_datetime"
),
[
(start_datetime, start_datetime.second),
(end_datetime, end_datetime.second),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(
start_datetime__second=ExtractSecond("start_datetime")
).count(),
2,
)
def test_extract_second_func_no_fractional(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 30, 50, 783)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
obj = self.create_model(start_datetime, end_datetime)
self.assertSequenceEqual(
DTModel.objects.filter(start_datetime__second=F("end_datetime__second")),
[obj],
)
self.assertSequenceEqual(
DTModel.objects.filter(start_time__second=F("end_time__second")),
[obj],
)
def test_trunc_lookup_name_sql_injection(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
# Database backends raise an exception or don't return any results.
try:
exists = DTModel.objects.filter(
start_datetime__date=Trunc(
"start_datetime",
"year', start_datetime)) OR 1=1;--",
)
).exists()
except (DataError, OperationalError):
pass
else:
self.assertIs(exists, False)
def test_trunc_func(self):
start_datetime = datetime(999, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
def test_datetime_kind(kind):
self.assertQuerySetEqual(
DTModel.objects.annotate(
truncated=Trunc(
"start_datetime", kind, output_field=DateTimeField()
)
).order_by("start_datetime"),
[
(start_datetime, truncate_to(start_datetime, kind)),
(end_datetime, truncate_to(end_datetime, kind)),
],
lambda m: (m.start_datetime, m.truncated),
)
def test_date_kind(kind):
self.assertQuerySetEqual(
DTModel.objects.annotate(
truncated=Trunc("start_date", kind, output_field=DateField())
).order_by("start_datetime"),
[
(start_datetime, truncate_to(start_datetime.date(), kind)),
(end_datetime, truncate_to(end_datetime.date(), kind)),
],
lambda m: (m.start_datetime, m.truncated),
)
def test_time_kind(kind):
self.assertQuerySetEqual(
DTModel.objects.annotate(
truncated=Trunc("start_time", kind, output_field=TimeField())
).order_by("start_datetime"),
[
(start_datetime, truncate_to(start_datetime.time(), kind)),
(end_datetime, truncate_to(end_datetime.time(), kind)),
],
lambda m: (m.start_datetime, m.truncated),
)
def test_datetime_to_time_kind(kind):
self.assertQuerySetEqual(
DTModel.objects.annotate(
truncated=Trunc("start_datetime", kind, output_field=TimeField()),
).order_by("start_datetime"),
[
(start_datetime, truncate_to(start_datetime.time(), kind)),
(end_datetime, truncate_to(end_datetime.time(), kind)),
],
lambda m: (m.start_datetime, m.truncated),
)
test_date_kind("year")
test_date_kind("quarter")
test_date_kind("month")
test_date_kind("day")
test_time_kind("hour")
test_time_kind("minute")
test_time_kind("second")
test_datetime_kind("year")
test_datetime_kind("quarter")
test_datetime_kind("month")
test_datetime_kind("day")
test_datetime_kind("hour")
test_datetime_kind("minute")
test_datetime_kind("second")
test_datetime_to_time_kind("hour")
test_datetime_to_time_kind("minute")
test_datetime_to_time_kind("second")
qs = DTModel.objects.filter(
start_datetime__date=Trunc(
"start_datetime", "day", output_field=DateField()
)
)
self.assertEqual(qs.count(), 2)
def _test_trunc_week(self, start_datetime, end_datetime):
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(
truncated=Trunc("start_datetime", "week", output_field=DateTimeField())
).order_by("start_datetime"),
[
(start_datetime, truncate_to(start_datetime, "week")),
(end_datetime, truncate_to(end_datetime, "week")),
],
lambda m: (m.start_datetime, m.truncated),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(
truncated=Trunc("start_date", "week", output_field=DateField())
).order_by("start_datetime"),
[
(start_datetime, truncate_to(start_datetime.date(), "week")),
(end_datetime, truncate_to(end_datetime.date(), "week")),
],
lambda m: (m.start_datetime, m.truncated),
)
def test_trunc_week(self):
self._test_trunc_week(
start_datetime=datetime(2015, 6, 15, 14, 30, 50, 321),
end_datetime=datetime(2016, 6, 15, 14, 10, 50, 123),
)
def test_trunc_week_before_1000(self):
self._test_trunc_week(
start_datetime=datetime(999, 6, 15, 14, 30, 50, 321),
end_datetime=datetime(2016, 6, 15, 14, 10, 50, 123),
)
def test_trunc_invalid_arguments(self):
msg = "output_field must be either DateField, TimeField, or DateTimeField"
with self.assertRaisesMessage(ValueError, msg):
list(
DTModel.objects.annotate(
truncated=Trunc(
"start_datetime", "year", output_field=IntegerField()
),
)
)
msg = "'name' isn't a DateField, TimeField, or DateTimeField."
with self.assertRaisesMessage(TypeError, msg):
list(
DTModel.objects.annotate(
truncated=Trunc("name", "year", output_field=DateTimeField()),
)
)
msg = "Cannot truncate DateField 'start_date' to DateTimeField"
with self.assertRaisesMessage(ValueError, msg):
list(DTModel.objects.annotate(truncated=Trunc("start_date", "second")))
with self.assertRaisesMessage(ValueError, msg):
list(
DTModel.objects.annotate(
truncated=Trunc(
"start_date", "month", output_field=DateTimeField()
),
)
)
msg = "Cannot truncate TimeField 'start_time' to DateTimeField"
with self.assertRaisesMessage(ValueError, msg):
list(DTModel.objects.annotate(truncated=Trunc("start_time", "month")))
with self.assertRaisesMessage(ValueError, msg):
list(
DTModel.objects.annotate(
truncated=Trunc(
"start_time", "second", output_field=DateTimeField()
),
)
)
def test_trunc_none(self):
self.create_model(None, None)
for t in (
Trunc("start_datetime", "year"),
Trunc("start_date", "year"),
Trunc("start_time", "hour"),
):
with self.subTest(t):
self.assertIsNone(
DTModel.objects.annotate(truncated=t).first().truncated
)
def test_trunc_year_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "year")
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=TruncYear("start_datetime")).order_by(
"start_datetime"
),
[
(start_datetime, truncate_to(start_datetime, "year")),
(end_datetime, truncate_to(end_datetime, "year")),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=TruncYear("start_date")).order_by(
"start_datetime"
),
[
(start_datetime, truncate_to(start_datetime.date(), "year")),
(end_datetime, truncate_to(end_datetime.date(), "year")),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(start_datetime=TruncYear("start_datetime")).count(),
1,
)
with self.assertRaisesMessage(
ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"
):
list(DTModel.objects.annotate(truncated=TruncYear("start_time")))
with self.assertRaisesMessage(
ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"
):
list(
DTModel.objects.annotate(
truncated=TruncYear("start_time", output_field=TimeField())
)
)
def test_trunc_quarter_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = truncate_to(datetime(2016, 10, 15, 14, 10, 50, 123), "quarter")
last_quarter_2015 = truncate_to(
datetime(2015, 12, 31, 14, 10, 50, 123), "quarter"
)
first_quarter_2016 = truncate_to(
datetime(2016, 1, 1, 14, 10, 50, 123), "quarter"
)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
last_quarter_2015 = timezone.make_aware(last_quarter_2015)
first_quarter_2016 = timezone.make_aware(first_quarter_2016)
self.create_model(start_datetime=start_datetime, end_datetime=end_datetime)
self.create_model(start_datetime=end_datetime, end_datetime=start_datetime)
self.create_model(start_datetime=last_quarter_2015, end_datetime=end_datetime)
self.create_model(start_datetime=first_quarter_2016, end_datetime=end_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=TruncQuarter("start_date")).order_by(
"start_datetime"
),
[
(start_datetime, truncate_to(start_datetime.date(), "quarter")),
(last_quarter_2015, truncate_to(last_quarter_2015.date(), "quarter")),
(first_quarter_2016, truncate_to(first_quarter_2016.date(), "quarter")),
(end_datetime, truncate_to(end_datetime.date(), "quarter")),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=TruncQuarter("start_datetime")).order_by(
"start_datetime"
),
[
(start_datetime, truncate_to(start_datetime, "quarter")),
(last_quarter_2015, truncate_to(last_quarter_2015, "quarter")),
(first_quarter_2016, truncate_to(first_quarter_2016, "quarter")),
(end_datetime, truncate_to(end_datetime, "quarter")),
],
lambda m: (m.start_datetime, m.extracted),
)
with self.assertRaisesMessage(
ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"
):
list(DTModel.objects.annotate(truncated=TruncQuarter("start_time")))
with self.assertRaisesMessage(
ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"
):
list(
DTModel.objects.annotate(
truncated=TruncQuarter("start_time", output_field=TimeField())
)
)
def test_trunc_month_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "month")
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=TruncMonth("start_datetime")).order_by(
"start_datetime"
),
[
(start_datetime, truncate_to(start_datetime, "month")),
(end_datetime, truncate_to(end_datetime, "month")),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=TruncMonth("start_date")).order_by(
"start_datetime"
),
[
(start_datetime, truncate_to(start_datetime.date(), "month")),
(end_datetime, truncate_to(end_datetime.date(), "month")),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(start_datetime=TruncMonth("start_datetime")).count(),
1,
)
with self.assertRaisesMessage(
ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"
):
list(DTModel.objects.annotate(truncated=TruncMonth("start_time")))
with self.assertRaisesMessage(
ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"
):
list(
DTModel.objects.annotate(
truncated=TruncMonth("start_time", output_field=TimeField())
)
)
def test_trunc_week_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "week")
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=TruncWeek("start_datetime")).order_by(
"start_datetime"
),
[
(start_datetime, truncate_to(start_datetime, "week")),
(end_datetime, truncate_to(end_datetime, "week")),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(start_datetime=TruncWeek("start_datetime")).count(),
1,
)
with self.assertRaisesMessage(
ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"
):
list(DTModel.objects.annotate(truncated=TruncWeek("start_time")))
with self.assertRaisesMessage(
ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"
):
list(
DTModel.objects.annotate(
truncated=TruncWeek("start_time", output_field=TimeField())
)
)
def test_trunc_date_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=TruncDate("start_datetime")).order_by(
"start_datetime"
),
[
(start_datetime, start_datetime.date()),
(end_datetime, end_datetime.date()),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(
start_datetime__date=TruncDate("start_datetime")
).count(),
2,
)
with self.assertRaisesMessage(
ValueError, "Cannot truncate TimeField 'start_time' to DateField"
):
list(DTModel.objects.annotate(truncated=TruncDate("start_time")))
with self.assertRaisesMessage(
ValueError, "Cannot truncate TimeField 'start_time' to DateField"
):
list(
DTModel.objects.annotate(
truncated=TruncDate("start_time", output_field=TimeField())
)
)
def test_trunc_date_none(self):
self.create_model(None, None)
self.assertIsNone(
DTModel.objects.annotate(truncated=TruncDate("start_datetime"))
.first()
.truncated
)
def test_trunc_time_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=TruncTime("start_datetime")).order_by(
"start_datetime"
),
[
(start_datetime, start_datetime.time()),
(end_datetime, end_datetime.time()),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(
start_datetime__time=TruncTime("start_datetime")
).count(),
2,
)
with self.assertRaisesMessage(
ValueError, "Cannot truncate DateField 'start_date' to TimeField"
):
list(DTModel.objects.annotate(truncated=TruncTime("start_date")))
with self.assertRaisesMessage(
ValueError, "Cannot truncate DateField 'start_date' to TimeField"
):
list(
DTModel.objects.annotate(
truncated=TruncTime("start_date", output_field=DateField())
)
)
def test_trunc_time_none(self):
self.create_model(None, None)
self.assertIsNone(
DTModel.objects.annotate(truncated=TruncTime("start_datetime"))
.first()
.truncated
)
def test_trunc_time_comparison(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 26) # 0 microseconds.
end_datetime = datetime(2015, 6, 15, 14, 30, 26, 321)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.assertIs(
DTModel.objects.filter(
start_datetime__time=start_datetime.time(),
end_datetime__time=end_datetime.time(),
).exists(),
True,
)
self.assertIs(
DTModel.objects.annotate(
extracted_start=TruncTime("start_datetime"),
extracted_end=TruncTime("end_datetime"),
)
.filter(
extracted_start=start_datetime.time(),
extracted_end=end_datetime.time(),
)
.exists(),
True,
)
def test_trunc_day_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "day")
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=TruncDay("start_datetime")).order_by(
"start_datetime"
),
[
(start_datetime, truncate_to(start_datetime, "day")),
(end_datetime, truncate_to(end_datetime, "day")),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(start_datetime=TruncDay("start_datetime")).count(), 1
)
with self.assertRaisesMessage(
ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"
):
list(DTModel.objects.annotate(truncated=TruncDay("start_time")))
with self.assertRaisesMessage(
ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"
):
list(
DTModel.objects.annotate(
truncated=TruncDay("start_time", output_field=TimeField())
)
)
def test_trunc_hour_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "hour")
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=TruncHour("start_datetime")).order_by(
"start_datetime"
),
[
(start_datetime, truncate_to(start_datetime, "hour")),
(end_datetime, truncate_to(end_datetime, "hour")),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=TruncHour("start_time")).order_by(
"start_datetime"
),
[
(start_datetime, truncate_to(start_datetime.time(), "hour")),
(end_datetime, truncate_to(end_datetime.time(), "hour")),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(start_datetime=TruncHour("start_datetime")).count(),
1,
)
with self.assertRaisesMessage(
ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"
):
list(DTModel.objects.annotate(truncated=TruncHour("start_date")))
with self.assertRaisesMessage(
ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"
):
list(
DTModel.objects.annotate(
truncated=TruncHour("start_date", output_field=DateField())
)
)
def test_trunc_minute_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "minute")
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=TruncMinute("start_datetime")).order_by(
"start_datetime"
),
[
(start_datetime, truncate_to(start_datetime, "minute")),
(end_datetime, truncate_to(end_datetime, "minute")),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=TruncMinute("start_time")).order_by(
"start_datetime"
),
[
(start_datetime, truncate_to(start_datetime.time(), "minute")),
(end_datetime, truncate_to(end_datetime.time(), "minute")),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(
start_datetime=TruncMinute("start_datetime")
).count(),
1,
)
with self.assertRaisesMessage(
ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"
):
list(DTModel.objects.annotate(truncated=TruncMinute("start_date")))
with self.assertRaisesMessage(
ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"
):
list(
DTModel.objects.annotate(
truncated=TruncMinute("start_date", output_field=DateField())
)
)
def test_trunc_second_func(self):
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "second")
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=TruncSecond("start_datetime")).order_by(
"start_datetime"
),
[
(start_datetime, truncate_to(start_datetime, "second")),
(end_datetime, truncate_to(end_datetime, "second")),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertQuerySetEqual(
DTModel.objects.annotate(extracted=TruncSecond("start_time")).order_by(
"start_datetime"
),
[
(start_datetime, truncate_to(start_datetime.time(), "second")),
(end_datetime, truncate_to(end_datetime.time(), "second")),
],
lambda m: (m.start_datetime, m.extracted),
)
self.assertEqual(
DTModel.objects.filter(
start_datetime=TruncSecond("start_datetime")
).count(),
1,
)
with self.assertRaisesMessage(
ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"
):
list(DTModel.objects.annotate(truncated=TruncSecond("start_date")))
with self.assertRaisesMessage(
ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"
):
list(
DTModel.objects.annotate(
truncated=TruncSecond("start_date", output_field=DateField())
)
)
def test_trunc_subquery_with_parameters(self):
author_1 = Author.objects.create(name="J. R. R. Tolkien")
author_2 = Author.objects.create(name="G. R. R. Martin")
fan_since_1 = datetime(2016, 2, 3, 15, 0, 0)
fan_since_2 = datetime(2015, 2, 3, 15, 0, 0)
fan_since_3 = datetime(2017, 2, 3, 15, 0, 0)
if settings.USE_TZ:
fan_since_1 = timezone.make_aware(fan_since_1)
fan_since_2 = timezone.make_aware(fan_since_2)
fan_since_3 = timezone.make_aware(fan_since_3)
Fan.objects.create(author=author_1, name="Tom", fan_since=fan_since_1)
Fan.objects.create(author=author_1, name="Emma", fan_since=fan_since_2)
Fan.objects.create(author=author_2, name="Isabella", fan_since=fan_since_3)
inner = (
Fan.objects.filter(
author=OuterRef("pk"), name__in=("Emma", "Isabella", "Tom")
)
.values("author")
.annotate(newest_fan=Max("fan_since"))
.values("newest_fan")
)
outer = Author.objects.annotate(
newest_fan_year=TruncYear(Subquery(inner, output_field=DateTimeField()))
)
tz = datetime_timezone.utc if settings.USE_TZ else None
self.assertSequenceEqual(
outer.order_by("name").values("name", "newest_fan_year"),
[
{
"name": "G. R. R. Martin",
"newest_fan_year": datetime(2017, 1, 1, 0, 0, tzinfo=tz),
},
{
"name": "J. R. R. Tolkien",
"newest_fan_year": datetime(2016, 1, 1, 0, 0, tzinfo=tz),
},
],
)
def test_extract_outerref(self):
datetime_1 = datetime(2000, 1, 1)
datetime_2 = datetime(2001, 3, 5)
datetime_3 = datetime(2002, 1, 3)
if settings.USE_TZ:
datetime_1 = timezone.make_aware(datetime_1)
datetime_2 = timezone.make_aware(datetime_2)
datetime_3 = timezone.make_aware(datetime_3)
obj_1 = self.create_model(datetime_1, datetime_3)
obj_2 = self.create_model(datetime_2, datetime_1)
obj_3 = self.create_model(datetime_3, datetime_2)
inner_qs = DTModel.objects.filter(
start_datetime__year=2000,
start_datetime__month=ExtractMonth(OuterRef("end_datetime")),
)
qs = DTModel.objects.annotate(
related_pk=Subquery(inner_qs.values("pk")[:1]),
)
self.assertSequenceEqual(
qs.order_by("name").values("pk", "related_pk"),
[
{"pk": obj_1.pk, "related_pk": obj_1.pk},
{"pk": obj_2.pk, "related_pk": obj_1.pk},
{"pk": obj_3.pk, "related_pk": None},
],
)
@override_settings(USE_TZ=True, TIME_ZONE="UTC")
class DateFunctionWithTimeZoneTests(DateFunctionTests):
def get_timezones(self, key):
for constructor in ZONE_CONSTRUCTORS:
yield constructor(key)
def test_extract_func_with_timezone(self):
start_datetime = datetime(2015, 6, 15, 23, 30, 1, 321)
end_datetime = datetime(2015, 6, 16, 13, 11, 27, 123)
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
delta_tzinfo_pos = datetime_timezone(timedelta(hours=5))
delta_tzinfo_neg = datetime_timezone(timedelta(hours=-5, minutes=17))
for melb in self.get_timezones("Australia/Melbourne"):
with self.subTest(repr(melb)):
qs = DTModel.objects.annotate(
day=Extract("start_datetime", "day"),
day_melb=Extract("start_datetime", "day", tzinfo=melb),
week=Extract("start_datetime", "week", tzinfo=melb),
isoyear=ExtractIsoYear("start_datetime", tzinfo=melb),
weekday=ExtractWeekDay("start_datetime"),
weekday_melb=ExtractWeekDay("start_datetime", tzinfo=melb),
isoweekday=ExtractIsoWeekDay("start_datetime"),
isoweekday_melb=ExtractIsoWeekDay("start_datetime", tzinfo=melb),
quarter=ExtractQuarter("start_datetime", tzinfo=melb),
hour=ExtractHour("start_datetime"),
hour_melb=ExtractHour("start_datetime", tzinfo=melb),
hour_with_delta_pos=ExtractHour(
"start_datetime", tzinfo=delta_tzinfo_pos
),
hour_with_delta_neg=ExtractHour(
"start_datetime", tzinfo=delta_tzinfo_neg
),
minute_with_delta_neg=ExtractMinute(
"start_datetime", tzinfo=delta_tzinfo_neg
),
).order_by("start_datetime")
utc_model = qs.get()
self.assertEqual(utc_model.day, 15)
self.assertEqual(utc_model.day_melb, 16)
self.assertEqual(utc_model.week, 25)
self.assertEqual(utc_model.isoyear, 2015)
self.assertEqual(utc_model.weekday, 2)
self.assertEqual(utc_model.weekday_melb, 3)
self.assertEqual(utc_model.isoweekday, 1)
self.assertEqual(utc_model.isoweekday_melb, 2)
self.assertEqual(utc_model.quarter, 2)
self.assertEqual(utc_model.hour, 23)
self.assertEqual(utc_model.hour_melb, 9)
self.assertEqual(utc_model.hour_with_delta_pos, 4)
self.assertEqual(utc_model.hour_with_delta_neg, 18)
self.assertEqual(utc_model.minute_with_delta_neg, 47)
with timezone.override(melb):
melb_model = qs.get()
self.assertEqual(melb_model.day, 16)
self.assertEqual(melb_model.day_melb, 16)
self.assertEqual(melb_model.week, 25)
self.assertEqual(melb_model.isoyear, 2015)
self.assertEqual(melb_model.weekday, 3)
self.assertEqual(melb_model.isoweekday, 2)
self.assertEqual(melb_model.quarter, 2)
self.assertEqual(melb_model.weekday_melb, 3)
self.assertEqual(melb_model.isoweekday_melb, 2)
self.assertEqual(melb_model.hour, 9)
self.assertEqual(melb_model.hour_melb, 9)
def test_extract_func_with_timezone_minus_no_offset(self):
start_datetime = datetime(2015, 6, 15, 23, 30, 1, 321)
end_datetime = datetime(2015, 6, 16, 13, 11, 27, 123)
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
for ust_nera in self.get_timezones("Asia/Ust-Nera"):
with self.subTest(repr(ust_nera)):
qs = DTModel.objects.annotate(
hour=ExtractHour("start_datetime"),
hour_tz=ExtractHour("start_datetime", tzinfo=ust_nera),
).order_by("start_datetime")
utc_model = qs.get()
self.assertEqual(utc_model.hour, 23)
self.assertEqual(utc_model.hour_tz, 9)
with timezone.override(ust_nera):
ust_nera_model = qs.get()
self.assertEqual(ust_nera_model.hour, 9)
self.assertEqual(ust_nera_model.hour_tz, 9)
def test_extract_func_explicit_timezone_priority(self):
start_datetime = datetime(2015, 6, 15, 23, 30, 1, 321)
end_datetime = datetime(2015, 6, 16, 13, 11, 27, 123)
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
for melb in self.get_timezones("Australia/Melbourne"):
with self.subTest(repr(melb)):
with timezone.override(melb):
model = (
DTModel.objects.annotate(
day_melb=Extract("start_datetime", "day"),
day_utc=Extract(
"start_datetime", "day", tzinfo=datetime_timezone.utc
),
)
.order_by("start_datetime")
.get()
)
self.assertEqual(model.day_melb, 16)
self.assertEqual(model.day_utc, 15)
def test_extract_invalid_field_with_timezone(self):
for melb in self.get_timezones("Australia/Melbourne"):
with self.subTest(repr(melb)):
msg = "tzinfo can only be used with DateTimeField."
with self.assertRaisesMessage(ValueError, msg):
DTModel.objects.annotate(
day_melb=Extract("start_date", "day", tzinfo=melb),
).get()
with self.assertRaisesMessage(ValueError, msg):
DTModel.objects.annotate(
hour_melb=Extract("start_time", "hour", tzinfo=melb),
).get()
def test_trunc_timezone_applied_before_truncation(self):
start_datetime = datetime(2016, 1, 1, 1, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
for melb, pacific in zip(
self.get_timezones("Australia/Melbourne"),
self.get_timezones("America/Los_Angeles"),
):
with self.subTest((repr(melb), repr(pacific))):
model = (
DTModel.objects.annotate(
melb_year=TruncYear("start_datetime", tzinfo=melb),
pacific_year=TruncYear("start_datetime", tzinfo=pacific),
melb_date=TruncDate("start_datetime", tzinfo=melb),
pacific_date=TruncDate("start_datetime", tzinfo=pacific),
melb_time=TruncTime("start_datetime", tzinfo=melb),
pacific_time=TruncTime("start_datetime", tzinfo=pacific),
)
.order_by("start_datetime")
.get()
)
melb_start_datetime = start_datetime.astimezone(melb)
pacific_start_datetime = start_datetime.astimezone(pacific)
self.assertEqual(model.start_datetime, start_datetime)
self.assertEqual(
model.melb_year, truncate_to(start_datetime, "year", melb)
)
self.assertEqual(
model.pacific_year, truncate_to(start_datetime, "year", pacific)
)
self.assertEqual(model.start_datetime.year, 2016)
self.assertEqual(model.melb_year.year, 2016)
self.assertEqual(model.pacific_year.year, 2015)
self.assertEqual(model.melb_date, melb_start_datetime.date())
self.assertEqual(model.pacific_date, pacific_start_datetime.date())
self.assertEqual(model.melb_time, melb_start_datetime.time())
self.assertEqual(model.pacific_time, pacific_start_datetime.time())
@needs_pytz
@ignore_warnings(category=RemovedInDjango50Warning)
def test_trunc_ambiguous_and_invalid_times(self):
sao = pytz.timezone("America/Sao_Paulo")
start_datetime = datetime(2016, 10, 16, 13, tzinfo=datetime_timezone.utc)
end_datetime = datetime(2016, 2, 21, 1, tzinfo=datetime_timezone.utc)
self.create_model(start_datetime, end_datetime)
with timezone.override(sao):
with self.assertRaisesMessage(
pytz.NonExistentTimeError, "2016-10-16 00:00:00"
):
model = DTModel.objects.annotate(
truncated_start=TruncDay("start_datetime")
).get()
with self.assertRaisesMessage(
pytz.AmbiguousTimeError, "2016-02-20 23:00:00"
):
model = DTModel.objects.annotate(
truncated_end=TruncHour("end_datetime")
).get()
model = DTModel.objects.annotate(
truncated_start=TruncDay("start_datetime", is_dst=False),
truncated_end=TruncHour("end_datetime", is_dst=False),
).get()
self.assertEqual(model.truncated_start.dst(), timedelta(0))
self.assertEqual(model.truncated_end.dst(), timedelta(0))
model = DTModel.objects.annotate(
truncated_start=TruncDay("start_datetime", is_dst=True),
truncated_end=TruncHour("end_datetime", is_dst=True),
).get()
self.assertEqual(model.truncated_start.dst(), timedelta(0, 3600))
self.assertEqual(model.truncated_end.dst(), timedelta(0, 3600))
def test_trunc_func_with_timezone(self):
"""
If the truncated datetime transitions to a different offset (daylight
saving) then the returned value will have that new timezone/offset.
"""
start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321)
end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123)
start_datetime = timezone.make_aware(start_datetime)
end_datetime = timezone.make_aware(end_datetime)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
for melb in self.get_timezones("Australia/Melbourne"):
with self.subTest(repr(melb)):
def test_datetime_kind(kind):
self.assertQuerySetEqual(
DTModel.objects.annotate(
truncated=Trunc(
"start_datetime",
kind,
output_field=DateTimeField(),
tzinfo=melb,
)
).order_by("start_datetime"),
[
(
start_datetime,
truncate_to(
start_datetime.astimezone(melb), kind, melb
),
),
(
end_datetime,
truncate_to(end_datetime.astimezone(melb), kind, melb),
),
],
lambda m: (m.start_datetime, m.truncated),
)
def test_datetime_to_date_kind(kind):
self.assertQuerySetEqual(
DTModel.objects.annotate(
truncated=Trunc(
"start_datetime",
kind,
output_field=DateField(),
tzinfo=melb,
),
).order_by("start_datetime"),
[
(
start_datetime,
truncate_to(
start_datetime.astimezone(melb).date(), kind
),
),
(
end_datetime,
truncate_to(end_datetime.astimezone(melb).date(), kind),
),
],
lambda m: (m.start_datetime, m.truncated),
)
def test_datetime_to_time_kind(kind):
self.assertQuerySetEqual(
DTModel.objects.annotate(
truncated=Trunc(
"start_datetime",
kind,
output_field=TimeField(),
tzinfo=melb,
)
).order_by("start_datetime"),
[
(
start_datetime,
truncate_to(
start_datetime.astimezone(melb).time(), kind
),
),
(
end_datetime,
truncate_to(end_datetime.astimezone(melb).time(), kind),
),
],
lambda m: (m.start_datetime, m.truncated),
)
test_datetime_to_date_kind("year")
test_datetime_to_date_kind("quarter")
test_datetime_to_date_kind("month")
test_datetime_to_date_kind("week")
test_datetime_to_date_kind("day")
test_datetime_to_time_kind("hour")
test_datetime_to_time_kind("minute")
test_datetime_to_time_kind("second")
test_datetime_kind("year")
test_datetime_kind("quarter")
test_datetime_kind("month")
test_datetime_kind("week")
test_datetime_kind("day")
test_datetime_kind("hour")
test_datetime_kind("minute")
test_datetime_kind("second")
qs = DTModel.objects.filter(
start_datetime__date=Trunc(
"start_datetime", "day", output_field=DateField()
)
)
self.assertEqual(qs.count(), 2)
def test_trunc_invalid_field_with_timezone(self):
for melb in self.get_timezones("Australia/Melbourne"):
with self.subTest(repr(melb)):
msg = "tzinfo can only be used with DateTimeField."
with self.assertRaisesMessage(ValueError, msg):
DTModel.objects.annotate(
day_melb=Trunc("start_date", "day", tzinfo=melb),
).get()
with self.assertRaisesMessage(ValueError, msg):
DTModel.objects.annotate(
hour_melb=Trunc("start_time", "hour", tzinfo=melb),
).get()
|
a71f585c459150e4e552a5540b646c57a7fdab097b7321f36208d2c0d53341e9 | from django.db.models import Subquery, TextField
from django.db.models.functions import Coalesce, Lower
from django.test import TestCase
from django.utils import timezone
from ..models import Article, Author
lorem_ipsum = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua."""
class CoalesceTests(TestCase):
def test_basic(self):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
authors = Author.objects.annotate(display_name=Coalesce("alias", "name"))
self.assertQuerySetEqual(
authors.order_by("name"), ["smithj", "Rhonda"], lambda a: a.display_name
)
def test_gt_two_expressions(self):
with self.assertRaisesMessage(
ValueError, "Coalesce must take at least two expressions"
):
Author.objects.annotate(display_name=Coalesce("alias"))
def test_mixed_values(self):
a1 = Author.objects.create(name="John Smith", alias="smithj")
a2 = Author.objects.create(name="Rhonda")
ar1 = Article.objects.create(
title="How to Django",
text=lorem_ipsum,
written=timezone.now(),
)
ar1.authors.add(a1)
ar1.authors.add(a2)
# mixed Text and Char
article = Article.objects.annotate(
headline=Coalesce("summary", "text", output_field=TextField()),
)
self.assertQuerySetEqual(
article.order_by("title"), [lorem_ipsum], lambda a: a.headline
)
# mixed Text and Char wrapped
article = Article.objects.annotate(
headline=Coalesce(
Lower("summary"), Lower("text"), output_field=TextField()
),
)
self.assertQuerySetEqual(
article.order_by("title"), [lorem_ipsum.lower()], lambda a: a.headline
)
def test_ordering(self):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
authors = Author.objects.order_by(Coalesce("alias", "name"))
self.assertQuerySetEqual(authors, ["Rhonda", "John Smith"], lambda a: a.name)
authors = Author.objects.order_by(Coalesce("alias", "name").asc())
self.assertQuerySetEqual(authors, ["Rhonda", "John Smith"], lambda a: a.name)
authors = Author.objects.order_by(Coalesce("alias", "name").desc())
self.assertQuerySetEqual(authors, ["John Smith", "Rhonda"], lambda a: a.name)
def test_empty_queryset(self):
Author.objects.create(name="John Smith")
queryset = Author.objects.values("id")
tests = [
(queryset.none(), "QuerySet.none()"),
(queryset.filter(id=0), "QuerySet.filter(id=0)"),
(Subquery(queryset.none()), "Subquery(QuerySet.none())"),
(Subquery(queryset.filter(id=0)), "Subquery(Queryset.filter(id=0)"),
]
for empty_query, description in tests:
with self.subTest(description), self.assertNumQueries(1):
qs = Author.objects.annotate(annotation=Coalesce(empty_query, 42))
self.assertEqual(qs.first().annotation, 42)
|
ae6b4406290048091016543a0d8488a5cd0c8389bd8f2f03d5d2c5e21d8c4a31 | import os
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponse, HttpResponsePermanentRedirect
from django.middleware.locale import LocaleMiddleware
from django.template import Context, Template
from django.test import SimpleTestCase, override_settings
from django.test.client import RequestFactory
from django.test.utils import override_script_prefix
from django.urls import clear_url_caches, resolve, reverse, translate_url
from django.utils import translation
class PermanentRedirectLocaleMiddleWare(LocaleMiddleware):
response_redirect_class = HttpResponsePermanentRedirect
@override_settings(
USE_I18N=True,
LOCALE_PATHS=[
os.path.join(os.path.dirname(__file__), "locale"),
],
LANGUAGE_CODE="en-us",
LANGUAGES=[
("nl", "Dutch"),
("en", "English"),
("pt-br", "Brazilian Portuguese"),
],
MIDDLEWARE=[
"django.middleware.locale.LocaleMiddleware",
"django.middleware.common.CommonMiddleware",
],
ROOT_URLCONF="i18n.patterns.urls.default",
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [os.path.join(os.path.dirname(__file__), "templates")],
"OPTIONS": {
"context_processors": [
"django.template.context_processors.i18n",
],
},
}
],
)
class URLTestCaseBase(SimpleTestCase):
"""
TestCase base-class for the URL tests.
"""
def setUp(self):
# Make sure the cache is empty before we are doing our tests.
clear_url_caches()
def tearDown(self):
# Make sure we will leave an empty cache for other testcases.
clear_url_caches()
class URLPrefixTests(URLTestCaseBase):
"""
Tests if the `i18n_patterns` is adding the prefix correctly.
"""
def test_not_prefixed(self):
with translation.override("en"):
self.assertEqual(reverse("not-prefixed"), "/not-prefixed/")
self.assertEqual(
reverse("not-prefixed-included-url"), "/not-prefixed-include/foo/"
)
with translation.override("nl"):
self.assertEqual(reverse("not-prefixed"), "/not-prefixed/")
self.assertEqual(
reverse("not-prefixed-included-url"), "/not-prefixed-include/foo/"
)
def test_prefixed(self):
with translation.override("en"):
self.assertEqual(reverse("prefixed"), "/en/prefixed/")
with translation.override("nl"):
self.assertEqual(reverse("prefixed"), "/nl/prefixed/")
with translation.override(None):
self.assertEqual(
reverse("prefixed"), "/%s/prefixed/" % settings.LANGUAGE_CODE
)
@override_settings(ROOT_URLCONF="i18n.patterns.urls.wrong")
def test_invalid_prefix_use(self):
msg = "Using i18n_patterns in an included URLconf is not allowed."
with self.assertRaisesMessage(ImproperlyConfigured, msg):
reverse("account:register")
@override_settings(ROOT_URLCONF="i18n.patterns.urls.disabled")
class URLDisabledTests(URLTestCaseBase):
@override_settings(USE_I18N=False)
def test_prefixed_i18n_disabled(self):
with translation.override("en"):
self.assertEqual(reverse("prefixed"), "/prefixed/")
with translation.override("nl"):
self.assertEqual(reverse("prefixed"), "/prefixed/")
class RequestURLConfTests(SimpleTestCase):
@override_settings(ROOT_URLCONF="i18n.patterns.urls.path_unused")
def test_request_urlconf_considered(self):
request = RequestFactory().get("/nl/")
request.urlconf = "i18n.patterns.urls.default"
middleware = LocaleMiddleware(lambda req: HttpResponse())
with translation.override("nl"):
middleware.process_request(request)
self.assertEqual(request.LANGUAGE_CODE, "nl")
@override_settings(ROOT_URLCONF="i18n.patterns.urls.path_unused")
class PathUnusedTests(URLTestCaseBase):
"""
If no i18n_patterns is used in root URLconfs, then no language activation
activation happens based on url prefix.
"""
def test_no_lang_activate(self):
response = self.client.get("/nl/foo/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers["content-language"], "en")
self.assertEqual(response.context["LANGUAGE_CODE"], "en")
class URLTranslationTests(URLTestCaseBase):
"""
Tests if the pattern-strings are translated correctly (within the
`i18n_patterns` and the normal `patterns` function).
"""
def test_no_prefix_translated(self):
with translation.override("en"):
self.assertEqual(reverse("no-prefix-translated"), "/translated/")
self.assertEqual(
reverse("no-prefix-translated-slug", kwargs={"slug": "yeah"}),
"/translated/yeah/",
)
with translation.override("nl"):
self.assertEqual(reverse("no-prefix-translated"), "/vertaald/")
self.assertEqual(
reverse("no-prefix-translated-slug", kwargs={"slug": "yeah"}),
"/vertaald/yeah/",
)
with translation.override("pt-br"):
self.assertEqual(reverse("no-prefix-translated"), "/traduzidos/")
self.assertEqual(
reverse("no-prefix-translated-slug", kwargs={"slug": "yeah"}),
"/traduzidos/yeah/",
)
def test_users_url(self):
with translation.override("en"):
self.assertEqual(reverse("users"), "/en/users/")
with translation.override("nl"):
self.assertEqual(reverse("users"), "/nl/gebruikers/")
self.assertEqual(reverse("prefixed_xml"), "/nl/prefixed.xml")
with translation.override("pt-br"):
self.assertEqual(reverse("users"), "/pt-br/usuarios/")
def test_translate_url_utility(self):
with translation.override("en"):
self.assertEqual(
translate_url("/en/nonexistent/", "nl"), "/en/nonexistent/"
)
self.assertEqual(translate_url("/en/users/", "nl"), "/nl/gebruikers/")
# Namespaced URL
self.assertEqual(
translate_url("/en/account/register/", "nl"), "/nl/profiel/registreren/"
)
# path() URL pattern
self.assertEqual(
translate_url("/en/account/register-as-path/", "nl"),
"/nl/profiel/registreren-als-pad/",
)
self.assertEqual(translation.get_language(), "en")
# URL with parameters.
self.assertEqual(
translate_url("/en/with-arguments/regular-argument/", "nl"),
"/nl/with-arguments/regular-argument/",
)
self.assertEqual(
translate_url(
"/en/with-arguments/regular-argument/optional.html", "nl"
),
"/nl/with-arguments/regular-argument/optional.html",
)
with translation.override("nl"):
self.assertEqual(translate_url("/nl/gebruikers/", "en"), "/en/users/")
self.assertEqual(translation.get_language(), "nl")
def test_reverse_translated_with_captured_kwargs(self):
with translation.override("en"):
match = resolve("/translated/apo/")
# Links to the same page in other languages.
tests = [
("nl", "/vertaald/apo/"),
("pt-br", "/traduzidos/apo/"),
]
for lang, expected_link in tests:
with translation.override(lang):
self.assertEqual(
reverse(
match.url_name, args=match.args, kwargs=match.captured_kwargs
),
expected_link,
)
def test_locale_not_interepreted_as_regex(self):
with translation.override("e("):
# Would previously error:
# re.error: missing ), unterminated subpattern at position 1
reverse("users")
class URLNamespaceTests(URLTestCaseBase):
"""
Tests if the translations are still working within namespaces.
"""
def test_account_register(self):
with translation.override("en"):
self.assertEqual(reverse("account:register"), "/en/account/register/")
self.assertEqual(
reverse("account:register-as-path"), "/en/account/register-as-path/"
)
with translation.override("nl"):
self.assertEqual(reverse("account:register"), "/nl/profiel/registreren/")
self.assertEqual(
reverse("account:register-as-path"), "/nl/profiel/registreren-als-pad/"
)
class URLRedirectTests(URLTestCaseBase):
"""
Tests if the user gets redirected to the right URL when there is no
language-prefix in the request URL.
"""
def test_no_prefix_response(self):
response = self.client.get("/not-prefixed/")
self.assertEqual(response.status_code, 200)
def test_en_redirect(self):
response = self.client.get("/account/register/", HTTP_ACCEPT_LANGUAGE="en")
self.assertRedirects(response, "/en/account/register/")
response = self.client.get(response.headers["location"])
self.assertEqual(response.status_code, 200)
def test_en_redirect_wrong_url(self):
response = self.client.get("/profiel/registreren/", HTTP_ACCEPT_LANGUAGE="en")
self.assertEqual(response.status_code, 404)
def test_nl_redirect(self):
response = self.client.get("/profiel/registreren/", HTTP_ACCEPT_LANGUAGE="nl")
self.assertRedirects(response, "/nl/profiel/registreren/")
response = self.client.get(response.headers["location"])
self.assertEqual(response.status_code, 200)
def test_nl_redirect_wrong_url(self):
response = self.client.get("/account/register/", HTTP_ACCEPT_LANGUAGE="nl")
self.assertEqual(response.status_code, 404)
def test_pt_br_redirect(self):
response = self.client.get("/conta/registre-se/", HTTP_ACCEPT_LANGUAGE="pt-br")
self.assertRedirects(response, "/pt-br/conta/registre-se/")
response = self.client.get(response.headers["location"])
self.assertEqual(response.status_code, 200)
def test_pl_pl_redirect(self):
# language from outside of the supported LANGUAGES list
response = self.client.get("/account/register/", HTTP_ACCEPT_LANGUAGE="pl-pl")
self.assertRedirects(response, "/en/account/register/")
response = self.client.get(response.headers["location"])
self.assertEqual(response.status_code, 200)
@override_settings(
MIDDLEWARE=[
"i18n.patterns.tests.PermanentRedirectLocaleMiddleWare",
"django.middleware.common.CommonMiddleware",
],
)
def test_custom_redirect_class(self):
response = self.client.get("/account/register/", HTTP_ACCEPT_LANGUAGE="en")
self.assertRedirects(response, "/en/account/register/", 301)
class URLVaryAcceptLanguageTests(URLTestCaseBase):
"""
'Accept-Language' is not added to the Vary header when using prefixed URLs.
"""
def test_no_prefix_response(self):
response = self.client.get("/not-prefixed/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get("Vary"), "Accept-Language")
def test_en_redirect(self):
"""
The redirect to a prefixed URL depends on 'Accept-Language' and
'Cookie', but once prefixed no header is set.
"""
response = self.client.get("/account/register/", HTTP_ACCEPT_LANGUAGE="en")
self.assertRedirects(response, "/en/account/register/")
self.assertEqual(response.get("Vary"), "Accept-Language, Cookie")
response = self.client.get(response.headers["location"])
self.assertEqual(response.status_code, 200)
self.assertFalse(response.get("Vary"))
class URLRedirectWithoutTrailingSlashTests(URLTestCaseBase):
"""
Tests the redirect when the requested URL doesn't end with a slash
(`settings.APPEND_SLASH=True`).
"""
def test_not_prefixed_redirect(self):
response = self.client.get("/not-prefixed", HTTP_ACCEPT_LANGUAGE="en")
self.assertRedirects(response, "/not-prefixed/", 301)
def test_en_redirect(self):
response = self.client.get(
"/account/register", HTTP_ACCEPT_LANGUAGE="en", follow=True
)
# We only want one redirect, bypassing CommonMiddleware
self.assertEqual(response.redirect_chain, [("/en/account/register/", 302)])
self.assertRedirects(response, "/en/account/register/", 302)
response = self.client.get(
"/prefixed.xml", HTTP_ACCEPT_LANGUAGE="en", follow=True
)
self.assertRedirects(response, "/en/prefixed.xml", 302)
class URLRedirectWithoutTrailingSlashSettingTests(URLTestCaseBase):
"""
Tests the redirect when the requested URL doesn't end with a slash
(`settings.APPEND_SLASH=False`).
"""
@override_settings(APPEND_SLASH=False)
def test_not_prefixed_redirect(self):
response = self.client.get("/not-prefixed", HTTP_ACCEPT_LANGUAGE="en")
self.assertEqual(response.status_code, 404)
@override_settings(APPEND_SLASH=False)
def test_en_redirect(self):
response = self.client.get(
"/account/register-without-slash", HTTP_ACCEPT_LANGUAGE="en"
)
self.assertRedirects(response, "/en/account/register-without-slash", 302)
response = self.client.get(response.headers["location"])
self.assertEqual(response.status_code, 200)
class URLResponseTests(URLTestCaseBase):
"""Tests if the response has the correct language code."""
def test_not_prefixed_with_prefix(self):
response = self.client.get("/en/not-prefixed/")
self.assertEqual(response.status_code, 404)
def test_en_url(self):
response = self.client.get("/en/account/register/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers["content-language"], "en")
self.assertEqual(response.context["LANGUAGE_CODE"], "en")
def test_nl_url(self):
response = self.client.get("/nl/profiel/registreren/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers["content-language"], "nl")
self.assertEqual(response.context["LANGUAGE_CODE"], "nl")
def test_wrong_en_prefix(self):
response = self.client.get("/en/profiel/registreren/")
self.assertEqual(response.status_code, 404)
def test_wrong_nl_prefix(self):
response = self.client.get("/nl/account/register/")
self.assertEqual(response.status_code, 404)
def test_pt_br_url(self):
response = self.client.get("/pt-br/conta/registre-se/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers["content-language"], "pt-br")
self.assertEqual(response.context["LANGUAGE_CODE"], "pt-br")
def test_en_path(self):
response = self.client.get("/en/account/register-as-path/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers["content-language"], "en")
self.assertEqual(response.context["LANGUAGE_CODE"], "en")
def test_nl_path(self):
response = self.client.get("/nl/profiel/registreren-als-pad/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers["content-language"], "nl")
self.assertEqual(response.context["LANGUAGE_CODE"], "nl")
class URLRedirectWithScriptAliasTests(URLTestCaseBase):
"""
#21579 - LocaleMiddleware should respect the script prefix.
"""
def test_language_prefix_with_script_prefix(self):
prefix = "/script_prefix"
with override_script_prefix(prefix):
response = self.client.get(
"/prefixed/", HTTP_ACCEPT_LANGUAGE="en", SCRIPT_NAME=prefix
)
self.assertRedirects(
response, "%s/en/prefixed/" % prefix, target_status_code=404
)
class URLTagTests(URLTestCaseBase):
"""
Test if the language tag works.
"""
def test_strings_only(self):
t = Template(
"""{% load i18n %}
{% language 'nl' %}{% url 'no-prefix-translated' %}{% endlanguage %}
{% language 'pt-br' %}{% url 'no-prefix-translated' %}{% endlanguage %}"""
)
self.assertEqual(
t.render(Context({})).strip().split(), ["/vertaald/", "/traduzidos/"]
)
def test_context(self):
ctx = Context({"lang1": "nl", "lang2": "pt-br"})
tpl = Template(
"""{% load i18n %}
{% language lang1 %}{% url 'no-prefix-translated' %}{% endlanguage %}
{% language lang2 %}{% url 'no-prefix-translated' %}{% endlanguage %}"""
)
self.assertEqual(
tpl.render(ctx).strip().split(), ["/vertaald/", "/traduzidos/"]
)
def test_args(self):
tpl = Template(
"""
{% load i18n %}
{% language 'nl' %}
{% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %}
{% language 'pt-br' %}
{% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %}
"""
)
self.assertEqual(
tpl.render(Context({})).strip().split(),
["/vertaald/apo/", "/traduzidos/apo/"],
)
def test_kwargs(self):
tpl = Template(
"""
{% load i18n %}
{% language 'nl' %}
{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}
{% language 'pt-br' %}
{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}
"""
)
self.assertEqual(
tpl.render(Context({})).strip().split(),
["/vertaald/apo/", "/traduzidos/apo/"],
)
|
8df16641f09599e96e38375dd15dd97098e3358950a4ca339c0f069c9d4a87c7 | import argparse
import ctypes
import faulthandler
import io
import itertools
import logging
import multiprocessing
import os
import pickle
import random
import sys
import textwrap
import unittest
import warnings
from collections import defaultdict
from contextlib import contextmanager
from importlib import import_module
from io import StringIO
from django.core.management import call_command
from django.db import connections
from django.test import SimpleTestCase, TestCase
from django.test.utils import NullTimeKeeper, TimeKeeper, iter_test_cases
from django.test.utils import setup_databases as _setup_databases
from django.test.utils import setup_test_environment
from django.test.utils import teardown_databases as _teardown_databases
from django.test.utils import teardown_test_environment
from django.utils.crypto import new_hash
from django.utils.datastructures import OrderedSet
from django.utils.deprecation import RemovedInDjango50Warning
try:
import ipdb as pdb
except ImportError:
import pdb
try:
import tblib.pickling_support
except ImportError:
tblib = None
class DebugSQLTextTestResult(unittest.TextTestResult):
def __init__(self, stream, descriptions, verbosity):
self.logger = logging.getLogger("django.db.backends")
self.logger.setLevel(logging.DEBUG)
self.debug_sql_stream = None
super().__init__(stream, descriptions, verbosity)
def startTest(self, test):
self.debug_sql_stream = StringIO()
self.handler = logging.StreamHandler(self.debug_sql_stream)
self.logger.addHandler(self.handler)
super().startTest(test)
def stopTest(self, test):
super().stopTest(test)
self.logger.removeHandler(self.handler)
if self.showAll:
self.debug_sql_stream.seek(0)
self.stream.write(self.debug_sql_stream.read())
self.stream.writeln(self.separator2)
def addError(self, test, err):
super().addError(test, err)
if self.debug_sql_stream is None:
# Error before tests e.g. in setUpTestData().
sql = ""
else:
self.debug_sql_stream.seek(0)
sql = self.debug_sql_stream.read()
self.errors[-1] = self.errors[-1] + (sql,)
def addFailure(self, test, err):
super().addFailure(test, err)
self.debug_sql_stream.seek(0)
self.failures[-1] = self.failures[-1] + (self.debug_sql_stream.read(),)
def addSubTest(self, test, subtest, err):
super().addSubTest(test, subtest, err)
if err is not None:
self.debug_sql_stream.seek(0)
errors = (
self.failures
if issubclass(err[0], test.failureException)
else self.errors
)
errors[-1] = errors[-1] + (self.debug_sql_stream.read(),)
def printErrorList(self, flavour, errors):
for test, err, sql_debug in errors:
self.stream.writeln(self.separator1)
self.stream.writeln("%s: %s" % (flavour, self.getDescription(test)))
self.stream.writeln(self.separator2)
self.stream.writeln(err)
self.stream.writeln(self.separator2)
self.stream.writeln(sql_debug)
class PDBDebugResult(unittest.TextTestResult):
"""
Custom result class that triggers a PDB session when an error or failure
occurs.
"""
def addError(self, test, err):
super().addError(test, err)
self.debug(err)
def addFailure(self, test, err):
super().addFailure(test, err)
self.debug(err)
def addSubTest(self, test, subtest, err):
if err is not None:
self.debug(err)
super().addSubTest(test, subtest, err)
def debug(self, error):
self._restoreStdout()
self.buffer = False
exc_type, exc_value, traceback = error
print("\nOpening PDB: %r" % exc_value)
pdb.post_mortem(traceback)
class DummyList:
"""
Dummy list class for faking storage of results in unittest.TestResult.
"""
__slots__ = ()
def append(self, item):
pass
class RemoteTestResult(unittest.TestResult):
"""
Extend unittest.TestResult to record events in the child processes so they
can be replayed in the parent process. Events include things like which
tests succeeded or failed.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Fake storage of results to reduce memory usage. These are used by the
# unittest default methods, but here 'events' is used instead.
dummy_list = DummyList()
self.failures = dummy_list
self.errors = dummy_list
self.skipped = dummy_list
self.expectedFailures = dummy_list
self.unexpectedSuccesses = dummy_list
if tblib is not None:
tblib.pickling_support.install()
self.events = []
def __getstate__(self):
# Make this class picklable by removing the file-like buffer
# attributes. This is possible since they aren't used after unpickling
# after being sent to ParallelTestSuite.
state = self.__dict__.copy()
state.pop("_stdout_buffer", None)
state.pop("_stderr_buffer", None)
state.pop("_original_stdout", None)
state.pop("_original_stderr", None)
return state
@property
def test_index(self):
return self.testsRun - 1
def _confirm_picklable(self, obj):
"""
Confirm that obj can be pickled and unpickled as multiprocessing will
need to pickle the exception in the child process and unpickle it in
the parent process. Let the exception rise, if not.
"""
pickle.loads(pickle.dumps(obj))
def _print_unpicklable_subtest(self, test, subtest, pickle_exc):
print(
"""
Subtest failed:
test: {}
subtest: {}
Unfortunately, the subtest that failed cannot be pickled, so the parallel
test runner cannot handle it cleanly. Here is the pickling error:
> {}
You should re-run this test with --parallel=1 to reproduce the failure
with a cleaner failure message.
""".format(
test, subtest, pickle_exc
)
)
def check_picklable(self, test, err):
# Ensure that sys.exc_info() tuples are picklable. This displays a
# clear multiprocessing.pool.RemoteTraceback generated in the child
# process instead of a multiprocessing.pool.MaybeEncodingError, making
# the root cause easier to figure out for users who aren't familiar
# with the multiprocessing module. Since we're in a forked process,
# our best chance to communicate with them is to print to stdout.
try:
self._confirm_picklable(err)
except Exception as exc:
original_exc_txt = repr(err[1])
original_exc_txt = textwrap.fill(
original_exc_txt, 75, initial_indent=" ", subsequent_indent=" "
)
pickle_exc_txt = repr(exc)
pickle_exc_txt = textwrap.fill(
pickle_exc_txt, 75, initial_indent=" ", subsequent_indent=" "
)
if tblib is None:
print(
"""
{} failed:
{}
Unfortunately, tracebacks cannot be pickled, making it impossible for the
parallel test runner to handle this exception cleanly.
In order to see the traceback, you should install tblib:
python -m pip install tblib
""".format(
test, original_exc_txt
)
)
else:
print(
"""
{} failed:
{}
Unfortunately, the exception it raised cannot be pickled, making it impossible
for the parallel test runner to handle it cleanly.
Here's the error encountered while trying to pickle the exception:
{}
You should re-run this test with the --parallel=1 option to reproduce the
failure and get a correct traceback.
""".format(
test, original_exc_txt, pickle_exc_txt
)
)
raise
def check_subtest_picklable(self, test, subtest):
try:
self._confirm_picklable(subtest)
except Exception as exc:
self._print_unpicklable_subtest(test, subtest, exc)
raise
def startTestRun(self):
super().startTestRun()
self.events.append(("startTestRun",))
def stopTestRun(self):
super().stopTestRun()
self.events.append(("stopTestRun",))
def startTest(self, test):
super().startTest(test)
self.events.append(("startTest", self.test_index))
def stopTest(self, test):
super().stopTest(test)
self.events.append(("stopTest", self.test_index))
def addError(self, test, err):
self.check_picklable(test, err)
self.events.append(("addError", self.test_index, err))
super().addError(test, err)
def addFailure(self, test, err):
self.check_picklable(test, err)
self.events.append(("addFailure", self.test_index, err))
super().addFailure(test, err)
def addSubTest(self, test, subtest, err):
# Follow Python's implementation of unittest.TestResult.addSubTest() by
# not doing anything when a subtest is successful.
if err is not None:
# Call check_picklable() before check_subtest_picklable() since
# check_picklable() performs the tblib check.
self.check_picklable(test, err)
self.check_subtest_picklable(test, subtest)
self.events.append(("addSubTest", self.test_index, subtest, err))
super().addSubTest(test, subtest, err)
def addSuccess(self, test):
self.events.append(("addSuccess", self.test_index))
super().addSuccess(test)
def addSkip(self, test, reason):
self.events.append(("addSkip", self.test_index, reason))
super().addSkip(test, reason)
def addExpectedFailure(self, test, err):
# If tblib isn't installed, pickling the traceback will always fail.
# However we don't want tblib to be required for running the tests
# when they pass or fail as expected. Drop the traceback when an
# expected failure occurs.
if tblib is None:
err = err[0], err[1], None
self.check_picklable(test, err)
self.events.append(("addExpectedFailure", self.test_index, err))
super().addExpectedFailure(test, err)
def addUnexpectedSuccess(self, test):
self.events.append(("addUnexpectedSuccess", self.test_index))
super().addUnexpectedSuccess(test)
def wasSuccessful(self):
"""Tells whether or not this result was a success."""
failure_types = {"addError", "addFailure", "addSubTest", "addUnexpectedSuccess"}
return all(e[0] not in failure_types for e in self.events)
def _exc_info_to_string(self, err, test):
# Make this method no-op. It only powers the default unittest behavior
# for recording errors, but this class pickles errors into 'events'
# instead.
return ""
class RemoteTestRunner:
"""
Run tests and record everything but don't display anything.
The implementation matches the unpythonic coding style of unittest2.
"""
resultclass = RemoteTestResult
def __init__(self, failfast=False, resultclass=None, buffer=False):
self.failfast = failfast
self.buffer = buffer
if resultclass is not None:
self.resultclass = resultclass
def run(self, test):
result = self.resultclass()
unittest.registerResult(result)
result.failfast = self.failfast
result.buffer = self.buffer
test(result)
return result
def get_max_test_processes():
"""
The maximum number of test processes when using the --parallel option.
"""
# The current implementation of the parallel test runner requires
# multiprocessing to start subprocesses with fork() or spawn().
if multiprocessing.get_start_method() not in {"fork", "spawn"}:
return 1
try:
return int(os.environ["DJANGO_TEST_PROCESSES"])
except KeyError:
return multiprocessing.cpu_count()
def parallel_type(value):
"""Parse value passed to the --parallel option."""
if value == "auto":
return value
try:
return int(value)
except ValueError:
raise argparse.ArgumentTypeError(
f"{value!r} is not an integer or the string 'auto'"
)
_worker_id = 0
def _init_worker(
counter,
initial_settings=None,
serialized_contents=None,
process_setup=None,
process_setup_args=None,
):
"""
Switch to databases dedicated to this worker.
This helper lives at module-level because of the multiprocessing module's
requirements.
"""
global _worker_id
with counter.get_lock():
counter.value += 1
_worker_id = counter.value
start_method = multiprocessing.get_start_method()
if start_method == "spawn":
if process_setup and callable(process_setup):
if process_setup_args is None:
process_setup_args = ()
process_setup(*process_setup_args)
setup_test_environment()
for alias in connections:
connection = connections[alias]
if start_method == "spawn":
# Restore initial settings in spawned processes.
connection.settings_dict.update(initial_settings[alias])
if value := serialized_contents.get(alias):
connection._test_serialized_contents = value
connection.creation.setup_worker_connection(_worker_id)
def _run_subsuite(args):
"""
Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult.
This helper lives at module-level and its arguments are wrapped in a tuple
because of the multiprocessing module's requirements.
"""
runner_class, subsuite_index, subsuite, failfast, buffer = args
runner = runner_class(failfast=failfast, buffer=buffer)
result = runner.run(subsuite)
return subsuite_index, result.events
def _process_setup_stub(*args):
"""Stub method to simplify run() implementation."""
pass
class ParallelTestSuite(unittest.TestSuite):
"""
Run a series of tests in parallel in several processes.
While the unittest module's documentation implies that orchestrating the
execution of tests is the responsibility of the test runner, in practice,
it appears that TestRunner classes are more concerned with formatting and
displaying test results.
Since there are fewer use cases for customizing TestSuite than TestRunner,
implementing parallelization at the level of the TestSuite improves
interoperability with existing custom test runners. A single instance of a
test runner can still collect results from all tests without being aware
that they have been run in parallel.
"""
# In case someone wants to modify these in a subclass.
init_worker = _init_worker
process_setup = _process_setup_stub
process_setup_args = ()
run_subsuite = _run_subsuite
runner_class = RemoteTestRunner
def __init__(self, subsuites, processes, failfast=False, buffer=False):
self.subsuites = subsuites
self.processes = processes
self.failfast = failfast
self.buffer = buffer
self.initial_settings = None
self.serialized_contents = None
super().__init__()
def run(self, result):
"""
Distribute test cases across workers.
Return an identifier of each test case with its result in order to use
imap_unordered to show results as soon as they're available.
To minimize pickling errors when getting results from workers:
- pass back numeric indexes in self.subsuites instead of tests
- make tracebacks picklable with tblib, if available
Even with tblib, errors may still occur for dynamically created
exception classes which cannot be unpickled.
"""
self.initialize_suite()
counter = multiprocessing.Value(ctypes.c_int, 0)
pool = multiprocessing.Pool(
processes=self.processes,
initializer=self.init_worker.__func__,
initargs=[
counter,
self.initial_settings,
self.serialized_contents,
self.process_setup.__func__,
self.process_setup_args,
],
)
args = [
(self.runner_class, index, subsuite, self.failfast, self.buffer)
for index, subsuite in enumerate(self.subsuites)
]
test_results = pool.imap_unordered(self.run_subsuite.__func__, args)
while True:
if result.shouldStop:
pool.terminate()
break
try:
subsuite_index, events = test_results.next(timeout=0.1)
except multiprocessing.TimeoutError:
continue
except StopIteration:
pool.close()
break
tests = list(self.subsuites[subsuite_index])
for event in events:
event_name = event[0]
handler = getattr(result, event_name, None)
if handler is None:
continue
test = tests[event[1]]
args = event[2:]
handler(test, *args)
pool.join()
return result
def __iter__(self):
return iter(self.subsuites)
def initialize_suite(self):
if multiprocessing.get_start_method() == "spawn":
self.initial_settings = {
alias: connections[alias].settings_dict for alias in connections
}
self.serialized_contents = {
alias: connections[alias]._test_serialized_contents
for alias in connections
if alias in self.serialized_aliases
}
class Shuffler:
"""
This class implements shuffling with a special consistency property.
Consistency means that, for a given seed and key function, if two sets of
items are shuffled, the resulting order will agree on the intersection of
the two sets. For example, if items are removed from an original set, the
shuffled order for the new set will be the shuffled order of the original
set restricted to the smaller set.
"""
# This doesn't need to be cryptographically strong, so use what's fastest.
hash_algorithm = "md5"
@classmethod
def _hash_text(cls, text):
h = new_hash(cls.hash_algorithm, usedforsecurity=False)
h.update(text.encode("utf-8"))
return h.hexdigest()
def __init__(self, seed=None):
if seed is None:
# Limit seeds to 10 digits for simpler output.
seed = random.randint(0, 10**10 - 1)
seed_source = "generated"
else:
seed_source = "given"
self.seed = seed
self.seed_source = seed_source
@property
def seed_display(self):
return f"{self.seed!r} ({self.seed_source})"
def _hash_item(self, item, key):
text = "{}{}".format(self.seed, key(item))
return self._hash_text(text)
def shuffle(self, items, key):
"""
Return a new list of the items in a shuffled order.
The `key` is a function that accepts an item in `items` and returns
a string unique for that item that can be viewed as a string id. The
order of the return value is deterministic. It depends on the seed
and key function but not on the original order.
"""
hashes = {}
for item in items:
hashed = self._hash_item(item, key)
if hashed in hashes:
msg = "item {!r} has same hash {!r} as item {!r}".format(
item,
hashed,
hashes[hashed],
)
raise RuntimeError(msg)
hashes[hashed] = item
return [hashes[hashed] for hashed in sorted(hashes)]
class DiscoverRunner:
"""A Django test runner that uses unittest2 test discovery."""
test_suite = unittest.TestSuite
parallel_test_suite = ParallelTestSuite
test_runner = unittest.TextTestRunner
test_loader = unittest.defaultTestLoader
reorder_by = (TestCase, SimpleTestCase)
def __init__(
self,
pattern=None,
top_level=None,
verbosity=1,
interactive=True,
failfast=False,
keepdb=False,
reverse=False,
debug_mode=False,
debug_sql=False,
parallel=0,
tags=None,
exclude_tags=None,
test_name_patterns=None,
pdb=False,
buffer=False,
enable_faulthandler=True,
timing=False,
shuffle=False,
logger=None,
**kwargs,
):
self.pattern = pattern
self.top_level = top_level
self.verbosity = verbosity
self.interactive = interactive
self.failfast = failfast
self.keepdb = keepdb
self.reverse = reverse
self.debug_mode = debug_mode
self.debug_sql = debug_sql
self.parallel = parallel
self.tags = set(tags or [])
self.exclude_tags = set(exclude_tags or [])
if not faulthandler.is_enabled() and enable_faulthandler:
try:
faulthandler.enable(file=sys.stderr.fileno())
except (AttributeError, io.UnsupportedOperation):
faulthandler.enable(file=sys.__stderr__.fileno())
self.pdb = pdb
if self.pdb and self.parallel > 1:
raise ValueError(
"You cannot use --pdb with parallel tests; pass --parallel=1 to use it."
)
self.buffer = buffer
self.test_name_patterns = None
self.time_keeper = TimeKeeper() if timing else NullTimeKeeper()
if test_name_patterns:
# unittest does not export the _convert_select_pattern function
# that converts command-line arguments to patterns.
self.test_name_patterns = {
pattern if "*" in pattern else "*%s*" % pattern
for pattern in test_name_patterns
}
self.shuffle = shuffle
self._shuffler = None
self.logger = logger
@classmethod
def add_arguments(cls, parser):
parser.add_argument(
"-t",
"--top-level-directory",
dest="top_level",
help="Top level of project for unittest discovery.",
)
parser.add_argument(
"-p",
"--pattern",
default="test*.py",
help="The test matching pattern. Defaults to test*.py.",
)
parser.add_argument(
"--keepdb", action="store_true", help="Preserves the test DB between runs."
)
parser.add_argument(
"--shuffle",
nargs="?",
default=False,
type=int,
metavar="SEED",
help="Shuffles test case order.",
)
parser.add_argument(
"-r",
"--reverse",
action="store_true",
help="Reverses test case order.",
)
parser.add_argument(
"--debug-mode",
action="store_true",
help="Sets settings.DEBUG to True.",
)
parser.add_argument(
"-d",
"--debug-sql",
action="store_true",
help="Prints logged SQL queries on failure.",
)
parser.add_argument(
"--parallel",
nargs="?",
const="auto",
default=0,
type=parallel_type,
metavar="N",
help=(
"Run tests using up to N parallel processes. Use the value "
'"auto" to run one test process for each processor core.'
),
)
parser.add_argument(
"--tag",
action="append",
dest="tags",
help="Run only tests with the specified tag. Can be used multiple times.",
)
parser.add_argument(
"--exclude-tag",
action="append",
dest="exclude_tags",
help="Do not run tests with the specified tag. Can be used multiple times.",
)
parser.add_argument(
"--pdb",
action="store_true",
help="Runs a debugger (pdb, or ipdb if installed) on error or failure.",
)
parser.add_argument(
"-b",
"--buffer",
action="store_true",
help="Discard output from passing tests.",
)
parser.add_argument(
"--no-faulthandler",
action="store_false",
dest="enable_faulthandler",
help="Disables the Python faulthandler module during tests.",
)
parser.add_argument(
"--timing",
action="store_true",
help=("Output timings, including database set up and total run time."),
)
parser.add_argument(
"-k",
action="append",
dest="test_name_patterns",
help=(
"Only run test methods and classes that match the pattern "
"or substring. Can be used multiple times. Same as "
"unittest -k option."
),
)
@property
def shuffle_seed(self):
if self._shuffler is None:
return None
return self._shuffler.seed
def log(self, msg, level=None):
"""
Log the message at the given logging level (the default is INFO).
If a logger isn't set, the message is instead printed to the console,
respecting the configured verbosity. A verbosity of 0 prints no output,
a verbosity of 1 prints INFO and above, and a verbosity of 2 or higher
prints all levels.
"""
if level is None:
level = logging.INFO
if self.logger is None:
if self.verbosity <= 0 or (self.verbosity == 1 and level < logging.INFO):
return
print(msg)
else:
self.logger.log(level, msg)
def setup_test_environment(self, **kwargs):
setup_test_environment(debug=self.debug_mode)
unittest.installHandler()
def setup_shuffler(self):
if self.shuffle is False:
return
shuffler = Shuffler(seed=self.shuffle)
self.log(f"Using shuffle seed: {shuffler.seed_display}")
self._shuffler = shuffler
@contextmanager
def load_with_patterns(self):
original_test_name_patterns = self.test_loader.testNamePatterns
self.test_loader.testNamePatterns = self.test_name_patterns
try:
yield
finally:
# Restore the original patterns.
self.test_loader.testNamePatterns = original_test_name_patterns
def load_tests_for_label(self, label, discover_kwargs):
label_as_path = os.path.abspath(label)
tests = None
# If a module, or "module.ClassName[.method_name]", just run those.
if not os.path.exists(label_as_path):
with self.load_with_patterns():
tests = self.test_loader.loadTestsFromName(label)
if tests.countTestCases():
return tests
# Try discovery if "label" is a package or directory.
is_importable, is_package = try_importing(label)
if is_importable:
if not is_package:
return tests
elif not os.path.isdir(label_as_path):
if os.path.exists(label_as_path):
assert tests is None
raise RuntimeError(
f"One of the test labels is a path to a file: {label!r}, "
f"which is not supported. Use a dotted module name or "
f"path to a directory instead."
)
return tests
kwargs = discover_kwargs.copy()
if os.path.isdir(label_as_path) and not self.top_level:
kwargs["top_level_dir"] = find_top_level(label_as_path)
with self.load_with_patterns():
tests = self.test_loader.discover(start_dir=label, **kwargs)
# Make unittest forget the top-level dir it calculated from this run,
# to support running tests from two different top-levels.
self.test_loader._top_level_dir = None
return tests
def build_suite(self, test_labels=None, extra_tests=None, **kwargs):
if extra_tests is not None:
warnings.warn(
"The extra_tests argument is deprecated.",
RemovedInDjango50Warning,
stacklevel=2,
)
test_labels = test_labels or ["."]
extra_tests = extra_tests or []
discover_kwargs = {}
if self.pattern is not None:
discover_kwargs["pattern"] = self.pattern
if self.top_level is not None:
discover_kwargs["top_level_dir"] = self.top_level
self.setup_shuffler()
all_tests = []
for label in test_labels:
tests = self.load_tests_for_label(label, discover_kwargs)
all_tests.extend(iter_test_cases(tests))
all_tests.extend(iter_test_cases(extra_tests))
if self.tags or self.exclude_tags:
if self.tags:
self.log(
"Including test tag(s): %s." % ", ".join(sorted(self.tags)),
level=logging.DEBUG,
)
if self.exclude_tags:
self.log(
"Excluding test tag(s): %s." % ", ".join(sorted(self.exclude_tags)),
level=logging.DEBUG,
)
all_tests = filter_tests_by_tags(all_tests, self.tags, self.exclude_tags)
# Put the failures detected at load time first for quicker feedback.
# _FailedTest objects include things like test modules that couldn't be
# found or that couldn't be loaded due to syntax errors.
test_types = (unittest.loader._FailedTest, *self.reorder_by)
all_tests = list(
reorder_tests(
all_tests,
test_types,
shuffler=self._shuffler,
reverse=self.reverse,
)
)
self.log("Found %d test(s)." % len(all_tests))
suite = self.test_suite(all_tests)
if self.parallel > 1:
subsuites = partition_suite_by_case(suite)
# Since tests are distributed across processes on a per-TestCase
# basis, there's no need for more processes than TestCases.
processes = min(self.parallel, len(subsuites))
# Update also "parallel" because it's used to determine the number
# of test databases.
self.parallel = processes
if processes > 1:
suite = self.parallel_test_suite(
subsuites,
processes,
self.failfast,
self.buffer,
)
return suite
def setup_databases(self, **kwargs):
return _setup_databases(
self.verbosity,
self.interactive,
time_keeper=self.time_keeper,
keepdb=self.keepdb,
debug_sql=self.debug_sql,
parallel=self.parallel,
**kwargs,
)
def get_resultclass(self):
if self.debug_sql:
return DebugSQLTextTestResult
elif self.pdb:
return PDBDebugResult
def get_test_runner_kwargs(self):
return {
"failfast": self.failfast,
"resultclass": self.get_resultclass(),
"verbosity": self.verbosity,
"buffer": self.buffer,
}
def run_checks(self, databases):
# Checks are run after database creation since some checks require
# database access.
call_command("check", verbosity=self.verbosity, databases=databases)
def run_suite(self, suite, **kwargs):
kwargs = self.get_test_runner_kwargs()
runner = self.test_runner(**kwargs)
try:
return runner.run(suite)
finally:
if self._shuffler is not None:
seed_display = self._shuffler.seed_display
self.log(f"Used shuffle seed: {seed_display}")
def teardown_databases(self, old_config, **kwargs):
"""Destroy all the non-mirror databases."""
_teardown_databases(
old_config,
verbosity=self.verbosity,
parallel=self.parallel,
keepdb=self.keepdb,
)
def teardown_test_environment(self, **kwargs):
unittest.removeHandler()
teardown_test_environment()
def suite_result(self, suite, result, **kwargs):
return (
len(result.failures) + len(result.errors) + len(result.unexpectedSuccesses)
)
def _get_databases(self, suite):
databases = {}
for test in iter_test_cases(suite):
test_databases = getattr(test, "databases", None)
if test_databases == "__all__":
test_databases = connections
if test_databases:
serialized_rollback = getattr(test, "serialized_rollback", False)
databases.update(
(alias, serialized_rollback or databases.get(alias, False))
for alias in test_databases
)
return databases
def get_databases(self, suite):
databases = self._get_databases(suite)
unused_databases = [alias for alias in connections if alias not in databases]
if unused_databases:
self.log(
"Skipping setup of unused database(s): %s."
% ", ".join(sorted(unused_databases)),
level=logging.DEBUG,
)
return databases
def run_tests(self, test_labels, extra_tests=None, **kwargs):
"""
Run the unit tests for all the test labels in the provided list.
Test labels should be dotted Python paths to test modules, test
classes, or test methods.
Return the number of tests that failed.
"""
if extra_tests is not None:
warnings.warn(
"The extra_tests argument is deprecated.",
RemovedInDjango50Warning,
stacklevel=2,
)
self.setup_test_environment()
suite = self.build_suite(test_labels, extra_tests)
databases = self.get_databases(suite)
suite.serialized_aliases = set(
alias for alias, serialize in databases.items() if serialize
)
with self.time_keeper.timed("Total database setup"):
old_config = self.setup_databases(
aliases=databases,
serialized_aliases=suite.serialized_aliases,
)
run_failed = False
try:
self.run_checks(databases)
result = self.run_suite(suite)
except Exception:
run_failed = True
raise
finally:
try:
with self.time_keeper.timed("Total database teardown"):
self.teardown_databases(old_config)
self.teardown_test_environment()
except Exception:
# Silence teardown exceptions if an exception was raised during
# runs to avoid shadowing it.
if not run_failed:
raise
self.time_keeper.print_results()
return self.suite_result(suite, result)
def try_importing(label):
"""
Try importing a test label, and return (is_importable, is_package).
Relative labels like "." and ".." are seen as directories.
"""
try:
mod = import_module(label)
except (ImportError, TypeError):
return (False, False)
return (True, hasattr(mod, "__path__"))
def find_top_level(top_level):
# Try to be a bit smarter than unittest about finding the default top-level
# for a given directory path, to avoid breaking relative imports.
# (Unittest's default is to set top-level equal to the path, which means
# relative imports will result in "Attempted relative import in
# non-package.").
# We'd be happy to skip this and require dotted module paths (which don't
# cause this problem) instead of file paths (which do), but in the case of
# a directory in the cwd, which would be equally valid if considered as a
# top-level module or as a directory path, unittest unfortunately prefers
# the latter.
while True:
init_py = os.path.join(top_level, "__init__.py")
if not os.path.exists(init_py):
break
try_next = os.path.dirname(top_level)
if try_next == top_level:
# __init__.py all the way down? give up.
break
top_level = try_next
return top_level
def _class_shuffle_key(cls):
return f"{cls.__module__}.{cls.__qualname__}"
def shuffle_tests(tests, shuffler):
"""
Return an iterator over the given tests in a shuffled order, keeping tests
next to other tests of their class.
`tests` should be an iterable of tests.
"""
tests_by_type = {}
for _, class_tests in itertools.groupby(tests, type):
class_tests = list(class_tests)
test_type = type(class_tests[0])
class_tests = shuffler.shuffle(class_tests, key=lambda test: test.id())
tests_by_type[test_type] = class_tests
classes = shuffler.shuffle(tests_by_type, key=_class_shuffle_key)
return itertools.chain(*(tests_by_type[cls] for cls in classes))
def reorder_test_bin(tests, shuffler=None, reverse=False):
"""
Return an iterator that reorders the given tests, keeping tests next to
other tests of their class.
`tests` should be an iterable of tests that supports reversed().
"""
if shuffler is None:
if reverse:
return reversed(tests)
# The function must return an iterator.
return iter(tests)
tests = shuffle_tests(tests, shuffler)
if not reverse:
return tests
# Arguments to reversed() must be reversible.
return reversed(list(tests))
def reorder_tests(tests, classes, reverse=False, shuffler=None):
"""
Reorder an iterable of tests, grouping by the given TestCase classes.
This function also removes any duplicates and reorders so that tests of the
same type are consecutive.
The result is returned as an iterator. `classes` is a sequence of types.
Tests that are instances of `classes[0]` are grouped first, followed by
instances of `classes[1]`, etc. Tests that are not instances of any of the
classes are grouped last.
If `reverse` is True, the tests within each `classes` group are reversed,
but without reversing the order of `classes` itself.
The `shuffler` argument is an optional instance of this module's `Shuffler`
class. If provided, tests will be shuffled within each `classes` group, but
keeping tests with other tests of their TestCase class. Reversing is
applied after shuffling to allow reversing the same random order.
"""
# Each bin maps TestCase class to OrderedSet of tests. This permits tests
# to be grouped by TestCase class even if provided non-consecutively.
bins = [defaultdict(OrderedSet) for i in range(len(classes) + 1)]
*class_bins, last_bin = bins
for test in tests:
for test_bin, test_class in zip(class_bins, classes):
if isinstance(test, test_class):
break
else:
test_bin = last_bin
test_bin[type(test)].add(test)
for test_bin in bins:
# Call list() since reorder_test_bin()'s input must support reversed().
tests = list(itertools.chain.from_iterable(test_bin.values()))
yield from reorder_test_bin(tests, shuffler=shuffler, reverse=reverse)
def partition_suite_by_case(suite):
"""Partition a test suite by test case, preserving the order of tests."""
suite_class = type(suite)
all_tests = iter_test_cases(suite)
return [suite_class(tests) for _, tests in itertools.groupby(all_tests, type)]
def test_match_tags(test, tags, exclude_tags):
if isinstance(test, unittest.loader._FailedTest):
# Tests that couldn't load always match to prevent tests from falsely
# passing due e.g. to syntax errors.
return True
test_tags = set(getattr(test, "tags", []))
test_fn_name = getattr(test, "_testMethodName", str(test))
if hasattr(test, test_fn_name):
test_fn = getattr(test, test_fn_name)
test_fn_tags = list(getattr(test_fn, "tags", []))
test_tags = test_tags.union(test_fn_tags)
if tags and test_tags.isdisjoint(tags):
return False
return test_tags.isdisjoint(exclude_tags)
def filter_tests_by_tags(tests, tags, exclude_tags):
"""Return the matching tests as an iterator."""
return (test for test in tests if test_match_tags(test, tags, exclude_tags))
|
25b05da5244b67964d1f09ccf83f39c82a4b79af6935bdde510a57add70ff648 | from django.core.exceptions import ValidationError
from django.forms import Form
from django.forms.fields import BooleanField, IntegerField
from django.forms.renderers import get_default_renderer
from django.forms.utils import ErrorList, RenderableFormMixin
from django.forms.widgets import CheckboxInput, HiddenInput, NumberInput
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from django.utils.translation import ngettext_lazy
__all__ = ("BaseFormSet", "formset_factory", "all_valid")
# special field names
TOTAL_FORM_COUNT = "TOTAL_FORMS"
INITIAL_FORM_COUNT = "INITIAL_FORMS"
MIN_NUM_FORM_COUNT = "MIN_NUM_FORMS"
MAX_NUM_FORM_COUNT = "MAX_NUM_FORMS"
ORDERING_FIELD_NAME = "ORDER"
DELETION_FIELD_NAME = "DELETE"
# default minimum number of forms in a formset
DEFAULT_MIN_NUM = 0
# default maximum number of forms in a formset, to prevent memory exhaustion
DEFAULT_MAX_NUM = 1000
class ManagementForm(Form):
"""
Keep track of how many form instances are displayed on the page. If adding
new forms via JavaScript, you should increment the count field of this form
as well.
"""
template_name = "django/forms/div.html" # RemovedInDjango50Warning.
TOTAL_FORMS = IntegerField(widget=HiddenInput)
INITIAL_FORMS = IntegerField(widget=HiddenInput)
# MIN_NUM_FORM_COUNT and MAX_NUM_FORM_COUNT are output with the rest of the
# management form, but only for the convenience of client-side code. The
# POST value of them returned from the client is not checked.
MIN_NUM_FORMS = IntegerField(required=False, widget=HiddenInput)
MAX_NUM_FORMS = IntegerField(required=False, widget=HiddenInput)
def clean(self):
cleaned_data = super().clean()
# When the management form is invalid, we don't know how many forms
# were submitted.
cleaned_data.setdefault(TOTAL_FORM_COUNT, 0)
cleaned_data.setdefault(INITIAL_FORM_COUNT, 0)
return cleaned_data
class BaseFormSet(RenderableFormMixin):
"""
A collection of instances of the same Form class.
"""
deletion_widget = CheckboxInput
ordering_widget = NumberInput
default_error_messages = {
"missing_management_form": _(
"ManagementForm data is missing or has been tampered with. Missing fields: "
"%(field_names)s. You may need to file a bug report if the issue persists."
),
"too_many_forms": ngettext_lazy(
"Please submit at most %(num)d form.",
"Please submit at most %(num)d forms.",
"num",
),
"too_few_forms": ngettext_lazy(
"Please submit at least %(num)d form.",
"Please submit at least %(num)d forms.",
"num",
),
}
template_name_div = "django/forms/formsets/div.html"
template_name_p = "django/forms/formsets/p.html"
template_name_table = "django/forms/formsets/table.html"
template_name_ul = "django/forms/formsets/ul.html"
def __init__(
self,
data=None,
files=None,
auto_id="id_%s",
prefix=None,
initial=None,
error_class=ErrorList,
form_kwargs=None,
error_messages=None,
):
self.is_bound = data is not None or files is not None
self.prefix = prefix or self.get_default_prefix()
self.auto_id = auto_id
self.data = data or {}
self.files = files or {}
self.initial = initial
self.form_kwargs = form_kwargs or {}
self.error_class = error_class
self._errors = None
self._non_form_errors = None
messages = {}
for cls in reversed(type(self).__mro__):
messages.update(getattr(cls, "default_error_messages", {}))
if error_messages is not None:
messages.update(error_messages)
self.error_messages = messages
def __iter__(self):
"""Yield the forms in the order they should be rendered."""
return iter(self.forms)
def __getitem__(self, index):
"""Return the form at the given index, based on the rendering order."""
return self.forms[index]
def __len__(self):
return len(self.forms)
def __bool__(self):
"""
Return True since all formsets have a management form which is not
included in the length.
"""
return True
def __repr__(self):
if self._errors is None:
is_valid = "Unknown"
else:
is_valid = (
self.is_bound
and not self._non_form_errors
and not any(form_errors for form_errors in self._errors)
)
return "<%s: bound=%s valid=%s total_forms=%s>" % (
self.__class__.__qualname__,
self.is_bound,
is_valid,
self.total_form_count(),
)
@cached_property
def management_form(self):
"""Return the ManagementForm instance for this FormSet."""
if self.is_bound:
form = ManagementForm(
self.data,
auto_id=self.auto_id,
prefix=self.prefix,
renderer=self.renderer,
)
form.full_clean()
else:
form = ManagementForm(
auto_id=self.auto_id,
prefix=self.prefix,
initial={
TOTAL_FORM_COUNT: self.total_form_count(),
INITIAL_FORM_COUNT: self.initial_form_count(),
MIN_NUM_FORM_COUNT: self.min_num,
MAX_NUM_FORM_COUNT: self.max_num,
},
renderer=self.renderer,
)
return form
def total_form_count(self):
"""Return the total number of forms in this FormSet."""
if self.is_bound:
# return absolute_max if it is lower than the actual total form
# count in the data; this is DoS protection to prevent clients
# from forcing the server to instantiate arbitrary numbers of
# forms
return min(
self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max
)
else:
initial_forms = self.initial_form_count()
total_forms = max(initial_forms, self.min_num) + self.extra
# Allow all existing related objects/inlines to be displayed,
# but don't allow extra beyond max_num.
if initial_forms > self.max_num >= 0:
total_forms = initial_forms
elif total_forms > self.max_num >= 0:
total_forms = self.max_num
return total_forms
def initial_form_count(self):
"""Return the number of forms that are required in this FormSet."""
if self.is_bound:
return self.management_form.cleaned_data[INITIAL_FORM_COUNT]
else:
# Use the length of the initial data if it's there, 0 otherwise.
initial_forms = len(self.initial) if self.initial else 0
return initial_forms
@cached_property
def forms(self):
"""Instantiate forms at first property access."""
# DoS protection is included in total_form_count()
return [
self._construct_form(i, **self.get_form_kwargs(i))
for i in range(self.total_form_count())
]
def get_form_kwargs(self, index):
"""
Return additional keyword arguments for each individual formset form.
index will be None if the form being constructed is a new empty
form.
"""
return self.form_kwargs.copy()
def _construct_form(self, i, **kwargs):
"""Instantiate and return the i-th form instance in a formset."""
defaults = {
"auto_id": self.auto_id,
"prefix": self.add_prefix(i),
"error_class": self.error_class,
# Don't render the HTML 'required' attribute as it may cause
# incorrect validation for extra, optional, and deleted
# forms in the formset.
"use_required_attribute": False,
"renderer": self.renderer,
}
if self.is_bound:
defaults["data"] = self.data
defaults["files"] = self.files
if self.initial and "initial" not in kwargs:
try:
defaults["initial"] = self.initial[i]
except IndexError:
pass
# Allow extra forms to be empty, unless they're part of
# the minimum forms.
if i >= self.initial_form_count() and i >= self.min_num:
defaults["empty_permitted"] = True
defaults.update(kwargs)
form = self.form(**defaults)
self.add_fields(form, i)
return form
@property
def initial_forms(self):
"""Return a list of all the initial forms in this formset."""
return self.forms[: self.initial_form_count()]
@property
def extra_forms(self):
"""Return a list of all the extra forms in this formset."""
return self.forms[self.initial_form_count() :]
@property
def empty_form(self):
form = self.form(
auto_id=self.auto_id,
prefix=self.add_prefix("__prefix__"),
empty_permitted=True,
use_required_attribute=False,
**self.get_form_kwargs(None),
renderer=self.renderer,
)
self.add_fields(form, None)
return form
@property
def cleaned_data(self):
"""
Return a list of form.cleaned_data dicts for every form in self.forms.
"""
if not self.is_valid():
raise AttributeError(
"'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__
)
return [form.cleaned_data for form in self.forms]
@property
def deleted_forms(self):
"""Return a list of forms that have been marked for deletion."""
if not self.is_valid() or not self.can_delete:
return []
# construct _deleted_form_indexes which is just a list of form indexes
# that have had their deletion widget set to True
if not hasattr(self, "_deleted_form_indexes"):
self._deleted_form_indexes = []
for i, form in enumerate(self.forms):
# if this is an extra form and hasn't changed, don't consider it
if i >= self.initial_form_count() and not form.has_changed():
continue
if self._should_delete_form(form):
self._deleted_form_indexes.append(i)
return [self.forms[i] for i in self._deleted_form_indexes]
@property
def ordered_forms(self):
"""
Return a list of form in the order specified by the incoming data.
Raise an AttributeError if ordering is not allowed.
"""
if not self.is_valid() or not self.can_order:
raise AttributeError(
"'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__
)
# Construct _ordering, which is a list of (form_index, order_field_value)
# tuples. After constructing this list, we'll sort it by order_field_value
# so we have a way to get to the form indexes in the order specified
# by the form data.
if not hasattr(self, "_ordering"):
self._ordering = []
for i, form in enumerate(self.forms):
# if this is an extra form and hasn't changed, don't consider it
if i >= self.initial_form_count() and not form.has_changed():
continue
# don't add data marked for deletion to self.ordered_data
if self.can_delete and self._should_delete_form(form):
continue
self._ordering.append((i, form.cleaned_data[ORDERING_FIELD_NAME]))
# After we're done populating self._ordering, sort it.
# A sort function to order things numerically ascending, but
# None should be sorted below anything else. Allowing None as
# a comparison value makes it so we can leave ordering fields
# blank.
def compare_ordering_key(k):
if k[1] is None:
return (1, 0) # +infinity, larger than any number
return (0, k[1])
self._ordering.sort(key=compare_ordering_key)
# Return a list of form.cleaned_data dicts in the order specified by
# the form data.
return [self.forms[i[0]] for i in self._ordering]
@classmethod
def get_default_prefix(cls):
return "form"
@classmethod
def get_deletion_widget(cls):
return cls.deletion_widget
@classmethod
def get_ordering_widget(cls):
return cls.ordering_widget
def non_form_errors(self):
"""
Return an ErrorList of errors that aren't associated with a particular
form -- i.e., from formset.clean(). Return an empty ErrorList if there
are none.
"""
if self._non_form_errors is None:
self.full_clean()
return self._non_form_errors
@property
def errors(self):
"""Return a list of form.errors for every form in self.forms."""
if self._errors is None:
self.full_clean()
return self._errors
def total_error_count(self):
"""Return the number of errors across all forms in the formset."""
return len(self.non_form_errors()) + sum(
len(form_errors) for form_errors in self.errors
)
def _should_delete_form(self, form):
"""Return whether or not the form was marked for deletion."""
return form.cleaned_data.get(DELETION_FIELD_NAME, False)
def is_valid(self):
"""Return True if every form in self.forms is valid."""
if not self.is_bound:
return False
# Accessing errors triggers a full clean the first time only.
self.errors
# List comprehension ensures is_valid() is called for all forms.
# Forms due to be deleted shouldn't cause the formset to be invalid.
forms_valid = all(
[
form.is_valid()
for form in self.forms
if not (self.can_delete and self._should_delete_form(form))
]
)
return forms_valid and not self.non_form_errors()
def full_clean(self):
"""
Clean all of self.data and populate self._errors and
self._non_form_errors.
"""
self._errors = []
self._non_form_errors = self.error_class(
error_class="nonform", renderer=self.renderer
)
empty_forms_count = 0
if not self.is_bound: # Stop further processing.
return
if not self.management_form.is_valid():
error = ValidationError(
self.error_messages["missing_management_form"],
params={
"field_names": ", ".join(
self.management_form.add_prefix(field_name)
for field_name in self.management_form.errors
),
},
code="missing_management_form",
)
self._non_form_errors.append(error)
for i, form in enumerate(self.forms):
# Empty forms are unchanged forms beyond those with initial data.
if not form.has_changed() and i >= self.initial_form_count():
empty_forms_count += 1
# Accessing errors calls full_clean() if necessary.
# _should_delete_form() requires cleaned_data.
form_errors = form.errors
if self.can_delete and self._should_delete_form(form):
continue
self._errors.append(form_errors)
try:
if (
self.validate_max
and self.total_form_count() - len(self.deleted_forms) > self.max_num
) or self.management_form.cleaned_data[
TOTAL_FORM_COUNT
] > self.absolute_max:
raise ValidationError(
self.error_messages["too_many_forms"] % {"num": self.max_num},
code="too_many_forms",
)
if (
self.validate_min
and self.total_form_count()
- len(self.deleted_forms)
- empty_forms_count
< self.min_num
):
raise ValidationError(
self.error_messages["too_few_forms"] % {"num": self.min_num},
code="too_few_forms",
)
# Give self.clean() a chance to do cross-form validation.
self.clean()
except ValidationError as e:
self._non_form_errors = self.error_class(
e.error_list,
error_class="nonform",
renderer=self.renderer,
)
def clean(self):
"""
Hook for doing any extra formset-wide cleaning after Form.clean() has
been called on every form. Any ValidationError raised by this method
will not be associated with a particular form; it will be accessible
via formset.non_form_errors()
"""
pass
def has_changed(self):
"""Return True if data in any form differs from initial."""
return any(form.has_changed() for form in self)
def add_fields(self, form, index):
"""A hook for adding extra fields on to each form instance."""
initial_form_count = self.initial_form_count()
if self.can_order:
# Only pre-fill the ordering field for initial forms.
if index is not None and index < initial_form_count:
form.fields[ORDERING_FIELD_NAME] = IntegerField(
label=_("Order"),
initial=index + 1,
required=False,
widget=self.get_ordering_widget(),
)
else:
form.fields[ORDERING_FIELD_NAME] = IntegerField(
label=_("Order"),
required=False,
widget=self.get_ordering_widget(),
)
if self.can_delete and (self.can_delete_extra or index < initial_form_count):
form.fields[DELETION_FIELD_NAME] = BooleanField(
label=_("Delete"),
required=False,
widget=self.get_deletion_widget(),
)
def add_prefix(self, index):
return "%s-%s" % (self.prefix, index)
def is_multipart(self):
"""
Return True if the formset needs to be multipart, i.e. it
has FileInput, or False otherwise.
"""
if self.forms:
return self.forms[0].is_multipart()
else:
return self.empty_form.is_multipart()
@property
def media(self):
# All the forms on a FormSet are the same, so you only need to
# interrogate the first form for media.
if self.forms:
return self.forms[0].media
else:
return self.empty_form.media
@property
def template_name(self):
return self.renderer.formset_template_name
def get_context(self):
return {"formset": self}
def formset_factory(
form,
formset=BaseFormSet,
extra=1,
can_order=False,
can_delete=False,
max_num=None,
validate_max=False,
min_num=None,
validate_min=False,
absolute_max=None,
can_delete_extra=True,
renderer=None,
):
"""Return a FormSet for the given form class."""
if min_num is None:
min_num = DEFAULT_MIN_NUM
if max_num is None:
max_num = DEFAULT_MAX_NUM
# absolute_max is a hard limit on forms instantiated, to prevent
# memory-exhaustion attacks. Default to max_num + DEFAULT_MAX_NUM
# (which is 2 * DEFAULT_MAX_NUM if max_num is None in the first place).
if absolute_max is None:
absolute_max = max_num + DEFAULT_MAX_NUM
if max_num > absolute_max:
raise ValueError("'absolute_max' must be greater or equal to 'max_num'.")
attrs = {
"form": form,
"extra": extra,
"can_order": can_order,
"can_delete": can_delete,
"can_delete_extra": can_delete_extra,
"min_num": min_num,
"max_num": max_num,
"absolute_max": absolute_max,
"validate_min": validate_min,
"validate_max": validate_max,
"renderer": renderer or get_default_renderer(),
}
return type(form.__name__ + "FormSet", (formset,), attrs)
def all_valid(formsets):
"""Validate every formset and return True if all are valid."""
# List comprehension ensures is_valid() is called for all formsets.
return all([formset.is_valid() for formset in formsets])
|
c7d0fb08eddedfeeca15386f87d60cfcb39aaedc4e7dc1a2ce7de3066bf5d99b | import datetime
import io
import json
import mimetypes
import os
import re
import sys
import time
from email.header import Header
from http.client import responses
from urllib.parse import quote, urlparse
from django.conf import settings
from django.core import signals, signing
from django.core.exceptions import DisallowedRedirect
from django.core.serializers.json import DjangoJSONEncoder
from django.http.cookie import SimpleCookie
from django.utils import timezone
from django.utils.datastructures import CaseInsensitiveMapping
from django.utils.encoding import iri_to_uri
from django.utils.http import http_date
from django.utils.regex_helper import _lazy_re_compile
_charset_from_content_type_re = _lazy_re_compile(
r";\s*charset=(?P<charset>[^\s;]+)", re.I
)
class ResponseHeaders(CaseInsensitiveMapping):
def __init__(self, data):
"""
Populate the initial data using __setitem__ to ensure values are
correctly encoded.
"""
self._store = {}
if data:
for header, value in self._unpack_items(data):
self[header] = value
def _convert_to_charset(self, value, charset, mime_encode=False):
"""
Convert headers key/value to ascii/latin-1 native strings.
`charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and
`value` can't be represented in the given charset, apply MIME-encoding.
"""
try:
if isinstance(value, str):
# Ensure string is valid in given charset
value.encode(charset)
elif isinstance(value, bytes):
# Convert bytestring using given charset
value = value.decode(charset)
else:
value = str(value)
# Ensure string is valid in given charset.
value.encode(charset)
if "\n" in value or "\r" in value:
raise BadHeaderError(
f"Header values can't contain newlines (got {value!r})"
)
except UnicodeError as e:
# Encoding to a string of the specified charset failed, but we
# don't know what type that value was, or if it contains newlines,
# which we may need to check for before sending it to be
# encoded for multiple character sets.
if (isinstance(value, bytes) and (b"\n" in value or b"\r" in value)) or (
isinstance(value, str) and ("\n" in value or "\r" in value)
):
raise BadHeaderError(
f"Header values can't contain newlines (got {value!r})"
) from e
if mime_encode:
value = Header(value, "utf-8", maxlinelen=sys.maxsize).encode()
else:
e.reason += ", HTTP response headers must be in %s format" % charset
raise
return value
def __delitem__(self, key):
self.pop(key)
def __setitem__(self, key, value):
key = self._convert_to_charset(key, "ascii")
value = self._convert_to_charset(value, "latin-1", mime_encode=True)
self._store[key.lower()] = (key, value)
def pop(self, key, default=None):
return self._store.pop(key.lower(), default)
def setdefault(self, key, value):
if key not in self:
self[key] = value
class BadHeaderError(ValueError):
pass
class HttpResponseBase:
"""
An HTTP response base class with dictionary-accessed headers.
This class doesn't handle content. It should not be used directly.
Use the HttpResponse and StreamingHttpResponse subclasses instead.
"""
status_code = 200
def __init__(
self, content_type=None, status=None, reason=None, charset=None, headers=None
):
self.headers = ResponseHeaders(headers)
self._charset = charset
if "Content-Type" not in self.headers:
if content_type is None:
content_type = f"text/html; charset={self.charset}"
self.headers["Content-Type"] = content_type
elif content_type:
raise ValueError(
"'headers' must not contain 'Content-Type' when the "
"'content_type' parameter is provided."
)
self._resource_closers = []
# This parameter is set by the handler. It's necessary to preserve the
# historical behavior of request_finished.
self._handler_class = None
self.cookies = SimpleCookie()
self.closed = False
if status is not None:
try:
self.status_code = int(status)
except (ValueError, TypeError):
raise TypeError("HTTP status code must be an integer.")
if not 100 <= self.status_code <= 599:
raise ValueError("HTTP status code must be an integer from 100 to 599.")
self._reason_phrase = reason
@property
def reason_phrase(self):
if self._reason_phrase is not None:
return self._reason_phrase
# Leave self._reason_phrase unset in order to use the default
# reason phrase for status code.
return responses.get(self.status_code, "Unknown Status Code")
@reason_phrase.setter
def reason_phrase(self, value):
self._reason_phrase = value
@property
def charset(self):
if self._charset is not None:
return self._charset
# The Content-Type header may not yet be set, because the charset is
# being inserted *into* it.
if content_type := self.headers.get("Content-Type"):
if matched := _charset_from_content_type_re.search(content_type):
# Extract the charset and strip its double quotes.
# Note that having parsed it from the Content-Type, we don't
# store it back into the _charset for later intentionally, to
# allow for the Content-Type to be switched again later.
return matched["charset"].replace('"', "")
return settings.DEFAULT_CHARSET
@charset.setter
def charset(self, value):
self._charset = value
def serialize_headers(self):
"""HTTP headers as a bytestring."""
return b"\r\n".join(
[
key.encode("ascii") + b": " + value.encode("latin-1")
for key, value in self.headers.items()
]
)
__bytes__ = serialize_headers
@property
def _content_type_for_repr(self):
return (
', "%s"' % self.headers["Content-Type"]
if "Content-Type" in self.headers
else ""
)
def __setitem__(self, header, value):
self.headers[header] = value
def __delitem__(self, header):
del self.headers[header]
def __getitem__(self, header):
return self.headers[header]
def has_header(self, header):
"""Case-insensitive check for a header."""
return header in self.headers
__contains__ = has_header
def items(self):
return self.headers.items()
def get(self, header, alternate=None):
return self.headers.get(header, alternate)
def set_cookie(
self,
key,
value="",
max_age=None,
expires=None,
path="/",
domain=None,
secure=False,
httponly=False,
samesite=None,
):
"""
Set a cookie.
``expires`` can be:
- a string in the correct format,
- a naive ``datetime.datetime`` object in UTC,
- an aware ``datetime.datetime`` object in any time zone.
If it is a ``datetime.datetime`` object then calculate ``max_age``.
``max_age`` can be:
- int/float specifying seconds,
- ``datetime.timedelta`` object.
"""
self.cookies[key] = value
if expires is not None:
if isinstance(expires, datetime.datetime):
if timezone.is_naive(expires):
expires = timezone.make_aware(expires, datetime.timezone.utc)
delta = expires - datetime.datetime.now(tz=datetime.timezone.utc)
# Add one second so the date matches exactly (a fraction of
# time gets lost between converting to a timedelta and
# then the date string).
delta = delta + datetime.timedelta(seconds=1)
# Just set max_age - the max_age logic will set expires.
expires = None
if max_age is not None:
raise ValueError("'expires' and 'max_age' can't be used together.")
max_age = max(0, delta.days * 86400 + delta.seconds)
else:
self.cookies[key]["expires"] = expires
else:
self.cookies[key]["expires"] = ""
if max_age is not None:
if isinstance(max_age, datetime.timedelta):
max_age = max_age.total_seconds()
self.cookies[key]["max-age"] = int(max_age)
# IE requires expires, so set it if hasn't been already.
if not expires:
self.cookies[key]["expires"] = http_date(time.time() + max_age)
if path is not None:
self.cookies[key]["path"] = path
if domain is not None:
self.cookies[key]["domain"] = domain
if secure:
self.cookies[key]["secure"] = True
if httponly:
self.cookies[key]["httponly"] = True
if samesite:
if samesite.lower() not in ("lax", "none", "strict"):
raise ValueError('samesite must be "lax", "none", or "strict".')
self.cookies[key]["samesite"] = samesite
def setdefault(self, key, value):
"""Set a header unless it has already been set."""
self.headers.setdefault(key, value)
def set_signed_cookie(self, key, value, salt="", **kwargs):
value = signing.get_cookie_signer(salt=key + salt).sign(value)
return self.set_cookie(key, value, **kwargs)
def delete_cookie(self, key, path="/", domain=None, samesite=None):
# Browsers can ignore the Set-Cookie header if the cookie doesn't use
# the secure flag and:
# - the cookie name starts with "__Host-" or "__Secure-", or
# - the samesite is "none".
secure = key.startswith(("__Secure-", "__Host-")) or (
samesite and samesite.lower() == "none"
)
self.set_cookie(
key,
max_age=0,
path=path,
domain=domain,
secure=secure,
expires="Thu, 01 Jan 1970 00:00:00 GMT",
samesite=samesite,
)
# Common methods used by subclasses
def make_bytes(self, value):
"""Turn a value into a bytestring encoded in the output charset."""
# Per PEP 3333, this response body must be bytes. To avoid returning
# an instance of a subclass, this function returns `bytes(value)`.
# This doesn't make a copy when `value` already contains bytes.
# Handle string types -- we can't rely on force_bytes here because:
# - Python attempts str conversion first
# - when self._charset != 'utf-8' it re-encodes the content
if isinstance(value, (bytes, memoryview)):
return bytes(value)
if isinstance(value, str):
return bytes(value.encode(self.charset))
# Handle non-string types.
return str(value).encode(self.charset)
# These methods partially implement the file-like object interface.
# See https://docs.python.org/library/io.html#io.IOBase
# The WSGI server must call this method upon completion of the request.
# See http://blog.dscpl.com.au/2012/10/obligations-for-calling-close-on.html
def close(self):
for closer in self._resource_closers:
try:
closer()
except Exception:
pass
# Free resources that were still referenced.
self._resource_closers.clear()
self.closed = True
signals.request_finished.send(sender=self._handler_class)
def write(self, content):
raise OSError("This %s instance is not writable" % self.__class__.__name__)
def flush(self):
pass
def tell(self):
raise OSError(
"This %s instance cannot tell its position" % self.__class__.__name__
)
# These methods partially implement a stream-like object interface.
# See https://docs.python.org/library/io.html#io.IOBase
def readable(self):
return False
def seekable(self):
return False
def writable(self):
return False
def writelines(self, lines):
raise OSError("This %s instance is not writable" % self.__class__.__name__)
class HttpResponse(HttpResponseBase):
"""
An HTTP response class with a string as content.
This content can be read, appended to, or replaced.
"""
streaming = False
non_picklable_attrs = frozenset(
[
"resolver_match",
# Non-picklable attributes added by test clients.
"asgi_request",
"client",
"context",
"json",
"templates",
"wsgi_request",
]
)
def __init__(self, content=b"", *args, **kwargs):
super().__init__(*args, **kwargs)
# Content is a bytestring. See the `content` property methods.
self.content = content
def __getstate__(self):
obj_dict = self.__dict__.copy()
for attr in self.non_picklable_attrs:
if attr in obj_dict:
del obj_dict[attr]
return obj_dict
def __repr__(self):
return "<%(cls)s status_code=%(status_code)d%(content_type)s>" % {
"cls": self.__class__.__name__,
"status_code": self.status_code,
"content_type": self._content_type_for_repr,
}
def serialize(self):
"""Full HTTP message, including headers, as a bytestring."""
return self.serialize_headers() + b"\r\n\r\n" + self.content
__bytes__ = serialize
@property
def content(self):
return b"".join(self._container)
@content.setter
def content(self, value):
# Consume iterators upon assignment to allow repeated iteration.
if hasattr(value, "__iter__") and not isinstance(
value, (bytes, memoryview, str)
):
content = b"".join(self.make_bytes(chunk) for chunk in value)
if hasattr(value, "close"):
try:
value.close()
except Exception:
pass
else:
content = self.make_bytes(value)
# Create a list of properly encoded bytestrings to support write().
self._container = [content]
def __iter__(self):
return iter(self._container)
def write(self, content):
self._container.append(self.make_bytes(content))
def tell(self):
return len(self.content)
def getvalue(self):
return self.content
def writable(self):
return True
def writelines(self, lines):
for line in lines:
self.write(line)
class StreamingHttpResponse(HttpResponseBase):
"""
A streaming HTTP response class with an iterator as content.
This should only be iterated once, when the response is streamed to the
client. However, it can be appended to or replaced with a new iterator
that wraps the original content (or yields entirely new content).
"""
streaming = True
def __init__(self, streaming_content=(), *args, **kwargs):
super().__init__(*args, **kwargs)
# `streaming_content` should be an iterable of bytestrings.
# See the `streaming_content` property methods.
self.streaming_content = streaming_content
def __repr__(self):
return "<%(cls)s status_code=%(status_code)d%(content_type)s>" % {
"cls": self.__class__.__qualname__,
"status_code": self.status_code,
"content_type": self._content_type_for_repr,
}
@property
def content(self):
raise AttributeError(
"This %s instance has no `content` attribute. Use "
"`streaming_content` instead." % self.__class__.__name__
)
@property
def streaming_content(self):
return map(self.make_bytes, self._iterator)
@streaming_content.setter
def streaming_content(self, value):
self._set_streaming_content(value)
def _set_streaming_content(self, value):
# Ensure we can never iterate on "value" more than once.
self._iterator = iter(value)
if hasattr(value, "close"):
self._resource_closers.append(value.close)
def __iter__(self):
return self.streaming_content
def getvalue(self):
return b"".join(self.streaming_content)
class FileResponse(StreamingHttpResponse):
"""
A streaming HTTP response class optimized for files.
"""
block_size = 4096
def __init__(self, *args, as_attachment=False, filename="", **kwargs):
self.as_attachment = as_attachment
self.filename = filename
self._no_explicit_content_type = (
"content_type" not in kwargs or kwargs["content_type"] is None
)
super().__init__(*args, **kwargs)
def _set_streaming_content(self, value):
if not hasattr(value, "read"):
self.file_to_stream = None
return super()._set_streaming_content(value)
self.file_to_stream = filelike = value
if hasattr(filelike, "close"):
self._resource_closers.append(filelike.close)
value = iter(lambda: filelike.read(self.block_size), b"")
self.set_headers(filelike)
super()._set_streaming_content(value)
def set_headers(self, filelike):
"""
Set some common response headers (Content-Length, Content-Type, and
Content-Disposition) based on the `filelike` response content.
"""
filename = getattr(filelike, "name", "")
filename = filename if isinstance(filename, str) else ""
seekable = hasattr(filelike, "seek") and (
not hasattr(filelike, "seekable") or filelike.seekable()
)
if hasattr(filelike, "tell"):
if seekable:
initial_position = filelike.tell()
filelike.seek(0, io.SEEK_END)
self.headers["Content-Length"] = filelike.tell() - initial_position
filelike.seek(initial_position)
elif hasattr(filelike, "getbuffer"):
self.headers["Content-Length"] = (
filelike.getbuffer().nbytes - filelike.tell()
)
elif os.path.exists(filename):
self.headers["Content-Length"] = (
os.path.getsize(filename) - filelike.tell()
)
elif seekable:
self.headers["Content-Length"] = sum(
iter(lambda: len(filelike.read(self.block_size)), 0)
)
filelike.seek(-int(self.headers["Content-Length"]), io.SEEK_END)
filename = os.path.basename(self.filename or filename)
if self._no_explicit_content_type:
if filename:
content_type, encoding = mimetypes.guess_type(filename)
# Encoding isn't set to prevent browsers from automatically
# uncompressing files.
content_type = {
"bzip2": "application/x-bzip",
"gzip": "application/gzip",
"xz": "application/x-xz",
}.get(encoding, content_type)
self.headers["Content-Type"] = (
content_type or "application/octet-stream"
)
else:
self.headers["Content-Type"] = "application/octet-stream"
if filename:
disposition = "attachment" if self.as_attachment else "inline"
try:
filename.encode("ascii")
file_expr = 'filename="{}"'.format(
filename.replace("\\", "\\\\").replace('"', r"\"")
)
except UnicodeEncodeError:
file_expr = "filename*=utf-8''{}".format(quote(filename))
self.headers["Content-Disposition"] = "{}; {}".format(
disposition, file_expr
)
elif self.as_attachment:
self.headers["Content-Disposition"] = "attachment"
class HttpResponseRedirectBase(HttpResponse):
allowed_schemes = ["http", "https", "ftp"]
def __init__(self, redirect_to, *args, **kwargs):
super().__init__(*args, **kwargs)
self["Location"] = iri_to_uri(redirect_to)
parsed = urlparse(str(redirect_to))
if parsed.scheme and parsed.scheme not in self.allowed_schemes:
raise DisallowedRedirect(
"Unsafe redirect to URL with protocol '%s'" % parsed.scheme
)
url = property(lambda self: self["Location"])
def __repr__(self):
return (
'<%(cls)s status_code=%(status_code)d%(content_type)s, url="%(url)s">'
% {
"cls": self.__class__.__name__,
"status_code": self.status_code,
"content_type": self._content_type_for_repr,
"url": self.url,
}
)
class HttpResponseRedirect(HttpResponseRedirectBase):
status_code = 302
class HttpResponsePermanentRedirect(HttpResponseRedirectBase):
status_code = 301
class HttpResponseNotModified(HttpResponse):
status_code = 304
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
del self["content-type"]
@HttpResponse.content.setter
def content(self, value):
if value:
raise AttributeError(
"You cannot set content to a 304 (Not Modified) response"
)
self._container = []
class HttpResponseBadRequest(HttpResponse):
status_code = 400
class HttpResponseNotFound(HttpResponse):
status_code = 404
class HttpResponseForbidden(HttpResponse):
status_code = 403
class HttpResponseNotAllowed(HttpResponse):
status_code = 405
def __init__(self, permitted_methods, *args, **kwargs):
super().__init__(*args, **kwargs)
self["Allow"] = ", ".join(permitted_methods)
def __repr__(self):
return "<%(cls)s [%(methods)s] status_code=%(status_code)d%(content_type)s>" % {
"cls": self.__class__.__name__,
"status_code": self.status_code,
"content_type": self._content_type_for_repr,
"methods": self["Allow"],
}
class HttpResponseGone(HttpResponse):
status_code = 410
class HttpResponseServerError(HttpResponse):
status_code = 500
class Http404(Exception):
pass
class JsonResponse(HttpResponse):
"""
An HTTP response class that consumes data to be serialized to JSON.
:param data: Data to be dumped into json. By default only ``dict`` objects
are allowed to be passed due to a security flaw before ECMAScript 5. See
the ``safe`` parameter for more information.
:param encoder: Should be a json encoder class. Defaults to
``django.core.serializers.json.DjangoJSONEncoder``.
:param safe: Controls if only ``dict`` objects may be serialized. Defaults
to ``True``.
:param json_dumps_params: A dictionary of kwargs passed to json.dumps().
"""
def __init__(
self,
data,
encoder=DjangoJSONEncoder,
safe=True,
json_dumps_params=None,
**kwargs,
):
if safe and not isinstance(data, dict):
raise TypeError(
"In order to allow non-dict objects to be serialized set the "
"safe parameter to False."
)
if json_dumps_params is None:
json_dumps_params = {}
kwargs.setdefault("content_type", "application/json")
data = json.dumps(data, cls=encoder, **json_dumps_params)
super().__init__(content=data, **kwargs)
|
b45736efa2543244277209e5414d9ab0dc2bde7a41d7ffb3234238a6bdd7985b | import functools
import re
from collections import defaultdict
from itertools import chain
from django.conf import settings
from django.db import models
from django.db.migrations import operations
from django.db.migrations.migration import Migration
from django.db.migrations.operations.models import AlterModelOptions
from django.db.migrations.optimizer import MigrationOptimizer
from django.db.migrations.questioner import MigrationQuestioner
from django.db.migrations.utils import (
COMPILED_REGEX_TYPE,
RegexObject,
resolve_relation,
)
from django.utils.topological_sort import stable_topological_sort
class MigrationAutodetector:
"""
Take a pair of ProjectStates and compare them to see what the first would
need doing to make it match the second (the second usually being the
project's current state).
Note that this naturally operates on entire projects at a time,
as it's likely that changes interact (for example, you can't
add a ForeignKey without having a migration to add the table it
depends on first). A user interface may offer single-app usage
if it wishes, with the caveat that it may not always be possible.
"""
def __init__(self, from_state, to_state, questioner=None):
self.from_state = from_state
self.to_state = to_state
self.questioner = questioner or MigrationQuestioner()
self.existing_apps = {app for app, model in from_state.models}
def changes(self, graph, trim_to_apps=None, convert_apps=None, migration_name=None):
"""
Main entry point to produce a list of applicable changes.
Take a graph to base names on and an optional set of apps
to try and restrict to (restriction is not guaranteed)
"""
changes = self._detect_changes(convert_apps, graph)
changes = self.arrange_for_graph(changes, graph, migration_name)
if trim_to_apps:
changes = self._trim_to_apps(changes, trim_to_apps)
return changes
def deep_deconstruct(self, obj):
"""
Recursive deconstruction for a field and its arguments.
Used for full comparison for rename/alter; sometimes a single-level
deconstruction will not compare correctly.
"""
if isinstance(obj, list):
return [self.deep_deconstruct(value) for value in obj]
elif isinstance(obj, tuple):
return tuple(self.deep_deconstruct(value) for value in obj)
elif isinstance(obj, dict):
return {key: self.deep_deconstruct(value) for key, value in obj.items()}
elif isinstance(obj, functools.partial):
return (
obj.func,
self.deep_deconstruct(obj.args),
self.deep_deconstruct(obj.keywords),
)
elif isinstance(obj, COMPILED_REGEX_TYPE):
return RegexObject(obj)
elif isinstance(obj, type):
# If this is a type that implements 'deconstruct' as an instance method,
# avoid treating this as being deconstructible itself - see #22951
return obj
elif hasattr(obj, "deconstruct"):
deconstructed = obj.deconstruct()
if isinstance(obj, models.Field):
# we have a field which also returns a name
deconstructed = deconstructed[1:]
path, args, kwargs = deconstructed
return (
path,
[self.deep_deconstruct(value) for value in args],
{key: self.deep_deconstruct(value) for key, value in kwargs.items()},
)
else:
return obj
def only_relation_agnostic_fields(self, fields):
"""
Return a definition of the fields that ignores field names and
what related fields actually relate to. Used for detecting renames (as
the related fields change during renames).
"""
fields_def = []
for name, field in sorted(fields.items()):
deconstruction = self.deep_deconstruct(field)
if field.remote_field and field.remote_field.model:
deconstruction[2].pop("to", None)
fields_def.append(deconstruction)
return fields_def
def _detect_changes(self, convert_apps=None, graph=None):
"""
Return a dict of migration plans which will achieve the
change from from_state to to_state. The dict has app labels
as keys and a list of migrations as values.
The resulting migrations aren't specially named, but the names
do matter for dependencies inside the set.
convert_apps is the list of apps to convert to use migrations
(i.e. to make initial migrations for, in the usual case)
graph is an optional argument that, if provided, can help improve
dependency generation and avoid potential circular dependencies.
"""
# The first phase is generating all the operations for each app
# and gathering them into a big per-app list.
# Then go through that list, order it, and split into migrations to
# resolve dependencies caused by M2Ms and FKs.
self.generated_operations = {}
self.altered_indexes = {}
self.altered_constraints = {}
self.renamed_fields = {}
# Prepare some old/new state and model lists, separating
# proxy models and ignoring unmigrated apps.
self.old_model_keys = set()
self.old_proxy_keys = set()
self.old_unmanaged_keys = set()
self.new_model_keys = set()
self.new_proxy_keys = set()
self.new_unmanaged_keys = set()
for (app_label, model_name), model_state in self.from_state.models.items():
if not model_state.options.get("managed", True):
self.old_unmanaged_keys.add((app_label, model_name))
elif app_label not in self.from_state.real_apps:
if model_state.options.get("proxy"):
self.old_proxy_keys.add((app_label, model_name))
else:
self.old_model_keys.add((app_label, model_name))
for (app_label, model_name), model_state in self.to_state.models.items():
if not model_state.options.get("managed", True):
self.new_unmanaged_keys.add((app_label, model_name))
elif app_label not in self.from_state.real_apps or (
convert_apps and app_label in convert_apps
):
if model_state.options.get("proxy"):
self.new_proxy_keys.add((app_label, model_name))
else:
self.new_model_keys.add((app_label, model_name))
self.from_state.resolve_fields_and_relations()
self.to_state.resolve_fields_and_relations()
# Renames have to come first
self.generate_renamed_models()
# Prepare lists of fields and generate through model map
self._prepare_field_lists()
self._generate_through_model_map()
# Generate non-rename model operations
self.generate_deleted_models()
self.generate_created_models()
self.generate_deleted_proxies()
self.generate_created_proxies()
self.generate_altered_options()
self.generate_altered_managers()
# Create the renamed fields and store them in self.renamed_fields.
# They are used by create_altered_indexes(), generate_altered_fields(),
# generate_removed_altered_index/unique_together(), and
# generate_altered_index/unique_together().
self.create_renamed_fields()
# Create the altered indexes and store them in self.altered_indexes.
# This avoids the same computation in generate_removed_indexes()
# and generate_added_indexes().
self.create_altered_indexes()
self.create_altered_constraints()
# Generate index removal operations before field is removed
self.generate_removed_constraints()
self.generate_removed_indexes()
# Generate field renaming operations.
self.generate_renamed_fields()
self.generate_renamed_indexes()
# Generate removal of foo together.
self.generate_removed_altered_unique_together()
self.generate_removed_altered_index_together() # RemovedInDjango51Warning.
# Generate field operations.
self.generate_removed_fields()
self.generate_added_fields()
self.generate_altered_fields()
self.generate_altered_order_with_respect_to()
self.generate_altered_unique_together()
self.generate_altered_index_together() # RemovedInDjango51Warning.
self.generate_added_indexes()
self.generate_added_constraints()
self.generate_altered_db_table()
self._sort_migrations()
self._build_migration_list(graph)
self._optimize_migrations()
return self.migrations
def _prepare_field_lists(self):
"""
Prepare field lists and a list of the fields that used through models
in the old state so dependencies can be made from the through model
deletion to the field that uses it.
"""
self.kept_model_keys = self.old_model_keys & self.new_model_keys
self.kept_proxy_keys = self.old_proxy_keys & self.new_proxy_keys
self.kept_unmanaged_keys = self.old_unmanaged_keys & self.new_unmanaged_keys
self.through_users = {}
self.old_field_keys = {
(app_label, model_name, field_name)
for app_label, model_name in self.kept_model_keys
for field_name in self.from_state.models[
app_label, self.renamed_models.get((app_label, model_name), model_name)
].fields
}
self.new_field_keys = {
(app_label, model_name, field_name)
for app_label, model_name in self.kept_model_keys
for field_name in self.to_state.models[app_label, model_name].fields
}
def _generate_through_model_map(self):
"""Through model map generation."""
for app_label, model_name in sorted(self.old_model_keys):
old_model_name = self.renamed_models.get(
(app_label, model_name), model_name
)
old_model_state = self.from_state.models[app_label, old_model_name]
for field_name, field in old_model_state.fields.items():
if hasattr(field, "remote_field") and getattr(
field.remote_field, "through", None
):
through_key = resolve_relation(
field.remote_field.through, app_label, model_name
)
self.through_users[through_key] = (
app_label,
old_model_name,
field_name,
)
@staticmethod
def _resolve_dependency(dependency):
"""
Return the resolved dependency and a boolean denoting whether or not
it was swappable.
"""
if dependency[0] != "__setting__":
return dependency, False
resolved_app_label, resolved_object_name = getattr(
settings, dependency[1]
).split(".")
return (resolved_app_label, resolved_object_name.lower()) + dependency[2:], True
def _build_migration_list(self, graph=None):
"""
Chop the lists of operations up into migrations with dependencies on
each other. Do this by going through an app's list of operations until
one is found that has an outgoing dependency that isn't in another
app's migration yet (hasn't been chopped off its list). Then chop off
the operations before it into a migration and move onto the next app.
If the loops completes without doing anything, there's a circular
dependency (which _should_ be impossible as the operations are
all split at this point so they can't depend and be depended on).
"""
self.migrations = {}
num_ops = sum(len(x) for x in self.generated_operations.values())
chop_mode = False
while num_ops:
# On every iteration, we step through all the apps and see if there
# is a completed set of operations.
# If we find that a subset of the operations are complete we can
# try to chop it off from the rest and continue, but we only
# do this if we've already been through the list once before
# without any chopping and nothing has changed.
for app_label in sorted(self.generated_operations):
chopped = []
dependencies = set()
for operation in list(self.generated_operations[app_label]):
deps_satisfied = True
operation_dependencies = set()
for dep in operation._auto_deps:
# Temporarily resolve the swappable dependency to
# prevent circular references. While keeping the
# dependency checks on the resolved model, add the
# swappable dependencies.
original_dep = dep
dep, is_swappable_dep = self._resolve_dependency(dep)
if dep[0] != app_label:
# External app dependency. See if it's not yet
# satisfied.
for other_operation in self.generated_operations.get(
dep[0], []
):
if self.check_dependency(other_operation, dep):
deps_satisfied = False
break
if not deps_satisfied:
break
else:
if is_swappable_dep:
operation_dependencies.add(
(original_dep[0], original_dep[1])
)
elif dep[0] in self.migrations:
operation_dependencies.add(
(dep[0], self.migrations[dep[0]][-1].name)
)
else:
# If we can't find the other app, we add a
# first/last dependency, but only if we've
# already been through once and checked
# everything.
if chop_mode:
# If the app already exists, we add a
# dependency on the last migration, as
# we don't know which migration
# contains the target field. If it's
# not yet migrated or has no
# migrations, we use __first__.
if graph and graph.leaf_nodes(dep[0]):
operation_dependencies.add(
graph.leaf_nodes(dep[0])[0]
)
else:
operation_dependencies.add(
(dep[0], "__first__")
)
else:
deps_satisfied = False
if deps_satisfied:
chopped.append(operation)
dependencies.update(operation_dependencies)
del self.generated_operations[app_label][0]
else:
break
# Make a migration! Well, only if there's stuff to put in it
if dependencies or chopped:
if not self.generated_operations[app_label] or chop_mode:
subclass = type(
"Migration",
(Migration,),
{"operations": [], "dependencies": []},
)
instance = subclass(
"auto_%i" % (len(self.migrations.get(app_label, [])) + 1),
app_label,
)
instance.dependencies = list(dependencies)
instance.operations = chopped
instance.initial = app_label not in self.existing_apps
self.migrations.setdefault(app_label, []).append(instance)
chop_mode = False
else:
self.generated_operations[app_label] = (
chopped + self.generated_operations[app_label]
)
new_num_ops = sum(len(x) for x in self.generated_operations.values())
if new_num_ops == num_ops:
if not chop_mode:
chop_mode = True
else:
raise ValueError(
"Cannot resolve operation dependencies: %r"
% self.generated_operations
)
num_ops = new_num_ops
def _sort_migrations(self):
"""
Reorder to make things possible. Reordering may be needed so FKs work
nicely inside the same app.
"""
for app_label, ops in sorted(self.generated_operations.items()):
# construct a dependency graph for intra-app dependencies
dependency_graph = {op: set() for op in ops}
for op in ops:
for dep in op._auto_deps:
# Resolve intra-app dependencies to handle circular
# references involving a swappable model.
dep = self._resolve_dependency(dep)[0]
if dep[0] == app_label:
for op2 in ops:
if self.check_dependency(op2, dep):
dependency_graph[op].add(op2)
# we use a stable sort for deterministic tests & general behavior
self.generated_operations[app_label] = stable_topological_sort(
ops, dependency_graph
)
def _optimize_migrations(self):
# Add in internal dependencies among the migrations
for app_label, migrations in self.migrations.items():
for m1, m2 in zip(migrations, migrations[1:]):
m2.dependencies.append((app_label, m1.name))
# De-dupe dependencies
for migrations in self.migrations.values():
for migration in migrations:
migration.dependencies = list(set(migration.dependencies))
# Optimize migrations
for app_label, migrations in self.migrations.items():
for migration in migrations:
migration.operations = MigrationOptimizer().optimize(
migration.operations, app_label
)
def check_dependency(self, operation, dependency):
"""
Return True if the given operation depends on the given dependency,
False otherwise.
"""
# Created model
if dependency[2] is None and dependency[3] is True:
return (
isinstance(operation, operations.CreateModel)
and operation.name_lower == dependency[1].lower()
)
# Created field
elif dependency[2] is not None and dependency[3] is True:
return (
isinstance(operation, operations.CreateModel)
and operation.name_lower == dependency[1].lower()
and any(dependency[2] == x for x, y in operation.fields)
) or (
isinstance(operation, operations.AddField)
and operation.model_name_lower == dependency[1].lower()
and operation.name_lower == dependency[2].lower()
)
# Removed field
elif dependency[2] is not None and dependency[3] is False:
return (
isinstance(operation, operations.RemoveField)
and operation.model_name_lower == dependency[1].lower()
and operation.name_lower == dependency[2].lower()
)
# Removed model
elif dependency[2] is None and dependency[3] is False:
return (
isinstance(operation, operations.DeleteModel)
and operation.name_lower == dependency[1].lower()
)
# Field being altered
elif dependency[2] is not None and dependency[3] == "alter":
return (
isinstance(operation, operations.AlterField)
and operation.model_name_lower == dependency[1].lower()
and operation.name_lower == dependency[2].lower()
)
# order_with_respect_to being unset for a field
elif dependency[2] is not None and dependency[3] == "order_wrt_unset":
return (
isinstance(operation, operations.AlterOrderWithRespectTo)
and operation.name_lower == dependency[1].lower()
and (operation.order_with_respect_to or "").lower()
!= dependency[2].lower()
)
# Field is removed and part of an index/unique_together
elif dependency[2] is not None and dependency[3] == "foo_together_change":
return (
isinstance(
operation,
(operations.AlterUniqueTogether, operations.AlterIndexTogether),
)
and operation.name_lower == dependency[1].lower()
)
# Unknown dependency. Raise an error.
else:
raise ValueError("Can't handle dependency %r" % (dependency,))
def add_operation(self, app_label, operation, dependencies=None, beginning=False):
# Dependencies are
# (app_label, model_name, field_name, create/delete as True/False)
operation._auto_deps = dependencies or []
if beginning:
self.generated_operations.setdefault(app_label, []).insert(0, operation)
else:
self.generated_operations.setdefault(app_label, []).append(operation)
def swappable_first_key(self, item):
"""
Place potential swappable models first in lists of created models (only
real way to solve #22783).
"""
try:
model_state = self.to_state.models[item]
base_names = {
base if isinstance(base, str) else base.__name__
for base in model_state.bases
}
string_version = "%s.%s" % (item[0], item[1])
if (
model_state.options.get("swappable")
or "AbstractUser" in base_names
or "AbstractBaseUser" in base_names
or settings.AUTH_USER_MODEL.lower() == string_version.lower()
):
return ("___" + item[0], "___" + item[1])
except LookupError:
pass
return item
def generate_renamed_models(self):
"""
Find any renamed models, generate the operations for them, and remove
the old entry from the model lists. Must be run before other
model-level generation.
"""
self.renamed_models = {}
self.renamed_models_rel = {}
added_models = self.new_model_keys - self.old_model_keys
for app_label, model_name in sorted(added_models):
model_state = self.to_state.models[app_label, model_name]
model_fields_def = self.only_relation_agnostic_fields(model_state.fields)
removed_models = self.old_model_keys - self.new_model_keys
for rem_app_label, rem_model_name in removed_models:
if rem_app_label == app_label:
rem_model_state = self.from_state.models[
rem_app_label, rem_model_name
]
rem_model_fields_def = self.only_relation_agnostic_fields(
rem_model_state.fields
)
if model_fields_def == rem_model_fields_def:
if self.questioner.ask_rename_model(
rem_model_state, model_state
):
dependencies = []
fields = list(model_state.fields.values()) + [
field.remote_field
for relations in self.to_state.relations[
app_label, model_name
].values()
for field in relations.values()
]
for field in fields:
if field.is_relation:
dependencies.extend(
self._get_dependencies_for_foreign_key(
app_label,
model_name,
field,
self.to_state,
)
)
self.add_operation(
app_label,
operations.RenameModel(
old_name=rem_model_state.name,
new_name=model_state.name,
),
dependencies=dependencies,
)
self.renamed_models[app_label, model_name] = rem_model_name
renamed_models_rel_key = "%s.%s" % (
rem_model_state.app_label,
rem_model_state.name_lower,
)
self.renamed_models_rel[
renamed_models_rel_key
] = "%s.%s" % (
model_state.app_label,
model_state.name_lower,
)
self.old_model_keys.remove((rem_app_label, rem_model_name))
self.old_model_keys.add((app_label, model_name))
break
def generate_created_models(self):
"""
Find all new models (both managed and unmanaged) and make create
operations for them as well as separate operations to create any
foreign key or M2M relationships (these are optimized later, if
possible).
Defer any model options that refer to collections of fields that might
be deferred (e.g. unique_together, index_together).
"""
old_keys = self.old_model_keys | self.old_unmanaged_keys
added_models = self.new_model_keys - old_keys
added_unmanaged_models = self.new_unmanaged_keys - old_keys
all_added_models = chain(
sorted(added_models, key=self.swappable_first_key, reverse=True),
sorted(added_unmanaged_models, key=self.swappable_first_key, reverse=True),
)
for app_label, model_name in all_added_models:
model_state = self.to_state.models[app_label, model_name]
# Gather related fields
related_fields = {}
primary_key_rel = None
for field_name, field in model_state.fields.items():
if field.remote_field:
if field.remote_field.model:
if field.primary_key:
primary_key_rel = field.remote_field.model
elif not field.remote_field.parent_link:
related_fields[field_name] = field
if getattr(field.remote_field, "through", None):
related_fields[field_name] = field
# Are there indexes/unique|index_together to defer?
indexes = model_state.options.pop("indexes")
constraints = model_state.options.pop("constraints")
unique_together = model_state.options.pop("unique_together", None)
# RemovedInDjango51Warning.
index_together = model_state.options.pop("index_together", None)
order_with_respect_to = model_state.options.pop(
"order_with_respect_to", None
)
# Depend on the deletion of any possible proxy version of us
dependencies = [
(app_label, model_name, None, False),
]
# Depend on all bases
for base in model_state.bases:
if isinstance(base, str) and "." in base:
base_app_label, base_name = base.split(".", 1)
dependencies.append((base_app_label, base_name, None, True))
# Depend on the removal of base fields if the new model has
# a field with the same name.
old_base_model_state = self.from_state.models.get(
(base_app_label, base_name)
)
new_base_model_state = self.to_state.models.get(
(base_app_label, base_name)
)
if old_base_model_state and new_base_model_state:
removed_base_fields = (
set(old_base_model_state.fields)
.difference(
new_base_model_state.fields,
)
.intersection(model_state.fields)
)
for removed_base_field in removed_base_fields:
dependencies.append(
(base_app_label, base_name, removed_base_field, False)
)
# Depend on the other end of the primary key if it's a relation
if primary_key_rel:
dependencies.append(
resolve_relation(
primary_key_rel,
app_label,
model_name,
)
+ (None, True)
)
# Generate creation operation
self.add_operation(
app_label,
operations.CreateModel(
name=model_state.name,
fields=[
d
for d in model_state.fields.items()
if d[0] not in related_fields
],
options=model_state.options,
bases=model_state.bases,
managers=model_state.managers,
),
dependencies=dependencies,
beginning=True,
)
# Don't add operations which modify the database for unmanaged models
if not model_state.options.get("managed", True):
continue
# Generate operations for each related field
for name, field in sorted(related_fields.items()):
dependencies = self._get_dependencies_for_foreign_key(
app_label,
model_name,
field,
self.to_state,
)
# Depend on our own model being created
dependencies.append((app_label, model_name, None, True))
# Make operation
self.add_operation(
app_label,
operations.AddField(
model_name=model_name,
name=name,
field=field,
),
dependencies=list(set(dependencies)),
)
# Generate other opns
if order_with_respect_to:
self.add_operation(
app_label,
operations.AlterOrderWithRespectTo(
name=model_name,
order_with_respect_to=order_with_respect_to,
),
dependencies=[
(app_label, model_name, order_with_respect_to, True),
(app_label, model_name, None, True),
],
)
related_dependencies = [
(app_label, model_name, name, True) for name in sorted(related_fields)
]
related_dependencies.append((app_label, model_name, None, True))
for index in indexes:
self.add_operation(
app_label,
operations.AddIndex(
model_name=model_name,
index=index,
),
dependencies=related_dependencies,
)
for constraint in constraints:
self.add_operation(
app_label,
operations.AddConstraint(
model_name=model_name,
constraint=constraint,
),
dependencies=related_dependencies,
)
if unique_together:
self.add_operation(
app_label,
operations.AlterUniqueTogether(
name=model_name,
unique_together=unique_together,
),
dependencies=related_dependencies,
)
# RemovedInDjango51Warning.
if index_together:
self.add_operation(
app_label,
operations.AlterIndexTogether(
name=model_name,
index_together=index_together,
),
dependencies=related_dependencies,
)
# Fix relationships if the model changed from a proxy model to a
# concrete model.
relations = self.to_state.relations
if (app_label, model_name) in self.old_proxy_keys:
for related_model_key, related_fields in relations[
app_label, model_name
].items():
related_model_state = self.to_state.models[related_model_key]
for related_field_name, related_field in related_fields.items():
self.add_operation(
related_model_state.app_label,
operations.AlterField(
model_name=related_model_state.name,
name=related_field_name,
field=related_field,
),
dependencies=[(app_label, model_name, None, True)],
)
def generate_created_proxies(self):
"""
Make CreateModel statements for proxy models. Use the same statements
as that way there's less code duplication, but for proxy models it's
safe to skip all the pointless field stuff and chuck out an operation.
"""
added = self.new_proxy_keys - self.old_proxy_keys
for app_label, model_name in sorted(added):
model_state = self.to_state.models[app_label, model_name]
assert model_state.options.get("proxy")
# Depend on the deletion of any possible non-proxy version of us
dependencies = [
(app_label, model_name, None, False),
]
# Depend on all bases
for base in model_state.bases:
if isinstance(base, str) and "." in base:
base_app_label, base_name = base.split(".", 1)
dependencies.append((base_app_label, base_name, None, True))
# Generate creation operation
self.add_operation(
app_label,
operations.CreateModel(
name=model_state.name,
fields=[],
options=model_state.options,
bases=model_state.bases,
managers=model_state.managers,
),
# Depend on the deletion of any possible non-proxy version of us
dependencies=dependencies,
)
def generate_deleted_models(self):
"""
Find all deleted models (managed and unmanaged) and make delete
operations for them as well as separate operations to delete any
foreign key or M2M relationships (these are optimized later, if
possible).
Also bring forward removal of any model options that refer to
collections of fields - the inverse of generate_created_models().
"""
new_keys = self.new_model_keys | self.new_unmanaged_keys
deleted_models = self.old_model_keys - new_keys
deleted_unmanaged_models = self.old_unmanaged_keys - new_keys
all_deleted_models = chain(
sorted(deleted_models), sorted(deleted_unmanaged_models)
)
for app_label, model_name in all_deleted_models:
model_state = self.from_state.models[app_label, model_name]
# Gather related fields
related_fields = {}
for field_name, field in model_state.fields.items():
if field.remote_field:
if field.remote_field.model:
related_fields[field_name] = field
if getattr(field.remote_field, "through", None):
related_fields[field_name] = field
# Generate option removal first
unique_together = model_state.options.pop("unique_together", None)
# RemovedInDjango51Warning.
index_together = model_state.options.pop("index_together", None)
if unique_together:
self.add_operation(
app_label,
operations.AlterUniqueTogether(
name=model_name,
unique_together=None,
),
)
# RemovedInDjango51Warning.
if index_together:
self.add_operation(
app_label,
operations.AlterIndexTogether(
name=model_name,
index_together=None,
),
)
# Then remove each related field
for name in sorted(related_fields):
self.add_operation(
app_label,
operations.RemoveField(
model_name=model_name,
name=name,
),
)
# Finally, remove the model.
# This depends on both the removal/alteration of all incoming fields
# and the removal of all its own related fields, and if it's
# a through model the field that references it.
dependencies = []
relations = self.from_state.relations
for (
related_object_app_label,
object_name,
), relation_related_fields in relations[app_label, model_name].items():
for field_name, field in relation_related_fields.items():
dependencies.append(
(related_object_app_label, object_name, field_name, False),
)
if not field.many_to_many:
dependencies.append(
(
related_object_app_label,
object_name,
field_name,
"alter",
),
)
for name in sorted(related_fields):
dependencies.append((app_label, model_name, name, False))
# We're referenced in another field's through=
through_user = self.through_users.get((app_label, model_state.name_lower))
if through_user:
dependencies.append(
(through_user[0], through_user[1], through_user[2], False)
)
# Finally, make the operation, deduping any dependencies
self.add_operation(
app_label,
operations.DeleteModel(
name=model_state.name,
),
dependencies=list(set(dependencies)),
)
def generate_deleted_proxies(self):
"""Make DeleteModel options for proxy models."""
deleted = self.old_proxy_keys - self.new_proxy_keys
for app_label, model_name in sorted(deleted):
model_state = self.from_state.models[app_label, model_name]
assert model_state.options.get("proxy")
self.add_operation(
app_label,
operations.DeleteModel(
name=model_state.name,
),
)
def create_renamed_fields(self):
"""Work out renamed fields."""
self.renamed_operations = []
old_field_keys = self.old_field_keys.copy()
for app_label, model_name, field_name in sorted(
self.new_field_keys - old_field_keys
):
old_model_name = self.renamed_models.get(
(app_label, model_name), model_name
)
old_model_state = self.from_state.models[app_label, old_model_name]
new_model_state = self.to_state.models[app_label, model_name]
field = new_model_state.get_field(field_name)
# Scan to see if this is actually a rename!
field_dec = self.deep_deconstruct(field)
for rem_app_label, rem_model_name, rem_field_name in sorted(
old_field_keys - self.new_field_keys
):
if rem_app_label == app_label and rem_model_name == model_name:
old_field = old_model_state.get_field(rem_field_name)
old_field_dec = self.deep_deconstruct(old_field)
if (
field.remote_field
and field.remote_field.model
and "to" in old_field_dec[2]
):
old_rel_to = old_field_dec[2]["to"]
if old_rel_to in self.renamed_models_rel:
old_field_dec[2]["to"] = self.renamed_models_rel[old_rel_to]
old_field.set_attributes_from_name(rem_field_name)
old_db_column = old_field.get_attname_column()[1]
if old_field_dec == field_dec or (
# Was the field renamed and db_column equal to the
# old field's column added?
old_field_dec[0:2] == field_dec[0:2]
and dict(old_field_dec[2], db_column=old_db_column)
== field_dec[2]
):
if self.questioner.ask_rename(
model_name, rem_field_name, field_name, field
):
self.renamed_operations.append(
(
rem_app_label,
rem_model_name,
old_field.db_column,
rem_field_name,
app_label,
model_name,
field,
field_name,
)
)
old_field_keys.remove(
(rem_app_label, rem_model_name, rem_field_name)
)
old_field_keys.add((app_label, model_name, field_name))
self.renamed_fields[
app_label, model_name, field_name
] = rem_field_name
break
def generate_renamed_fields(self):
"""Generate RenameField operations."""
for (
rem_app_label,
rem_model_name,
rem_db_column,
rem_field_name,
app_label,
model_name,
field,
field_name,
) in self.renamed_operations:
# A db_column mismatch requires a prior noop AlterField for the
# subsequent RenameField to be a noop on attempts at preserving the
# old name.
if rem_db_column != field.db_column:
altered_field = field.clone()
altered_field.name = rem_field_name
self.add_operation(
app_label,
operations.AlterField(
model_name=model_name,
name=rem_field_name,
field=altered_field,
),
)
self.add_operation(
app_label,
operations.RenameField(
model_name=model_name,
old_name=rem_field_name,
new_name=field_name,
),
)
self.old_field_keys.remove((rem_app_label, rem_model_name, rem_field_name))
self.old_field_keys.add((app_label, model_name, field_name))
def generate_added_fields(self):
"""Make AddField operations."""
for app_label, model_name, field_name in sorted(
self.new_field_keys - self.old_field_keys
):
self._generate_added_field(app_label, model_name, field_name)
def _generate_added_field(self, app_label, model_name, field_name):
field = self.to_state.models[app_label, model_name].get_field(field_name)
# Adding a field always depends at least on its removal.
dependencies = [(app_label, model_name, field_name, False)]
# Fields that are foreignkeys/m2ms depend on stuff.
if field.remote_field and field.remote_field.model:
dependencies.extend(
self._get_dependencies_for_foreign_key(
app_label,
model_name,
field,
self.to_state,
)
)
# You can't just add NOT NULL fields with no default or fields
# which don't allow empty strings as default.
time_fields = (models.DateField, models.DateTimeField, models.TimeField)
preserve_default = (
field.null
or field.has_default()
or field.many_to_many
or (field.blank and field.empty_strings_allowed)
or (isinstance(field, time_fields) and field.auto_now)
)
if not preserve_default:
field = field.clone()
if isinstance(field, time_fields) and field.auto_now_add:
field.default = self.questioner.ask_auto_now_add_addition(
field_name, model_name
)
else:
field.default = self.questioner.ask_not_null_addition(
field_name, model_name
)
if (
field.unique
and field.default is not models.NOT_PROVIDED
and callable(field.default)
):
self.questioner.ask_unique_callable_default_addition(field_name, model_name)
self.add_operation(
app_label,
operations.AddField(
model_name=model_name,
name=field_name,
field=field,
preserve_default=preserve_default,
),
dependencies=dependencies,
)
def generate_removed_fields(self):
"""Make RemoveField operations."""
for app_label, model_name, field_name in sorted(
self.old_field_keys - self.new_field_keys
):
self._generate_removed_field(app_label, model_name, field_name)
def _generate_removed_field(self, app_label, model_name, field_name):
self.add_operation(
app_label,
operations.RemoveField(
model_name=model_name,
name=field_name,
),
# We might need to depend on the removal of an
# order_with_respect_to or index/unique_together operation;
# this is safely ignored if there isn't one
dependencies=[
(app_label, model_name, field_name, "order_wrt_unset"),
(app_label, model_name, field_name, "foo_together_change"),
],
)
def generate_altered_fields(self):
"""
Make AlterField operations, or possibly RemovedField/AddField if alter
isn't possible.
"""
for app_label, model_name, field_name in sorted(
self.old_field_keys & self.new_field_keys
):
# Did the field change?
old_model_name = self.renamed_models.get(
(app_label, model_name), model_name
)
old_field_name = self.renamed_fields.get(
(app_label, model_name, field_name), field_name
)
old_field = self.from_state.models[app_label, old_model_name].get_field(
old_field_name
)
new_field = self.to_state.models[app_label, model_name].get_field(
field_name
)
dependencies = []
# Implement any model renames on relations; these are handled by RenameModel
# so we need to exclude them from the comparison
if hasattr(new_field, "remote_field") and getattr(
new_field.remote_field, "model", None
):
rename_key = resolve_relation(
new_field.remote_field.model, app_label, model_name
)
if rename_key in self.renamed_models:
new_field.remote_field.model = old_field.remote_field.model
# Handle ForeignKey which can only have a single to_field.
remote_field_name = getattr(new_field.remote_field, "field_name", None)
if remote_field_name:
to_field_rename_key = rename_key + (remote_field_name,)
if to_field_rename_key in self.renamed_fields:
# Repoint both model and field name because to_field
# inclusion in ForeignKey.deconstruct() is based on
# both.
new_field.remote_field.model = old_field.remote_field.model
new_field.remote_field.field_name = (
old_field.remote_field.field_name
)
# Handle ForeignObjects which can have multiple from_fields/to_fields.
from_fields = getattr(new_field, "from_fields", None)
if from_fields:
from_rename_key = (app_label, model_name)
new_field.from_fields = tuple(
[
self.renamed_fields.get(
from_rename_key + (from_field,), from_field
)
for from_field in from_fields
]
)
new_field.to_fields = tuple(
[
self.renamed_fields.get(rename_key + (to_field,), to_field)
for to_field in new_field.to_fields
]
)
dependencies.extend(
self._get_dependencies_for_foreign_key(
app_label,
model_name,
new_field,
self.to_state,
)
)
if hasattr(new_field, "remote_field") and getattr(
new_field.remote_field, "through", None
):
rename_key = resolve_relation(
new_field.remote_field.through, app_label, model_name
)
if rename_key in self.renamed_models:
new_field.remote_field.through = old_field.remote_field.through
old_field_dec = self.deep_deconstruct(old_field)
new_field_dec = self.deep_deconstruct(new_field)
# If the field was confirmed to be renamed it means that only
# db_column was allowed to change which generate_renamed_fields()
# already accounts for by adding an AlterField operation.
if old_field_dec != new_field_dec and old_field_name == field_name:
both_m2m = old_field.many_to_many and new_field.many_to_many
neither_m2m = not old_field.many_to_many and not new_field.many_to_many
if both_m2m or neither_m2m:
# Either both fields are m2m or neither is
preserve_default = True
if (
old_field.null
and not new_field.null
and not new_field.has_default()
and not new_field.many_to_many
):
field = new_field.clone()
new_default = self.questioner.ask_not_null_alteration(
field_name, model_name
)
if new_default is not models.NOT_PROVIDED:
field.default = new_default
preserve_default = False
else:
field = new_field
self.add_operation(
app_label,
operations.AlterField(
model_name=model_name,
name=field_name,
field=field,
preserve_default=preserve_default,
),
dependencies=dependencies,
)
else:
# We cannot alter between m2m and concrete fields
self._generate_removed_field(app_label, model_name, field_name)
self._generate_added_field(app_label, model_name, field_name)
def create_altered_indexes(self):
option_name = operations.AddIndex.option_name
self.renamed_index_together_values = defaultdict(list)
for app_label, model_name in sorted(self.kept_model_keys):
old_model_name = self.renamed_models.get(
(app_label, model_name), model_name
)
old_model_state = self.from_state.models[app_label, old_model_name]
new_model_state = self.to_state.models[app_label, model_name]
old_indexes = old_model_state.options[option_name]
new_indexes = new_model_state.options[option_name]
added_indexes = [idx for idx in new_indexes if idx not in old_indexes]
removed_indexes = [idx for idx in old_indexes if idx not in new_indexes]
renamed_indexes = []
# Find renamed indexes.
remove_from_added = []
remove_from_removed = []
for new_index in added_indexes:
new_index_dec = new_index.deconstruct()
new_index_name = new_index_dec[2].pop("name")
for old_index in removed_indexes:
old_index_dec = old_index.deconstruct()
old_index_name = old_index_dec[2].pop("name")
# Indexes are the same except for the names.
if (
new_index_dec == old_index_dec
and new_index_name != old_index_name
):
renamed_indexes.append((old_index_name, new_index_name, None))
remove_from_added.append(new_index)
remove_from_removed.append(old_index)
# Find index_together changed to indexes.
for (
old_value,
new_value,
index_together_app_label,
index_together_model_name,
dependencies,
) in self._get_altered_foo_together_operations(
operations.AlterIndexTogether.option_name
):
if (
app_label != index_together_app_label
or model_name != index_together_model_name
):
continue
removed_values = old_value.difference(new_value)
for removed_index_together in removed_values:
renamed_index_together_indexes = []
for new_index in added_indexes:
_, args, kwargs = new_index.deconstruct()
# Ensure only 'fields' are defined in the Index.
if (
not args
and new_index.fields == list(removed_index_together)
and set(kwargs) == {"name", "fields"}
):
renamed_index_together_indexes.append(new_index)
if len(renamed_index_together_indexes) == 1:
renamed_index = renamed_index_together_indexes[0]
remove_from_added.append(renamed_index)
renamed_indexes.append(
(None, renamed_index.name, removed_index_together)
)
self.renamed_index_together_values[
index_together_app_label, index_together_model_name
].append(removed_index_together)
# Remove renamed indexes from the lists of added and removed
# indexes.
added_indexes = [
idx for idx in added_indexes if idx not in remove_from_added
]
removed_indexes = [
idx for idx in removed_indexes if idx not in remove_from_removed
]
self.altered_indexes.update(
{
(app_label, model_name): {
"added_indexes": added_indexes,
"removed_indexes": removed_indexes,
"renamed_indexes": renamed_indexes,
}
}
)
def generate_added_indexes(self):
for (app_label, model_name), alt_indexes in self.altered_indexes.items():
for index in alt_indexes["added_indexes"]:
self.add_operation(
app_label,
operations.AddIndex(
model_name=model_name,
index=index,
),
)
def generate_removed_indexes(self):
for (app_label, model_name), alt_indexes in self.altered_indexes.items():
for index in alt_indexes["removed_indexes"]:
self.add_operation(
app_label,
operations.RemoveIndex(
model_name=model_name,
name=index.name,
),
)
def generate_renamed_indexes(self):
for (app_label, model_name), alt_indexes in self.altered_indexes.items():
for old_index_name, new_index_name, old_fields in alt_indexes[
"renamed_indexes"
]:
self.add_operation(
app_label,
operations.RenameIndex(
model_name=model_name,
new_name=new_index_name,
old_name=old_index_name,
old_fields=old_fields,
),
)
def create_altered_constraints(self):
option_name = operations.AddConstraint.option_name
for app_label, model_name in sorted(self.kept_model_keys):
old_model_name = self.renamed_models.get(
(app_label, model_name), model_name
)
old_model_state = self.from_state.models[app_label, old_model_name]
new_model_state = self.to_state.models[app_label, model_name]
old_constraints = old_model_state.options[option_name]
new_constraints = new_model_state.options[option_name]
add_constraints = [c for c in new_constraints if c not in old_constraints]
rem_constraints = [c for c in old_constraints if c not in new_constraints]
self.altered_constraints.update(
{
(app_label, model_name): {
"added_constraints": add_constraints,
"removed_constraints": rem_constraints,
}
}
)
def generate_added_constraints(self):
for (
app_label,
model_name,
), alt_constraints in self.altered_constraints.items():
for constraint in alt_constraints["added_constraints"]:
self.add_operation(
app_label,
operations.AddConstraint(
model_name=model_name,
constraint=constraint,
),
)
def generate_removed_constraints(self):
for (
app_label,
model_name,
), alt_constraints in self.altered_constraints.items():
for constraint in alt_constraints["removed_constraints"]:
self.add_operation(
app_label,
operations.RemoveConstraint(
model_name=model_name,
name=constraint.name,
),
)
@staticmethod
def _get_dependencies_for_foreign_key(app_label, model_name, field, project_state):
remote_field_model = None
if hasattr(field.remote_field, "model"):
remote_field_model = field.remote_field.model
else:
relations = project_state.relations[app_label, model_name]
for (remote_app_label, remote_model_name), fields in relations.items():
if any(
field == related_field.remote_field
for related_field in fields.values()
):
remote_field_model = f"{remote_app_label}.{remote_model_name}"
break
# Account for FKs to swappable models
swappable_setting = getattr(field, "swappable_setting", None)
if swappable_setting is not None:
dep_app_label = "__setting__"
dep_object_name = swappable_setting
else:
dep_app_label, dep_object_name = resolve_relation(
remote_field_model,
app_label,
model_name,
)
dependencies = [(dep_app_label, dep_object_name, None, True)]
if getattr(field.remote_field, "through", None):
through_app_label, through_object_name = resolve_relation(
remote_field_model,
app_label,
model_name,
)
dependencies.append((through_app_label, through_object_name, None, True))
return dependencies
def _get_altered_foo_together_operations(self, option_name):
for app_label, model_name in sorted(self.kept_model_keys):
old_model_name = self.renamed_models.get(
(app_label, model_name), model_name
)
old_model_state = self.from_state.models[app_label, old_model_name]
new_model_state = self.to_state.models[app_label, model_name]
# We run the old version through the field renames to account for those
old_value = old_model_state.options.get(option_name)
old_value = (
{
tuple(
self.renamed_fields.get((app_label, model_name, n), n)
for n in unique
)
for unique in old_value
}
if old_value
else set()
)
new_value = new_model_state.options.get(option_name)
new_value = set(new_value) if new_value else set()
if old_value != new_value:
dependencies = []
for foo_togethers in new_value:
for field_name in foo_togethers:
field = new_model_state.get_field(field_name)
if field.remote_field and field.remote_field.model:
dependencies.extend(
self._get_dependencies_for_foreign_key(
app_label,
model_name,
field,
self.to_state,
)
)
yield (
old_value,
new_value,
app_label,
model_name,
dependencies,
)
def _generate_removed_altered_foo_together(self, operation):
for (
old_value,
new_value,
app_label,
model_name,
dependencies,
) in self._get_altered_foo_together_operations(operation.option_name):
if operation == operations.AlterIndexTogether:
old_value = {
value
for value in old_value
if value
not in self.renamed_index_together_values[app_label, model_name]
}
removal_value = new_value.intersection(old_value)
if removal_value or old_value:
self.add_operation(
app_label,
operation(
name=model_name, **{operation.option_name: removal_value}
),
dependencies=dependencies,
)
def generate_removed_altered_unique_together(self):
self._generate_removed_altered_foo_together(operations.AlterUniqueTogether)
# RemovedInDjango51Warning.
def generate_removed_altered_index_together(self):
self._generate_removed_altered_foo_together(operations.AlterIndexTogether)
def _generate_altered_foo_together(self, operation):
for (
old_value,
new_value,
app_label,
model_name,
dependencies,
) in self._get_altered_foo_together_operations(operation.option_name):
removal_value = new_value.intersection(old_value)
if new_value != removal_value:
self.add_operation(
app_label,
operation(name=model_name, **{operation.option_name: new_value}),
dependencies=dependencies,
)
def generate_altered_unique_together(self):
self._generate_altered_foo_together(operations.AlterUniqueTogether)
# RemovedInDjango51Warning.
def generate_altered_index_together(self):
self._generate_altered_foo_together(operations.AlterIndexTogether)
def generate_altered_db_table(self):
models_to_check = self.kept_model_keys.union(
self.kept_proxy_keys, self.kept_unmanaged_keys
)
for app_label, model_name in sorted(models_to_check):
old_model_name = self.renamed_models.get(
(app_label, model_name), model_name
)
old_model_state = self.from_state.models[app_label, old_model_name]
new_model_state = self.to_state.models[app_label, model_name]
old_db_table_name = old_model_state.options.get("db_table")
new_db_table_name = new_model_state.options.get("db_table")
if old_db_table_name != new_db_table_name:
self.add_operation(
app_label,
operations.AlterModelTable(
name=model_name,
table=new_db_table_name,
),
)
def generate_altered_options(self):
"""
Work out if any non-schema-affecting options have changed and make an
operation to represent them in state changes (in case Python code in
migrations needs them).
"""
models_to_check = self.kept_model_keys.union(
self.kept_proxy_keys,
self.kept_unmanaged_keys,
# unmanaged converted to managed
self.old_unmanaged_keys & self.new_model_keys,
# managed converted to unmanaged
self.old_model_keys & self.new_unmanaged_keys,
)
for app_label, model_name in sorted(models_to_check):
old_model_name = self.renamed_models.get(
(app_label, model_name), model_name
)
old_model_state = self.from_state.models[app_label, old_model_name]
new_model_state = self.to_state.models[app_label, model_name]
old_options = {
key: value
for key, value in old_model_state.options.items()
if key in AlterModelOptions.ALTER_OPTION_KEYS
}
new_options = {
key: value
for key, value in new_model_state.options.items()
if key in AlterModelOptions.ALTER_OPTION_KEYS
}
if old_options != new_options:
self.add_operation(
app_label,
operations.AlterModelOptions(
name=model_name,
options=new_options,
),
)
def generate_altered_order_with_respect_to(self):
for app_label, model_name in sorted(self.kept_model_keys):
old_model_name = self.renamed_models.get(
(app_label, model_name), model_name
)
old_model_state = self.from_state.models[app_label, old_model_name]
new_model_state = self.to_state.models[app_label, model_name]
if old_model_state.options.get(
"order_with_respect_to"
) != new_model_state.options.get("order_with_respect_to"):
# Make sure it comes second if we're adding
# (removal dependency is part of RemoveField)
dependencies = []
if new_model_state.options.get("order_with_respect_to"):
dependencies.append(
(
app_label,
model_name,
new_model_state.options["order_with_respect_to"],
True,
)
)
# Actually generate the operation
self.add_operation(
app_label,
operations.AlterOrderWithRespectTo(
name=model_name,
order_with_respect_to=new_model_state.options.get(
"order_with_respect_to"
),
),
dependencies=dependencies,
)
def generate_altered_managers(self):
for app_label, model_name in sorted(self.kept_model_keys):
old_model_name = self.renamed_models.get(
(app_label, model_name), model_name
)
old_model_state = self.from_state.models[app_label, old_model_name]
new_model_state = self.to_state.models[app_label, model_name]
if old_model_state.managers != new_model_state.managers:
self.add_operation(
app_label,
operations.AlterModelManagers(
name=model_name,
managers=new_model_state.managers,
),
)
def arrange_for_graph(self, changes, graph, migration_name=None):
"""
Take a result from changes() and a MigrationGraph, and fix the names
and dependencies of the changes so they extend the graph from the leaf
nodes for each app.
"""
leaves = graph.leaf_nodes()
name_map = {}
for app_label, migrations in list(changes.items()):
if not migrations:
continue
# Find the app label's current leaf node
app_leaf = None
for leaf in leaves:
if leaf[0] == app_label:
app_leaf = leaf
break
# Do they want an initial migration for this app?
if app_leaf is None and not self.questioner.ask_initial(app_label):
# They don't.
for migration in migrations:
name_map[(app_label, migration.name)] = (app_label, "__first__")
del changes[app_label]
continue
# Work out the next number in the sequence
if app_leaf is None:
next_number = 1
else:
next_number = (self.parse_number(app_leaf[1]) or 0) + 1
# Name each migration
for i, migration in enumerate(migrations):
if i == 0 and app_leaf:
migration.dependencies.append(app_leaf)
new_name_parts = ["%04i" % next_number]
if migration_name:
new_name_parts.append(migration_name)
elif i == 0 and not app_leaf:
new_name_parts.append("initial")
else:
new_name_parts.append(migration.suggest_name()[:100])
new_name = "_".join(new_name_parts)
name_map[(app_label, migration.name)] = (app_label, new_name)
next_number += 1
migration.name = new_name
# Now fix dependencies
for migrations in changes.values():
for migration in migrations:
migration.dependencies = [
name_map.get(d, d) for d in migration.dependencies
]
return changes
def _trim_to_apps(self, changes, app_labels):
"""
Take changes from arrange_for_graph() and set of app labels, and return
a modified set of changes which trims out as many migrations that are
not in app_labels as possible. Note that some other migrations may
still be present as they may be required dependencies.
"""
# Gather other app dependencies in a first pass
app_dependencies = {}
for app_label, migrations in changes.items():
for migration in migrations:
for dep_app_label, name in migration.dependencies:
app_dependencies.setdefault(app_label, set()).add(dep_app_label)
required_apps = set(app_labels)
# Keep resolving till there's no change
old_required_apps = None
while old_required_apps != required_apps:
old_required_apps = set(required_apps)
required_apps.update(
*[app_dependencies.get(app_label, ()) for app_label in required_apps]
)
# Remove all migrations that aren't needed
for app_label in list(changes):
if app_label not in required_apps:
del changes[app_label]
return changes
@classmethod
def parse_number(cls, name):
"""
Given a migration name, try to extract a number from the beginning of
it. For a squashed migration such as '0001_squashed_0004…', return the
second number. If no number is found, return None.
"""
if squashed_match := re.search(r".*_squashed_(\d+)", name):
return int(squashed_match[1])
match = re.match(r"^\d+", name)
if match:
return int(match[0])
return None
|
52dc71ebd5386be5f078673dacbc145085d2b7380d6fedcc0f6b1aa373f08937 | import bisect
import copy
import inspect
import warnings
from collections import defaultdict
from django.apps import apps
from django.conf import settings
from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured
from django.db import connections
from django.db.models import AutoField, Manager, OrderWrt, UniqueConstraint
from django.db.models.query_utils import PathInfo
from django.utils.datastructures import ImmutableList, OrderedSet
from django.utils.deprecation import RemovedInDjango51Warning
from django.utils.functional import cached_property
from django.utils.module_loading import import_string
from django.utils.text import camel_case_to_spaces, format_lazy
from django.utils.translation import override
PROXY_PARENTS = object()
EMPTY_RELATION_TREE = ()
IMMUTABLE_WARNING = (
"The return type of '%s' should never be mutated. If you want to manipulate this "
"list for your own use, make a copy first."
)
DEFAULT_NAMES = (
"verbose_name",
"verbose_name_plural",
"db_table",
"ordering",
"unique_together",
"permissions",
"get_latest_by",
"order_with_respect_to",
"app_label",
"db_tablespace",
"abstract",
"managed",
"proxy",
"swappable",
"auto_created",
# Must be kept for backward compatibility with old migrations.
"index_together",
"apps",
"default_permissions",
"select_on_save",
"default_related_name",
"required_db_features",
"required_db_vendor",
"base_manager_name",
"default_manager_name",
"indexes",
"constraints",
)
def normalize_together(option_together):
"""
option_together can be either a tuple of tuples, or a single
tuple of two strings. Normalize it to a tuple of tuples, so that
calling code can uniformly expect that.
"""
try:
if not option_together:
return ()
if not isinstance(option_together, (tuple, list)):
raise TypeError
first_element = option_together[0]
if not isinstance(first_element, (tuple, list)):
option_together = (option_together,)
# Normalize everything to tuples
return tuple(tuple(ot) for ot in option_together)
except TypeError:
# If the value of option_together isn't valid, return it
# verbatim; this will be picked up by the check framework later.
return option_together
def make_immutable_fields_list(name, data):
return ImmutableList(data, warning=IMMUTABLE_WARNING % name)
class Options:
FORWARD_PROPERTIES = {
"fields",
"many_to_many",
"concrete_fields",
"local_concrete_fields",
"_forward_fields_map",
"managers",
"managers_map",
"base_manager",
"default_manager",
}
REVERSE_PROPERTIES = {"related_objects", "fields_map", "_relation_tree"}
default_apps = apps
def __init__(self, meta, app_label=None):
self._get_fields_cache = {}
self.local_fields = []
self.local_many_to_many = []
self.private_fields = []
self.local_managers = []
self.base_manager_name = None
self.default_manager_name = None
self.model_name = None
self.verbose_name = None
self.verbose_name_plural = None
self.db_table = ""
self.ordering = []
self._ordering_clash = False
self.indexes = []
self.constraints = []
self.unique_together = []
self.index_together = [] # RemovedInDjango51Warning.
self.select_on_save = False
self.default_permissions = ("add", "change", "delete", "view")
self.permissions = []
self.object_name = None
self.app_label = app_label
self.get_latest_by = None
self.order_with_respect_to = None
self.db_tablespace = settings.DEFAULT_TABLESPACE
self.required_db_features = []
self.required_db_vendor = None
self.meta = meta
self.pk = None
self.auto_field = None
self.abstract = False
self.managed = True
self.proxy = False
# For any class that is a proxy (including automatically created
# classes for deferred object loading), proxy_for_model tells us
# which class this model is proxying. Note that proxy_for_model
# can create a chain of proxy models. For non-proxy models, the
# variable is always None.
self.proxy_for_model = None
# For any non-abstract class, the concrete class is the model
# in the end of the proxy_for_model chain. In particular, for
# concrete models, the concrete_model is always the class itself.
self.concrete_model = None
self.swappable = None
self.parents = {}
self.auto_created = False
# List of all lookups defined in ForeignKey 'limit_choices_to' options
# from *other* models. Needed for some admin checks. Internal use only.
self.related_fkey_lookups = []
# A custom app registry to use, if you're making a separate model set.
self.apps = self.default_apps
self.default_related_name = None
@property
def label(self):
return "%s.%s" % (self.app_label, self.object_name)
@property
def label_lower(self):
return "%s.%s" % (self.app_label, self.model_name)
@property
def app_config(self):
# Don't go through get_app_config to avoid triggering imports.
return self.apps.app_configs.get(self.app_label)
def contribute_to_class(self, cls, name):
from django.db import connection
from django.db.backends.utils import truncate_name
cls._meta = self
self.model = cls
# First, construct the default values for these options.
self.object_name = cls.__name__
self.model_name = self.object_name.lower()
self.verbose_name = camel_case_to_spaces(self.object_name)
# Store the original user-defined values for each option,
# for use when serializing the model definition
self.original_attrs = {}
# Next, apply any overridden values from 'class Meta'.
if self.meta:
meta_attrs = self.meta.__dict__.copy()
for name in self.meta.__dict__:
# Ignore any private attributes that Django doesn't care about.
# NOTE: We can't modify a dictionary's contents while looping
# over it, so we loop over the *original* dictionary instead.
if name.startswith("_"):
del meta_attrs[name]
for attr_name in DEFAULT_NAMES:
if attr_name in meta_attrs:
setattr(self, attr_name, meta_attrs.pop(attr_name))
self.original_attrs[attr_name] = getattr(self, attr_name)
elif hasattr(self.meta, attr_name):
setattr(self, attr_name, getattr(self.meta, attr_name))
self.original_attrs[attr_name] = getattr(self, attr_name)
self.unique_together = normalize_together(self.unique_together)
self.index_together = normalize_together(self.index_together)
if self.index_together:
warnings.warn(
f"'index_together' is deprecated. Use 'Meta.indexes' in "
f"{self.label!r} instead.",
RemovedInDjango51Warning,
)
# App label/class name interpolation for names of constraints and
# indexes.
if not getattr(cls._meta, "abstract", False):
for attr_name in {"constraints", "indexes"}:
objs = getattr(self, attr_name, [])
setattr(self, attr_name, self._format_names_with_class(cls, objs))
# verbose_name_plural is a special case because it uses a 's'
# by default.
if self.verbose_name_plural is None:
self.verbose_name_plural = format_lazy("{}s", self.verbose_name)
# order_with_respect_and ordering are mutually exclusive.
self._ordering_clash = bool(self.ordering and self.order_with_respect_to)
# Any leftover attributes must be invalid.
if meta_attrs != {}:
raise TypeError(
"'class Meta' got invalid attribute(s): %s" % ",".join(meta_attrs)
)
else:
self.verbose_name_plural = format_lazy("{}s", self.verbose_name)
del self.meta
# If the db_table wasn't provided, use the app_label + model_name.
if not self.db_table:
self.db_table = "%s_%s" % (self.app_label, self.model_name)
self.db_table = truncate_name(
self.db_table, connection.ops.max_name_length()
)
def _format_names_with_class(self, cls, objs):
"""App label/class name interpolation for object names."""
new_objs = []
for obj in objs:
obj = obj.clone()
obj.name = obj.name % {
"app_label": cls._meta.app_label.lower(),
"class": cls.__name__.lower(),
}
new_objs.append(obj)
return new_objs
def _get_default_pk_class(self):
pk_class_path = getattr(
self.app_config,
"default_auto_field",
settings.DEFAULT_AUTO_FIELD,
)
if self.app_config and self.app_config._is_default_auto_field_overridden:
app_config_class = type(self.app_config)
source = (
f"{app_config_class.__module__}."
f"{app_config_class.__qualname__}.default_auto_field"
)
else:
source = "DEFAULT_AUTO_FIELD"
if not pk_class_path:
raise ImproperlyConfigured(f"{source} must not be empty.")
try:
pk_class = import_string(pk_class_path)
except ImportError as e:
msg = (
f"{source} refers to the module '{pk_class_path}' that could "
f"not be imported."
)
raise ImproperlyConfigured(msg) from e
if not issubclass(pk_class, AutoField):
raise ValueError(
f"Primary key '{pk_class_path}' referred by {source} must "
f"subclass AutoField."
)
return pk_class
def _prepare(self, model):
if self.order_with_respect_to:
# The app registry will not be ready at this point, so we cannot
# use get_field().
query = self.order_with_respect_to
try:
self.order_with_respect_to = next(
f
for f in self._get_fields(reverse=False)
if f.name == query or f.attname == query
)
except StopIteration:
raise FieldDoesNotExist(
"%s has no field named '%s'" % (self.object_name, query)
)
self.ordering = ("_order",)
if not any(
isinstance(field, OrderWrt) for field in model._meta.local_fields
):
model.add_to_class("_order", OrderWrt())
else:
self.order_with_respect_to = None
if self.pk is None:
if self.parents:
# Promote the first parent link in lieu of adding yet another
# field.
field = next(iter(self.parents.values()))
# Look for a local field with the same name as the
# first parent link. If a local field has already been
# created, use it instead of promoting the parent
already_created = [
fld for fld in self.local_fields if fld.name == field.name
]
if already_created:
field = already_created[0]
field.primary_key = True
self.setup_pk(field)
else:
pk_class = self._get_default_pk_class()
auto = pk_class(verbose_name="ID", primary_key=True, auto_created=True)
model.add_to_class("id", auto)
def add_manager(self, manager):
self.local_managers.append(manager)
self._expire_cache()
def add_field(self, field, private=False):
# Insert the given field in the order in which it was created, using
# the "creation_counter" attribute of the field.
# Move many-to-many related fields from self.fields into
# self.many_to_many.
if private:
self.private_fields.append(field)
elif field.is_relation and field.many_to_many:
bisect.insort(self.local_many_to_many, field)
else:
bisect.insort(self.local_fields, field)
self.setup_pk(field)
# If the field being added is a relation to another known field,
# expire the cache on this field and the forward cache on the field
# being referenced, because there will be new relationships in the
# cache. Otherwise, expire the cache of references *to* this field.
# The mechanism for getting at the related model is slightly odd -
# ideally, we'd just ask for field.related_model. However, related_model
# is a cached property, and all the models haven't been loaded yet, so
# we need to make sure we don't cache a string reference.
if (
field.is_relation
and hasattr(field.remote_field, "model")
and field.remote_field.model
):
try:
field.remote_field.model._meta._expire_cache(forward=False)
except AttributeError:
pass
self._expire_cache()
else:
self._expire_cache(reverse=False)
def setup_pk(self, field):
if not self.pk and field.primary_key:
self.pk = field
field.serialize = False
def setup_proxy(self, target):
"""
Do the internal setup so that the current model is a proxy for
"target".
"""
self.pk = target._meta.pk
self.proxy_for_model = target
self.db_table = target._meta.db_table
def __repr__(self):
return "<Options for %s>" % self.object_name
def __str__(self):
return self.label_lower
def can_migrate(self, connection):
"""
Return True if the model can/should be migrated on the `connection`.
`connection` can be either a real connection or a connection alias.
"""
if self.proxy or self.swapped or not self.managed:
return False
if isinstance(connection, str):
connection = connections[connection]
if self.required_db_vendor:
return self.required_db_vendor == connection.vendor
if self.required_db_features:
return all(
getattr(connection.features, feat, False)
for feat in self.required_db_features
)
return True
@property
def verbose_name_raw(self):
"""Return the untranslated verbose name."""
with override(None):
return str(self.verbose_name)
@property
def swapped(self):
"""
Has this model been swapped out for another? If so, return the model
name of the replacement; otherwise, return None.
For historical reasons, model name lookups using get_model() are
case insensitive, so we make sure we are case insensitive here.
"""
if self.swappable:
swapped_for = getattr(settings, self.swappable, None)
if swapped_for:
try:
swapped_label, swapped_object = swapped_for.split(".")
except ValueError:
# setting not in the format app_label.model_name
# raising ImproperlyConfigured here causes problems with
# test cleanup code - instead it is raised in get_user_model
# or as part of validation.
return swapped_for
if (
"%s.%s" % (swapped_label, swapped_object.lower())
!= self.label_lower
):
return swapped_for
return None
@cached_property
def managers(self):
managers = []
seen_managers = set()
bases = (b for b in self.model.mro() if hasattr(b, "_meta"))
for depth, base in enumerate(bases):
for manager in base._meta.local_managers:
if manager.name in seen_managers:
continue
manager = copy.copy(manager)
manager.model = self.model
seen_managers.add(manager.name)
managers.append((depth, manager.creation_counter, manager))
return make_immutable_fields_list(
"managers",
(m[2] for m in sorted(managers)),
)
@cached_property
def managers_map(self):
return {manager.name: manager for manager in self.managers}
@cached_property
def base_manager(self):
base_manager_name = self.base_manager_name
if not base_manager_name:
# Get the first parent's base_manager_name if there's one.
for parent in self.model.mro()[1:]:
if hasattr(parent, "_meta"):
if parent._base_manager.name != "_base_manager":
base_manager_name = parent._base_manager.name
break
if base_manager_name:
try:
return self.managers_map[base_manager_name]
except KeyError:
raise ValueError(
"%s has no manager named %r"
% (
self.object_name,
base_manager_name,
)
)
manager = Manager()
manager.name = "_base_manager"
manager.model = self.model
manager.auto_created = True
return manager
@cached_property
def default_manager(self):
default_manager_name = self.default_manager_name
if not default_manager_name and not self.local_managers:
# Get the first parent's default_manager_name if there's one.
for parent in self.model.mro()[1:]:
if hasattr(parent, "_meta"):
default_manager_name = parent._meta.default_manager_name
break
if default_manager_name:
try:
return self.managers_map[default_manager_name]
except KeyError:
raise ValueError(
"%s has no manager named %r"
% (
self.object_name,
default_manager_name,
)
)
if self.managers:
return self.managers[0]
@cached_property
def fields(self):
"""
Return a list of all forward fields on the model and its parents,
excluding ManyToManyFields.
Private API intended only to be used by Django itself; get_fields()
combined with filtering of field properties is the public API for
obtaining this field list.
"""
# For legacy reasons, the fields property should only contain forward
# fields that are not private or with a m2m cardinality. Therefore we
# pass these three filters as filters to the generator.
# The third lambda is a longwinded way of checking f.related_model - we don't
# use that property directly because related_model is a cached property,
# and all the models may not have been loaded yet; we don't want to cache
# the string reference to the related_model.
def is_not_an_m2m_field(f):
return not (f.is_relation and f.many_to_many)
def is_not_a_generic_relation(f):
return not (f.is_relation and f.one_to_many)
def is_not_a_generic_foreign_key(f):
return not (
f.is_relation
and f.many_to_one
and not (hasattr(f.remote_field, "model") and f.remote_field.model)
)
return make_immutable_fields_list(
"fields",
(
f
for f in self._get_fields(reverse=False)
if is_not_an_m2m_field(f)
and is_not_a_generic_relation(f)
and is_not_a_generic_foreign_key(f)
),
)
@cached_property
def concrete_fields(self):
"""
Return a list of all concrete fields on the model and its parents.
Private API intended only to be used by Django itself; get_fields()
combined with filtering of field properties is the public API for
obtaining this field list.
"""
return make_immutable_fields_list(
"concrete_fields", (f for f in self.fields if f.concrete)
)
@cached_property
def local_concrete_fields(self):
"""
Return a list of all concrete fields on the model.
Private API intended only to be used by Django itself; get_fields()
combined with filtering of field properties is the public API for
obtaining this field list.
"""
return make_immutable_fields_list(
"local_concrete_fields", (f for f in self.local_fields if f.concrete)
)
@cached_property
def many_to_many(self):
"""
Return a list of all many to many fields on the model and its parents.
Private API intended only to be used by Django itself; get_fields()
combined with filtering of field properties is the public API for
obtaining this list.
"""
return make_immutable_fields_list(
"many_to_many",
(
f
for f in self._get_fields(reverse=False)
if f.is_relation and f.many_to_many
),
)
@cached_property
def related_objects(self):
"""
Return all related objects pointing to the current model. The related
objects can come from a one-to-one, one-to-many, or many-to-many field
relation type.
Private API intended only to be used by Django itself; get_fields()
combined with filtering of field properties is the public API for
obtaining this field list.
"""
all_related_fields = self._get_fields(
forward=False, reverse=True, include_hidden=True
)
return make_immutable_fields_list(
"related_objects",
(
obj
for obj in all_related_fields
if not obj.hidden or obj.field.many_to_many
),
)
@cached_property
def _forward_fields_map(self):
res = {}
fields = self._get_fields(reverse=False)
for field in fields:
res[field.name] = field
# Due to the way Django's internals work, get_field() should also
# be able to fetch a field by attname. In the case of a concrete
# field with relation, includes the *_id name too
try:
res[field.attname] = field
except AttributeError:
pass
return res
@cached_property
def fields_map(self):
res = {}
fields = self._get_fields(forward=False, include_hidden=True)
for field in fields:
res[field.name] = field
# Due to the way Django's internals work, get_field() should also
# be able to fetch a field by attname. In the case of a concrete
# field with relation, includes the *_id name too
try:
res[field.attname] = field
except AttributeError:
pass
return res
def get_field(self, field_name):
"""
Return a field instance given the name of a forward or reverse field.
"""
try:
# In order to avoid premature loading of the relation tree
# (expensive) we prefer checking if the field is a forward field.
return self._forward_fields_map[field_name]
except KeyError:
# If the app registry is not ready, reverse fields are
# unavailable, therefore we throw a FieldDoesNotExist exception.
if not self.apps.models_ready:
raise FieldDoesNotExist(
"%s has no field named '%s'. The app cache isn't ready yet, "
"so if this is an auto-created related field, it won't "
"be available yet." % (self.object_name, field_name)
)
try:
# Retrieve field instance by name from cached or just-computed
# field map.
return self.fields_map[field_name]
except KeyError:
raise FieldDoesNotExist(
"%s has no field named '%s'" % (self.object_name, field_name)
)
def get_base_chain(self, model):
"""
Return a list of parent classes leading to `model` (ordered from
closest to most distant ancestor). This has to handle the case where
`model` is a grandparent or even more distant relation.
"""
if not self.parents:
return []
if model in self.parents:
return [model]
for parent in self.parents:
res = parent._meta.get_base_chain(model)
if res:
res.insert(0, parent)
return res
return []
def get_parent_list(self):
"""
Return all the ancestors of this model as a list ordered by MRO.
Useful for determining if something is an ancestor, regardless of lineage.
"""
result = OrderedSet(self.parents)
for parent in self.parents:
for ancestor in parent._meta.get_parent_list():
result.add(ancestor)
return list(result)
def get_ancestor_link(self, ancestor):
"""
Return the field on the current model which points to the given
"ancestor". This is possible an indirect link (a pointer to a parent
model, which points, eventually, to the ancestor). Used when
constructing table joins for model inheritance.
Return None if the model isn't an ancestor of this one.
"""
if ancestor in self.parents:
return self.parents[ancestor]
for parent in self.parents:
# Tries to get a link field from the immediate parent
parent_link = parent._meta.get_ancestor_link(ancestor)
if parent_link:
# In case of a proxied model, the first link
# of the chain to the ancestor is that parent
# links
return self.parents[parent] or parent_link
def get_path_to_parent(self, parent):
"""
Return a list of PathInfos containing the path from the current
model to the parent model, or an empty list if parent is not a
parent of the current model.
"""
if self.model is parent:
return []
# Skip the chain of proxy to the concrete proxied model.
proxied_model = self.concrete_model
path = []
opts = self
for int_model in self.get_base_chain(parent):
if int_model is proxied_model:
opts = int_model._meta
else:
final_field = opts.parents[int_model]
targets = (final_field.remote_field.get_related_field(),)
opts = int_model._meta
path.append(
PathInfo(
from_opts=final_field.model._meta,
to_opts=opts,
target_fields=targets,
join_field=final_field,
m2m=False,
direct=True,
filtered_relation=None,
)
)
return path
def get_path_from_parent(self, parent):
"""
Return a list of PathInfos containing the path from the parent
model to the current model, or an empty list if parent is not a
parent of the current model.
"""
if self.model is parent:
return []
model = self.concrete_model
# Get a reversed base chain including both the current and parent
# models.
chain = model._meta.get_base_chain(parent)
chain.reverse()
chain.append(model)
# Construct a list of the PathInfos between models in chain.
path = []
for i, ancestor in enumerate(chain[:-1]):
child = chain[i + 1]
link = child._meta.get_ancestor_link(ancestor)
path.extend(link.reverse_path_infos)
return path
def _populate_directed_relation_graph(self):
"""
This method is used by each model to find its reverse objects. As this
method is very expensive and is accessed frequently (it looks up every
field in a model, in every app), it is computed on first access and then
is set as a property on every model.
"""
related_objects_graph = defaultdict(list)
all_models = self.apps.get_models(include_auto_created=True)
for model in all_models:
opts = model._meta
# Abstract model's fields are copied to child models, hence we will
# see the fields from the child models.
if opts.abstract:
continue
fields_with_relations = (
f
for f in opts._get_fields(reverse=False, include_parents=False)
if f.is_relation and f.related_model is not None
)
for f in fields_with_relations:
if not isinstance(f.remote_field.model, str):
remote_label = f.remote_field.model._meta.concrete_model._meta.label
related_objects_graph[remote_label].append(f)
for model in all_models:
# Set the relation_tree using the internal __dict__. In this way
# we avoid calling the cached property. In attribute lookup,
# __dict__ takes precedence over a data descriptor (such as
# @cached_property). This means that the _meta._relation_tree is
# only called if related_objects is not in __dict__.
related_objects = related_objects_graph[
model._meta.concrete_model._meta.label
]
model._meta.__dict__["_relation_tree"] = related_objects
# It seems it is possible that self is not in all_models, so guard
# against that with default for get().
return self.__dict__.get("_relation_tree", EMPTY_RELATION_TREE)
@cached_property
def _relation_tree(self):
return self._populate_directed_relation_graph()
def _expire_cache(self, forward=True, reverse=True):
# This method is usually called by apps.cache_clear(), when the
# registry is finalized, or when a new field is added.
if forward:
for cache_key in self.FORWARD_PROPERTIES:
if cache_key in self.__dict__:
delattr(self, cache_key)
if reverse and not self.abstract:
for cache_key in self.REVERSE_PROPERTIES:
if cache_key in self.__dict__:
delattr(self, cache_key)
self._get_fields_cache = {}
def get_fields(self, include_parents=True, include_hidden=False):
"""
Return a list of fields associated to the model. By default, include
forward and reverse fields, fields derived from inheritance, but not
hidden fields. The returned fields can be changed using the parameters:
- include_parents: include fields derived from inheritance
- include_hidden: include fields that have a related_name that
starts with a "+"
"""
if include_parents is False:
include_parents = PROXY_PARENTS
return self._get_fields(
include_parents=include_parents, include_hidden=include_hidden
)
def _get_fields(
self,
forward=True,
reverse=True,
include_parents=True,
include_hidden=False,
seen_models=None,
):
"""
Internal helper function to return fields of the model.
* If forward=True, then fields defined on this model are returned.
* If reverse=True, then relations pointing to this model are returned.
* If include_hidden=True, then fields with is_hidden=True are returned.
* The include_parents argument toggles if fields from parent models
should be included. It has three values: True, False, and
PROXY_PARENTS. When set to PROXY_PARENTS, the call will return all
fields defined for the current model or any of its parents in the
parent chain to the model's concrete model.
"""
if include_parents not in (True, False, PROXY_PARENTS):
raise TypeError(
"Invalid argument for include_parents: %s" % (include_parents,)
)
# This helper function is used to allow recursion in ``get_fields()``
# implementation and to provide a fast way for Django's internals to
# access specific subsets of fields.
# We must keep track of which models we have already seen. Otherwise we
# could include the same field multiple times from different models.
topmost_call = seen_models is None
if topmost_call:
seen_models = set()
seen_models.add(self.model)
# Creates a cache key composed of all arguments
cache_key = (forward, reverse, include_parents, include_hidden, topmost_call)
try:
# In order to avoid list manipulation. Always return a shallow copy
# of the results.
return self._get_fields_cache[cache_key]
except KeyError:
pass
fields = []
# Recursively call _get_fields() on each parent, with the same
# options provided in this call.
if include_parents is not False:
for parent in self.parents:
# In diamond inheritance it is possible that we see the same
# model from two different routes. In that case, avoid adding
# fields from the same parent again.
if parent in seen_models:
continue
if (
parent._meta.concrete_model != self.concrete_model
and include_parents == PROXY_PARENTS
):
continue
for obj in parent._meta._get_fields(
forward=forward,
reverse=reverse,
include_parents=include_parents,
include_hidden=include_hidden,
seen_models=seen_models,
):
if (
not getattr(obj, "parent_link", False)
or obj.model == self.concrete_model
):
fields.append(obj)
if reverse and not self.proxy:
# Tree is computed once and cached until the app cache is expired.
# It is composed of a list of fields pointing to the current model
# from other models.
all_fields = self._relation_tree
for field in all_fields:
# If hidden fields should be included or the relation is not
# intentionally hidden, add to the fields dict.
if include_hidden or not field.remote_field.hidden:
fields.append(field.remote_field)
if forward:
fields += self.local_fields
fields += self.local_many_to_many
# Private fields are recopied to each child model, and they get a
# different model as field.model in each child. Hence we have to
# add the private fields separately from the topmost call. If we
# did this recursively similar to local_fields, we would get field
# instances with field.model != self.model.
if topmost_call:
fields += self.private_fields
# In order to avoid list manipulation. Always
# return a shallow copy of the results
fields = make_immutable_fields_list("get_fields()", fields)
# Store result into cache for later access
self._get_fields_cache[cache_key] = fields
return fields
@cached_property
def total_unique_constraints(self):
"""
Return a list of total unique constraints. Useful for determining set
of fields guaranteed to be unique for all rows.
"""
return [
constraint
for constraint in self.constraints
if (
isinstance(constraint, UniqueConstraint)
and constraint.condition is None
and not constraint.contains_expressions
)
]
@cached_property
def _property_names(self):
"""Return a set of the names of the properties defined on the model."""
names = []
for name in dir(self.model):
attr = inspect.getattr_static(self.model, name)
if isinstance(attr, property):
names.append(name)
return frozenset(names)
@cached_property
def db_returning_fields(self):
"""
Private API intended only to be used by Django itself.
Fields to be returned after a database insert.
"""
return [
field
for field in self._get_fields(
forward=True, reverse=False, include_parents=PROXY_PARENTS
)
if getattr(field, "db_returning", False)
]
|
071e9bb633dc68b1920803ab318325ec16f06914fa9cfe5055f99ba12789024a | import copy
import inspect
import warnings
from functools import partialmethod
from itertools import chain
import django
from django.apps import apps
from django.conf import settings
from django.core import checks
from django.core.exceptions import (
NON_FIELD_ERRORS,
FieldDoesNotExist,
FieldError,
MultipleObjectsReturned,
ObjectDoesNotExist,
ValidationError,
)
from django.db import (
DJANGO_VERSION_PICKLE_KEY,
DatabaseError,
connection,
connections,
router,
transaction,
)
from django.db.models import NOT_PROVIDED, ExpressionWrapper, IntegerField, Max, Value
from django.db.models.constants import LOOKUP_SEP
from django.db.models.constraints import CheckConstraint, UniqueConstraint
from django.db.models.deletion import CASCADE, Collector
from django.db.models.expressions import RawSQL
from django.db.models.fields.related import (
ForeignObjectRel,
OneToOneField,
lazy_related_operation,
resolve_relation,
)
from django.db.models.functions import Coalesce
from django.db.models.manager import Manager
from django.db.models.options import Options
from django.db.models.query import F, Q
from django.db.models.signals import (
class_prepared,
post_init,
post_save,
pre_init,
pre_save,
)
from django.db.models.utils import make_model_tuple
from django.utils.encoding import force_str
from django.utils.hashable import make_hashable
from django.utils.text import capfirst, get_text_list
from django.utils.translation import gettext_lazy as _
class Deferred:
def __repr__(self):
return "<Deferred field>"
def __str__(self):
return "<Deferred field>"
DEFERRED = Deferred()
def subclass_exception(name, bases, module, attached_to):
"""
Create exception subclass. Used by ModelBase below.
The exception is created in a way that allows it to be pickled, assuming
that the returned exception class will be added as an attribute to the
'attached_to' class.
"""
return type(
name,
bases,
{
"__module__": module,
"__qualname__": "%s.%s" % (attached_to.__qualname__, name),
},
)
def _has_contribute_to_class(value):
# Only call contribute_to_class() if it's bound.
return not inspect.isclass(value) and hasattr(value, "contribute_to_class")
class ModelBase(type):
"""Metaclass for all models."""
def __new__(cls, name, bases, attrs, **kwargs):
super_new = super().__new__
# Also ensure initialization is only performed for subclasses of Model
# (excluding Model class itself).
parents = [b for b in bases if isinstance(b, ModelBase)]
if not parents:
return super_new(cls, name, bases, attrs)
# Create the class.
module = attrs.pop("__module__")
new_attrs = {"__module__": module}
classcell = attrs.pop("__classcell__", None)
if classcell is not None:
new_attrs["__classcell__"] = classcell
attr_meta = attrs.pop("Meta", None)
# Pass all attrs without a (Django-specific) contribute_to_class()
# method to type.__new__() so that they're properly initialized
# (i.e. __set_name__()).
contributable_attrs = {}
for obj_name, obj in attrs.items():
if _has_contribute_to_class(obj):
contributable_attrs[obj_name] = obj
else:
new_attrs[obj_name] = obj
new_class = super_new(cls, name, bases, new_attrs, **kwargs)
abstract = getattr(attr_meta, "abstract", False)
meta = attr_meta or getattr(new_class, "Meta", None)
base_meta = getattr(new_class, "_meta", None)
app_label = None
# Look for an application configuration to attach the model to.
app_config = apps.get_containing_app_config(module)
if getattr(meta, "app_label", None) is None:
if app_config is None:
if not abstract:
raise RuntimeError(
"Model class %s.%s doesn't declare an explicit "
"app_label and isn't in an application in "
"INSTALLED_APPS." % (module, name)
)
else:
app_label = app_config.label
new_class.add_to_class("_meta", Options(meta, app_label))
if not abstract:
new_class.add_to_class(
"DoesNotExist",
subclass_exception(
"DoesNotExist",
tuple(
x.DoesNotExist
for x in parents
if hasattr(x, "_meta") and not x._meta.abstract
)
or (ObjectDoesNotExist,),
module,
attached_to=new_class,
),
)
new_class.add_to_class(
"MultipleObjectsReturned",
subclass_exception(
"MultipleObjectsReturned",
tuple(
x.MultipleObjectsReturned
for x in parents
if hasattr(x, "_meta") and not x._meta.abstract
)
or (MultipleObjectsReturned,),
module,
attached_to=new_class,
),
)
if base_meta and not base_meta.abstract:
# Non-abstract child classes inherit some attributes from their
# non-abstract parent (unless an ABC comes before it in the
# method resolution order).
if not hasattr(meta, "ordering"):
new_class._meta.ordering = base_meta.ordering
if not hasattr(meta, "get_latest_by"):
new_class._meta.get_latest_by = base_meta.get_latest_by
is_proxy = new_class._meta.proxy
# If the model is a proxy, ensure that the base class
# hasn't been swapped out.
if is_proxy and base_meta and base_meta.swapped:
raise TypeError(
"%s cannot proxy the swapped model '%s'." % (name, base_meta.swapped)
)
# Add remaining attributes (those with a contribute_to_class() method)
# to the class.
for obj_name, obj in contributable_attrs.items():
new_class.add_to_class(obj_name, obj)
# All the fields of any type declared on this model
new_fields = chain(
new_class._meta.local_fields,
new_class._meta.local_many_to_many,
new_class._meta.private_fields,
)
field_names = {f.name for f in new_fields}
# Basic setup for proxy models.
if is_proxy:
base = None
for parent in [kls for kls in parents if hasattr(kls, "_meta")]:
if parent._meta.abstract:
if parent._meta.fields:
raise TypeError(
"Abstract base class containing model fields not "
"permitted for proxy model '%s'." % name
)
else:
continue
if base is None:
base = parent
elif parent._meta.concrete_model is not base._meta.concrete_model:
raise TypeError(
"Proxy model '%s' has more than one non-abstract model base "
"class." % name
)
if base is None:
raise TypeError(
"Proxy model '%s' has no non-abstract model base class." % name
)
new_class._meta.setup_proxy(base)
new_class._meta.concrete_model = base._meta.concrete_model
else:
new_class._meta.concrete_model = new_class
# Collect the parent links for multi-table inheritance.
parent_links = {}
for base in reversed([new_class] + parents):
# Conceptually equivalent to `if base is Model`.
if not hasattr(base, "_meta"):
continue
# Skip concrete parent classes.
if base != new_class and not base._meta.abstract:
continue
# Locate OneToOneField instances.
for field in base._meta.local_fields:
if isinstance(field, OneToOneField) and field.remote_field.parent_link:
related = resolve_relation(new_class, field.remote_field.model)
parent_links[make_model_tuple(related)] = field
# Track fields inherited from base models.
inherited_attributes = set()
# Do the appropriate setup for any model parents.
for base in new_class.mro():
if base not in parents or not hasattr(base, "_meta"):
# Things without _meta aren't functional models, so they're
# uninteresting parents.
inherited_attributes.update(base.__dict__)
continue
parent_fields = base._meta.local_fields + base._meta.local_many_to_many
if not base._meta.abstract:
# Check for clashes between locally declared fields and those
# on the base classes.
for field in parent_fields:
if field.name in field_names:
raise FieldError(
"Local field %r in class %r clashes with field of "
"the same name from base class %r."
% (
field.name,
name,
base.__name__,
)
)
else:
inherited_attributes.add(field.name)
# Concrete classes...
base = base._meta.concrete_model
base_key = make_model_tuple(base)
if base_key in parent_links:
field = parent_links[base_key]
elif not is_proxy:
attr_name = "%s_ptr" % base._meta.model_name
field = OneToOneField(
base,
on_delete=CASCADE,
name=attr_name,
auto_created=True,
parent_link=True,
)
if attr_name in field_names:
raise FieldError(
"Auto-generated field '%s' in class %r for "
"parent_link to base class %r clashes with "
"declared field of the same name."
% (
attr_name,
name,
base.__name__,
)
)
# Only add the ptr field if it's not already present;
# e.g. migrations will already have it specified
if not hasattr(new_class, attr_name):
new_class.add_to_class(attr_name, field)
else:
field = None
new_class._meta.parents[base] = field
else:
base_parents = base._meta.parents.copy()
# Add fields from abstract base class if it wasn't overridden.
for field in parent_fields:
if (
field.name not in field_names
and field.name not in new_class.__dict__
and field.name not in inherited_attributes
):
new_field = copy.deepcopy(field)
new_class.add_to_class(field.name, new_field)
# Replace parent links defined on this base by the new
# field. It will be appropriately resolved if required.
if field.one_to_one:
for parent, parent_link in base_parents.items():
if field == parent_link:
base_parents[parent] = new_field
# Pass any non-abstract parent classes onto child.
new_class._meta.parents.update(base_parents)
# Inherit private fields (like GenericForeignKey) from the parent
# class
for field in base._meta.private_fields:
if field.name in field_names:
if not base._meta.abstract:
raise FieldError(
"Local field %r in class %r clashes with field of "
"the same name from base class %r."
% (
field.name,
name,
base.__name__,
)
)
else:
field = copy.deepcopy(field)
if not base._meta.abstract:
field.mti_inherited = True
new_class.add_to_class(field.name, field)
# Copy indexes so that index names are unique when models extend an
# abstract model.
new_class._meta.indexes = [
copy.deepcopy(idx) for idx in new_class._meta.indexes
]
if abstract:
# Abstract base models can't be instantiated and don't appear in
# the list of models for an app. We do the final setup for them a
# little differently from normal models.
attr_meta.abstract = False
new_class.Meta = attr_meta
return new_class
new_class._prepare()
new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
return new_class
def add_to_class(cls, name, value):
if _has_contribute_to_class(value):
value.contribute_to_class(cls, name)
else:
setattr(cls, name, value)
def _prepare(cls):
"""Create some methods once self._meta has been populated."""
opts = cls._meta
opts._prepare(cls)
if opts.order_with_respect_to:
cls.get_next_in_order = partialmethod(
cls._get_next_or_previous_in_order, is_next=True
)
cls.get_previous_in_order = partialmethod(
cls._get_next_or_previous_in_order, is_next=False
)
# Defer creating accessors on the foreign class until it has been
# created and registered. If remote_field is None, we're ordering
# with respect to a GenericForeignKey and don't know what the
# foreign class is - we'll add those accessors later in
# contribute_to_class().
if opts.order_with_respect_to.remote_field:
wrt = opts.order_with_respect_to
remote = wrt.remote_field.model
lazy_related_operation(make_foreign_order_accessors, cls, remote)
# Give the class a docstring -- its definition.
if cls.__doc__ is None:
cls.__doc__ = "%s(%s)" % (
cls.__name__,
", ".join(f.name for f in opts.fields),
)
get_absolute_url_override = settings.ABSOLUTE_URL_OVERRIDES.get(
opts.label_lower
)
if get_absolute_url_override:
setattr(cls, "get_absolute_url", get_absolute_url_override)
if not opts.managers:
if any(f.name == "objects" for f in opts.fields):
raise ValueError(
"Model %s must specify a custom Manager, because it has a "
"field named 'objects'." % cls.__name__
)
manager = Manager()
manager.auto_created = True
cls.add_to_class("objects", manager)
# Set the name of _meta.indexes. This can't be done in
# Options.contribute_to_class() because fields haven't been added to
# the model at that point.
for index in cls._meta.indexes:
if not index.name:
index.set_name_with_model(cls)
class_prepared.send(sender=cls)
@property
def _base_manager(cls):
return cls._meta.base_manager
@property
def _default_manager(cls):
return cls._meta.default_manager
class ModelStateCacheDescriptor:
"""
Upon first access, replace itself with an empty dictionary on the instance.
"""
def __set_name__(self, owner, name):
self.attribute_name = name
def __get__(self, instance, cls=None):
if instance is None:
return self
res = instance.__dict__[self.attribute_name] = {}
return res
class ModelState:
"""Store model instance state."""
db = None
# If true, uniqueness validation checks will consider this a new, unsaved
# object. Necessary for correct validation of new instances of objects with
# explicit (non-auto) PKs. This impacts validation only; it has no effect
# on the actual save.
adding = True
fields_cache = ModelStateCacheDescriptor()
related_managers_cache = ModelStateCacheDescriptor()
def __getstate__(self):
state = self.__dict__.copy()
if "fields_cache" in state:
state["fields_cache"] = self.fields_cache.copy()
# Manager instances stored in related_managers_cache won't necessarily
# be deserializable if they were dynamically created via an inner
# scope, e.g. create_forward_many_to_many_manager() and
# create_generic_related_manager().
if "related_managers_cache" in state:
state["related_managers_cache"] = {}
return state
class Model(metaclass=ModelBase):
def __init__(self, *args, **kwargs):
# Alias some things as locals to avoid repeat global lookups
cls = self.__class__
opts = self._meta
_setattr = setattr
_DEFERRED = DEFERRED
if opts.abstract:
raise TypeError("Abstract models cannot be instantiated.")
pre_init.send(sender=cls, args=args, kwargs=kwargs)
# Set up the storage for instance state
self._state = ModelState()
# There is a rather weird disparity here; if kwargs, it's set, then args
# overrides it. It should be one or the other; don't duplicate the work
# The reason for the kwargs check is that standard iterator passes in by
# args, and instantiation for iteration is 33% faster.
if len(args) > len(opts.concrete_fields):
# Daft, but matches old exception sans the err msg.
raise IndexError("Number of args exceeds number of fields")
if not kwargs:
fields_iter = iter(opts.concrete_fields)
# The ordering of the zip calls matter - zip throws StopIteration
# when an iter throws it. So if the first iter throws it, the second
# is *not* consumed. We rely on this, so don't change the order
# without changing the logic.
for val, field in zip(args, fields_iter):
if val is _DEFERRED:
continue
_setattr(self, field.attname, val)
else:
# Slower, kwargs-ready version.
fields_iter = iter(opts.fields)
for val, field in zip(args, fields_iter):
if val is _DEFERRED:
continue
_setattr(self, field.attname, val)
if kwargs.pop(field.name, NOT_PROVIDED) is not NOT_PROVIDED:
raise TypeError(
f"{cls.__qualname__}() got both positional and "
f"keyword arguments for field '{field.name}'."
)
# Now we're left with the unprocessed fields that *must* come from
# keywords, or default.
for field in fields_iter:
is_related_object = False
# Virtual field
if field.attname not in kwargs and field.column is None:
continue
if kwargs:
if isinstance(field.remote_field, ForeignObjectRel):
try:
# Assume object instance was passed in.
rel_obj = kwargs.pop(field.name)
is_related_object = True
except KeyError:
try:
# Object instance wasn't passed in -- must be an ID.
val = kwargs.pop(field.attname)
except KeyError:
val = field.get_default()
else:
try:
val = kwargs.pop(field.attname)
except KeyError:
# This is done with an exception rather than the
# default argument on pop because we don't want
# get_default() to be evaluated, and then not used.
# Refs #12057.
val = field.get_default()
else:
val = field.get_default()
if is_related_object:
# If we are passed a related instance, set it using the
# field.name instead of field.attname (e.g. "user" instead of
# "user_id") so that the object gets properly cached (and type
# checked) by the RelatedObjectDescriptor.
if rel_obj is not _DEFERRED:
_setattr(self, field.name, rel_obj)
else:
if val is not _DEFERRED:
_setattr(self, field.attname, val)
if kwargs:
property_names = opts._property_names
unexpected = ()
for prop, value in kwargs.items():
# Any remaining kwargs must correspond to properties or virtual
# fields.
if prop in property_names:
if value is not _DEFERRED:
_setattr(self, prop, value)
else:
try:
opts.get_field(prop)
except FieldDoesNotExist:
unexpected += (prop,)
else:
if value is not _DEFERRED:
_setattr(self, prop, value)
if unexpected:
unexpected_names = ", ".join(repr(n) for n in unexpected)
raise TypeError(
f"{cls.__name__}() got unexpected keyword arguments: "
f"{unexpected_names}"
)
super().__init__()
post_init.send(sender=cls, instance=self)
@classmethod
def from_db(cls, db, field_names, values):
if len(values) != len(cls._meta.concrete_fields):
values_iter = iter(values)
values = [
next(values_iter) if f.attname in field_names else DEFERRED
for f in cls._meta.concrete_fields
]
new = cls(*values)
new._state.adding = False
new._state.db = db
return new
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self)
def __str__(self):
return "%s object (%s)" % (self.__class__.__name__, self.pk)
def __eq__(self, other):
if not isinstance(other, Model):
return NotImplemented
if self._meta.concrete_model != other._meta.concrete_model:
return False
my_pk = self.pk
if my_pk is None:
return self is other
return my_pk == other.pk
def __hash__(self):
if self.pk is None:
raise TypeError("Model instances without primary key value are unhashable")
return hash(self.pk)
def __reduce__(self):
data = self.__getstate__()
data[DJANGO_VERSION_PICKLE_KEY] = django.__version__
class_id = self._meta.app_label, self._meta.object_name
return model_unpickle, (class_id,), data
def __getstate__(self):
"""Hook to allow choosing the attributes to pickle."""
state = self.__dict__.copy()
state["_state"] = copy.copy(state["_state"])
# memoryview cannot be pickled, so cast it to bytes and store
# separately.
_memoryview_attrs = []
for attr, value in state.items():
if isinstance(value, memoryview):
_memoryview_attrs.append((attr, bytes(value)))
if _memoryview_attrs:
state["_memoryview_attrs"] = _memoryview_attrs
for attr, value in _memoryview_attrs:
state.pop(attr)
return state
def __setstate__(self, state):
pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)
if pickled_version:
if pickled_version != django.__version__:
warnings.warn(
"Pickled model instance's Django version %s does not "
"match the current version %s."
% (pickled_version, django.__version__),
RuntimeWarning,
stacklevel=2,
)
else:
warnings.warn(
"Pickled model instance's Django version is not specified.",
RuntimeWarning,
stacklevel=2,
)
if "_memoryview_attrs" in state:
for attr, value in state.pop("_memoryview_attrs"):
state[attr] = memoryview(value)
self.__dict__.update(state)
def _get_pk_val(self, meta=None):
meta = meta or self._meta
return getattr(self, meta.pk.attname)
def _set_pk_val(self, value):
for parent_link in self._meta.parents.values():
if parent_link and parent_link != self._meta.pk:
setattr(self, parent_link.target_field.attname, value)
return setattr(self, self._meta.pk.attname, value)
pk = property(_get_pk_val, _set_pk_val)
def get_deferred_fields(self):
"""
Return a set containing names of deferred fields for this instance.
"""
return {
f.attname
for f in self._meta.concrete_fields
if f.attname not in self.__dict__
}
def refresh_from_db(self, using=None, fields=None):
"""
Reload field values from the database.
By default, the reloading happens from the database this instance was
loaded from, or by the read router if this instance wasn't loaded from
any database. The using parameter will override the default.
Fields can be used to specify which fields to reload. The fields
should be an iterable of field attnames. If fields is None, then
all non-deferred fields are reloaded.
When accessing deferred fields of an instance, the deferred loading
of the field will call this method.
"""
if fields is None:
self._prefetched_objects_cache = {}
else:
prefetched_objects_cache = getattr(self, "_prefetched_objects_cache", ())
for field in fields:
if field in prefetched_objects_cache:
del prefetched_objects_cache[field]
fields.remove(field)
if not fields:
return
if any(LOOKUP_SEP in f for f in fields):
raise ValueError(
'Found "%s" in fields argument. Relations and transforms '
"are not allowed in fields." % LOOKUP_SEP
)
hints = {"instance": self}
db_instance_qs = self.__class__._base_manager.db_manager(
using, hints=hints
).filter(pk=self.pk)
# Use provided fields, if not set then reload all non-deferred fields.
deferred_fields = self.get_deferred_fields()
if fields is not None:
fields = list(fields)
db_instance_qs = db_instance_qs.only(*fields)
elif deferred_fields:
fields = [
f.attname
for f in self._meta.concrete_fields
if f.attname not in deferred_fields
]
db_instance_qs = db_instance_qs.only(*fields)
db_instance = db_instance_qs.get()
non_loaded_fields = db_instance.get_deferred_fields()
for field in self._meta.concrete_fields:
if field.attname in non_loaded_fields:
# This field wasn't refreshed - skip ahead.
continue
setattr(self, field.attname, getattr(db_instance, field.attname))
# Clear cached foreign keys.
if field.is_relation and field.is_cached(self):
field.delete_cached_value(self)
# Clear cached relations.
for field in self._meta.related_objects:
if field.is_cached(self):
field.delete_cached_value(self)
self._state.db = db_instance._state.db
def serializable_value(self, field_name):
"""
Return the value of the field name for this instance. If the field is
a foreign key, return the id value instead of the object. If there's
no Field object with this name on the model, return the model
attribute's value.
Used to serialize a field's value (in the serializer, or form output,
for example). Normally, you would just access the attribute directly
and not use this method.
"""
try:
field = self._meta.get_field(field_name)
except FieldDoesNotExist:
return getattr(self, field_name)
return getattr(self, field.attname)
def save(
self, force_insert=False, force_update=False, using=None, update_fields=None
):
"""
Save the current instance. Override this in a subclass if you want to
control the saving process.
The 'force_insert' and 'force_update' parameters can be used to insist
that the "save" must be an SQL insert or update (or equivalent for
non-SQL backends), respectively. Normally, they should not be set.
"""
self._prepare_related_fields_for_save(operation_name="save")
using = using or router.db_for_write(self.__class__, instance=self)
if force_insert and (force_update or update_fields):
raise ValueError("Cannot force both insert and updating in model saving.")
deferred_fields = self.get_deferred_fields()
if update_fields is not None:
# If update_fields is empty, skip the save. We do also check for
# no-op saves later on for inheritance cases. This bailout is
# still needed for skipping signal sending.
if not update_fields:
return
update_fields = frozenset(update_fields)
field_names = set()
for field in self._meta.concrete_fields:
if not field.primary_key:
field_names.add(field.name)
if field.name != field.attname:
field_names.add(field.attname)
non_model_fields = update_fields.difference(field_names)
if non_model_fields:
raise ValueError(
"The following fields do not exist in this model, are m2m "
"fields, or are non-concrete fields: %s"
% ", ".join(non_model_fields)
)
# If saving to the same database, and this model is deferred, then
# automatically do an "update_fields" save on the loaded fields.
elif not force_insert and deferred_fields and using == self._state.db:
field_names = set()
for field in self._meta.concrete_fields:
if not field.primary_key and not hasattr(field, "through"):
field_names.add(field.attname)
loaded_fields = field_names.difference(deferred_fields)
if loaded_fields:
update_fields = frozenset(loaded_fields)
self.save_base(
using=using,
force_insert=force_insert,
force_update=force_update,
update_fields=update_fields,
)
save.alters_data = True
def save_base(
self,
raw=False,
force_insert=False,
force_update=False,
using=None,
update_fields=None,
):
"""
Handle the parts of saving which should be done only once per save,
yet need to be done in raw saves, too. This includes some sanity
checks and signal sending.
The 'raw' argument is telling save_base not to save any parent
models and not to do any changes to the values before save. This
is used by fixture loading.
"""
using = using or router.db_for_write(self.__class__, instance=self)
assert not (force_insert and (force_update or update_fields))
assert update_fields is None or update_fields
cls = origin = self.__class__
# Skip proxies, but keep the origin as the proxy model.
if cls._meta.proxy:
cls = cls._meta.concrete_model
meta = cls._meta
if not meta.auto_created:
pre_save.send(
sender=origin,
instance=self,
raw=raw,
using=using,
update_fields=update_fields,
)
# A transaction isn't needed if one query is issued.
if meta.parents:
context_manager = transaction.atomic(using=using, savepoint=False)
else:
context_manager = transaction.mark_for_rollback_on_error(using=using)
with context_manager:
parent_inserted = False
if not raw:
parent_inserted = self._save_parents(cls, using, update_fields)
updated = self._save_table(
raw,
cls,
force_insert or parent_inserted,
force_update,
using,
update_fields,
)
# Store the database on which the object was saved
self._state.db = using
# Once saved, this is no longer a to-be-added instance.
self._state.adding = False
# Signal that the save is complete
if not meta.auto_created:
post_save.send(
sender=origin,
instance=self,
created=(not updated),
update_fields=update_fields,
raw=raw,
using=using,
)
save_base.alters_data = True
def _save_parents(self, cls, using, update_fields):
"""Save all the parents of cls using values from self."""
meta = cls._meta
inserted = False
for parent, field in meta.parents.items():
# Make sure the link fields are synced between parent and self.
if (
field
and getattr(self, parent._meta.pk.attname) is None
and getattr(self, field.attname) is not None
):
setattr(self, parent._meta.pk.attname, getattr(self, field.attname))
parent_inserted = self._save_parents(
cls=parent, using=using, update_fields=update_fields
)
updated = self._save_table(
cls=parent,
using=using,
update_fields=update_fields,
force_insert=parent_inserted,
)
if not updated:
inserted = True
# Set the parent's PK value to self.
if field:
setattr(self, field.attname, self._get_pk_val(parent._meta))
# Since we didn't have an instance of the parent handy set
# attname directly, bypassing the descriptor. Invalidate
# the related object cache, in case it's been accidentally
# populated. A fresh instance will be re-built from the
# database if necessary.
if field.is_cached(self):
field.delete_cached_value(self)
return inserted
def _save_table(
self,
raw=False,
cls=None,
force_insert=False,
force_update=False,
using=None,
update_fields=None,
):
"""
Do the heavy-lifting involved in saving. Update or insert the data
for a single table.
"""
meta = cls._meta
non_pks = [f for f in meta.local_concrete_fields if not f.primary_key]
if update_fields:
non_pks = [
f
for f in non_pks
if f.name in update_fields or f.attname in update_fields
]
pk_val = self._get_pk_val(meta)
if pk_val is None:
pk_val = meta.pk.get_pk_value_on_save(self)
setattr(self, meta.pk.attname, pk_val)
pk_set = pk_val is not None
if not pk_set and (force_update or update_fields):
raise ValueError("Cannot force an update in save() with no primary key.")
updated = False
# Skip an UPDATE when adding an instance and primary key has a default.
if (
not raw
and not force_insert
and self._state.adding
and meta.pk.default
and meta.pk.default is not NOT_PROVIDED
):
force_insert = True
# If possible, try an UPDATE. If that doesn't update anything, do an INSERT.
if pk_set and not force_insert:
base_qs = cls._base_manager.using(using)
values = [
(
f,
None,
(getattr(self, f.attname) if raw else f.pre_save(self, False)),
)
for f in non_pks
]
forced_update = update_fields or force_update
updated = self._do_update(
base_qs, using, pk_val, values, update_fields, forced_update
)
if force_update and not updated:
raise DatabaseError("Forced update did not affect any rows.")
if update_fields and not updated:
raise DatabaseError("Save with update_fields did not affect any rows.")
if not updated:
if meta.order_with_respect_to:
# If this is a model with an order_with_respect_to
# autopopulate the _order field
field = meta.order_with_respect_to
filter_args = field.get_filter_kwargs_for_object(self)
self._order = (
cls._base_manager.using(using)
.filter(**filter_args)
.aggregate(
_order__max=Coalesce(
ExpressionWrapper(
Max("_order") + Value(1), output_field=IntegerField()
),
Value(0),
),
)["_order__max"]
)
fields = meta.local_concrete_fields
if not pk_set:
fields = [f for f in fields if f is not meta.auto_field]
returning_fields = meta.db_returning_fields
results = self._do_insert(
cls._base_manager, using, fields, returning_fields, raw
)
if results:
for value, field in zip(results[0], returning_fields):
setattr(self, field.attname, value)
return updated
def _do_update(self, base_qs, using, pk_val, values, update_fields, forced_update):
"""
Try to update the model. Return True if the model was updated (if an
update query was done and a matching row was found in the DB).
"""
filtered = base_qs.filter(pk=pk_val)
if not values:
# We can end up here when saving a model in inheritance chain where
# update_fields doesn't target any field in current model. In that
# case we just say the update succeeded. Another case ending up here
# is a model with just PK - in that case check that the PK still
# exists.
return update_fields is not None or filtered.exists()
if self._meta.select_on_save and not forced_update:
return (
filtered.exists()
and
# It may happen that the object is deleted from the DB right after
# this check, causing the subsequent UPDATE to return zero matching
# rows. The same result can occur in some rare cases when the
# database returns zero despite the UPDATE being executed
# successfully (a row is matched and updated). In order to
# distinguish these two cases, the object's existence in the
# database is again checked for if the UPDATE query returns 0.
(filtered._update(values) > 0 or filtered.exists())
)
return filtered._update(values) > 0
def _do_insert(self, manager, using, fields, returning_fields, raw):
"""
Do an INSERT. If returning_fields is defined then this method should
return the newly created data for the model.
"""
return manager._insert(
[self],
fields=fields,
returning_fields=returning_fields,
using=using,
raw=raw,
)
def _prepare_related_fields_for_save(self, operation_name, fields=None):
# Ensure that a model instance without a PK hasn't been assigned to
# a ForeignKey, GenericForeignKey or OneToOneField on this model. If
# the field is nullable, allowing the save would result in silent data
# loss.
for field in self._meta.concrete_fields:
if fields and field not in fields:
continue
# If the related field isn't cached, then an instance hasn't been
# assigned and there's no need to worry about this check.
if field.is_relation and field.is_cached(self):
obj = getattr(self, field.name, None)
if not obj:
continue
# A pk may have been assigned manually to a model instance not
# saved to the database (or auto-generated in a case like
# UUIDField), but we allow the save to proceed and rely on the
# database to raise an IntegrityError if applicable. If
# constraints aren't supported by the database, there's the
# unavoidable risk of data corruption.
if obj.pk is None:
# Remove the object from a related instance cache.
if not field.remote_field.multiple:
field.remote_field.delete_cached_value(obj)
raise ValueError(
"%s() prohibited to prevent data loss due to unsaved "
"related object '%s'." % (operation_name, field.name)
)
elif getattr(self, field.attname) in field.empty_values:
# Set related object if it has been saved after an
# assignment.
setattr(self, field.name, obj)
# If the relationship's pk/to_field was changed, clear the
# cached relationship.
if getattr(obj, field.target_field.attname) != getattr(
self, field.attname
):
field.delete_cached_value(self)
# GenericForeignKeys are private.
for field in self._meta.private_fields:
if fields and field not in fields:
continue
if (
field.is_relation
and field.is_cached(self)
and hasattr(field, "fk_field")
):
obj = field.get_cached_value(self, default=None)
if obj and obj.pk is None:
raise ValueError(
f"{operation_name}() prohibited to prevent data loss due to "
f"unsaved related object '{field.name}'."
)
def delete(self, using=None, keep_parents=False):
if self.pk is None:
raise ValueError(
"%s object can't be deleted because its %s attribute is set "
"to None." % (self._meta.object_name, self._meta.pk.attname)
)
using = using or router.db_for_write(self.__class__, instance=self)
collector = Collector(using=using, origin=self)
collector.collect([self], keep_parents=keep_parents)
return collector.delete()
delete.alters_data = True
def _get_FIELD_display(self, field):
value = getattr(self, field.attname)
choices_dict = dict(make_hashable(field.flatchoices))
# force_str() to coerce lazy strings.
return force_str(
choices_dict.get(make_hashable(value), value), strings_only=True
)
def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs):
if not self.pk:
raise ValueError("get_next/get_previous cannot be used on unsaved objects.")
op = "gt" if is_next else "lt"
order = "" if is_next else "-"
param = getattr(self, field.attname)
q = Q.create([(field.name, param), (f"pk__{op}", self.pk)], connector=Q.AND)
q = Q.create([q, (f"{field.name}__{op}", param)], connector=Q.OR)
qs = (
self.__class__._default_manager.using(self._state.db)
.filter(**kwargs)
.filter(q)
.order_by("%s%s" % (order, field.name), "%spk" % order)
)
try:
return qs[0]
except IndexError:
raise self.DoesNotExist(
"%s matching query does not exist." % self.__class__._meta.object_name
)
def _get_next_or_previous_in_order(self, is_next):
cachename = "__%s_order_cache" % is_next
if not hasattr(self, cachename):
op = "gt" if is_next else "lt"
order = "_order" if is_next else "-_order"
order_field = self._meta.order_with_respect_to
filter_args = order_field.get_filter_kwargs_for_object(self)
obj = (
self.__class__._default_manager.filter(**filter_args)
.filter(
**{
"_order__%s"
% op: self.__class__._default_manager.values("_order").filter(
**{self._meta.pk.name: self.pk}
)
}
)
.order_by(order)[:1]
.get()
)
setattr(self, cachename, obj)
return getattr(self, cachename)
def _get_field_value_map(self, meta, exclude=None):
if exclude is None:
exclude = set()
meta = meta or self._meta
return {
field.name: Value(getattr(self, field.attname), field)
for field in meta.local_concrete_fields
if field.name not in exclude
}
def prepare_database_save(self, field):
if self.pk is None:
raise ValueError(
"Unsaved model instance %r cannot be used in an ORM query." % self
)
return getattr(self, field.remote_field.get_related_field().attname)
def clean(self):
"""
Hook for doing any extra model-wide validation after clean() has been
called on every field by self.clean_fields. Any ValidationError raised
by this method will not be associated with a particular field; it will
have a special-case association with the field defined by NON_FIELD_ERRORS.
"""
pass
def validate_unique(self, exclude=None):
"""
Check unique constraints on the model and raise ValidationError if any
failed.
"""
unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
errors = self._perform_unique_checks(unique_checks)
date_errors = self._perform_date_checks(date_checks)
for k, v in date_errors.items():
errors.setdefault(k, []).extend(v)
if errors:
raise ValidationError(errors)
def _get_unique_checks(self, exclude=None, include_meta_constraints=False):
"""
Return a list of checks to perform. Since validate_unique() could be
called from a ModelForm, some fields may have been excluded; we can't
perform a unique check on a model that is missing fields involved
in that check. Fields that did not validate should also be excluded,
but they need to be passed in via the exclude argument.
"""
if exclude is None:
exclude = set()
unique_checks = []
unique_togethers = [(self.__class__, self._meta.unique_together)]
constraints = []
if include_meta_constraints:
constraints = [(self.__class__, self._meta.total_unique_constraints)]
for parent_class in self._meta.get_parent_list():
if parent_class._meta.unique_together:
unique_togethers.append(
(parent_class, parent_class._meta.unique_together)
)
if include_meta_constraints and parent_class._meta.total_unique_constraints:
constraints.append(
(parent_class, parent_class._meta.total_unique_constraints)
)
for model_class, unique_together in unique_togethers:
for check in unique_together:
if not any(name in exclude for name in check):
# Add the check if the field isn't excluded.
unique_checks.append((model_class, tuple(check)))
if include_meta_constraints:
for model_class, model_constraints in constraints:
for constraint in model_constraints:
if not any(name in exclude for name in constraint.fields):
unique_checks.append((model_class, constraint.fields))
# These are checks for the unique_for_<date/year/month>.
date_checks = []
# Gather a list of checks for fields declared as unique and add them to
# the list of checks.
fields_with_class = [(self.__class__, self._meta.local_fields)]
for parent_class in self._meta.get_parent_list():
fields_with_class.append((parent_class, parent_class._meta.local_fields))
for model_class, fields in fields_with_class:
for f in fields:
name = f.name
if name in exclude:
continue
if f.unique:
unique_checks.append((model_class, (name,)))
if f.unique_for_date and f.unique_for_date not in exclude:
date_checks.append((model_class, "date", name, f.unique_for_date))
if f.unique_for_year and f.unique_for_year not in exclude:
date_checks.append((model_class, "year", name, f.unique_for_year))
if f.unique_for_month and f.unique_for_month not in exclude:
date_checks.append((model_class, "month", name, f.unique_for_month))
return unique_checks, date_checks
def _perform_unique_checks(self, unique_checks):
errors = {}
for model_class, unique_check in unique_checks:
# Try to look up an existing object with the same values as this
# object's values for all the unique field.
lookup_kwargs = {}
for field_name in unique_check:
f = self._meta.get_field(field_name)
lookup_value = getattr(self, f.attname)
# TODO: Handle multiple backends with different feature flags.
if lookup_value is None or (
lookup_value == ""
and connection.features.interprets_empty_strings_as_nulls
):
# no value, skip the lookup
continue
if f.primary_key and not self._state.adding:
# no need to check for unique primary key when editing
continue
lookup_kwargs[str(field_name)] = lookup_value
# some fields were skipped, no reason to do the check
if len(unique_check) != len(lookup_kwargs):
continue
qs = model_class._default_manager.filter(**lookup_kwargs)
# Exclude the current object from the query if we are editing an
# instance (as opposed to creating a new one)
# Note that we need to use the pk as defined by model_class, not
# self.pk. These can be different fields because model inheritance
# allows single model to have effectively multiple primary keys.
# Refs #17615.
model_class_pk = self._get_pk_val(model_class._meta)
if not self._state.adding and model_class_pk is not None:
qs = qs.exclude(pk=model_class_pk)
if qs.exists():
if len(unique_check) == 1:
key = unique_check[0]
else:
key = NON_FIELD_ERRORS
errors.setdefault(key, []).append(
self.unique_error_message(model_class, unique_check)
)
return errors
def _perform_date_checks(self, date_checks):
errors = {}
for model_class, lookup_type, field, unique_for in date_checks:
lookup_kwargs = {}
# there's a ticket to add a date lookup, we can remove this special
# case if that makes it's way in
date = getattr(self, unique_for)
if date is None:
continue
if lookup_type == "date":
lookup_kwargs["%s__day" % unique_for] = date.day
lookup_kwargs["%s__month" % unique_for] = date.month
lookup_kwargs["%s__year" % unique_for] = date.year
else:
lookup_kwargs["%s__%s" % (unique_for, lookup_type)] = getattr(
date, lookup_type
)
lookup_kwargs[field] = getattr(self, field)
qs = model_class._default_manager.filter(**lookup_kwargs)
# Exclude the current object from the query if we are editing an
# instance (as opposed to creating a new one)
if not self._state.adding and self.pk is not None:
qs = qs.exclude(pk=self.pk)
if qs.exists():
errors.setdefault(field, []).append(
self.date_error_message(lookup_type, field, unique_for)
)
return errors
def date_error_message(self, lookup_type, field_name, unique_for):
opts = self._meta
field = opts.get_field(field_name)
return ValidationError(
message=field.error_messages["unique_for_date"],
code="unique_for_date",
params={
"model": self,
"model_name": capfirst(opts.verbose_name),
"lookup_type": lookup_type,
"field": field_name,
"field_label": capfirst(field.verbose_name),
"date_field": unique_for,
"date_field_label": capfirst(opts.get_field(unique_for).verbose_name),
},
)
def unique_error_message(self, model_class, unique_check):
opts = model_class._meta
params = {
"model": self,
"model_class": model_class,
"model_name": capfirst(opts.verbose_name),
"unique_check": unique_check,
}
# A unique field
if len(unique_check) == 1:
field = opts.get_field(unique_check[0])
params["field_label"] = capfirst(field.verbose_name)
return ValidationError(
message=field.error_messages["unique"],
code="unique",
params=params,
)
# unique_together
else:
field_labels = [
capfirst(opts.get_field(f).verbose_name) for f in unique_check
]
params["field_labels"] = get_text_list(field_labels, _("and"))
return ValidationError(
message=_("%(model_name)s with this %(field_labels)s already exists."),
code="unique_together",
params=params,
)
def get_constraints(self):
constraints = [(self.__class__, self._meta.constraints)]
for parent_class in self._meta.get_parent_list():
if parent_class._meta.constraints:
constraints.append((parent_class, parent_class._meta.constraints))
return constraints
def validate_constraints(self, exclude=None):
constraints = self.get_constraints()
using = router.db_for_write(self.__class__, instance=self)
errors = {}
for model_class, model_constraints in constraints:
for constraint in model_constraints:
try:
constraint.validate(model_class, self, exclude=exclude, using=using)
except ValidationError as e:
if e.code == "unique" and len(constraint.fields) == 1:
errors.setdefault(constraint.fields[0], []).append(e)
else:
errors = e.update_error_dict(errors)
if errors:
raise ValidationError(errors)
def full_clean(self, exclude=None, validate_unique=True, validate_constraints=True):
"""
Call clean_fields(), clean(), validate_unique(), and
validate_constraints() on the model. Raise a ValidationError for any
errors that occur.
"""
errors = {}
if exclude is None:
exclude = set()
else:
exclude = set(exclude)
try:
self.clean_fields(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
# Form.clean() is run even if other validation fails, so do the
# same with Model.clean() for consistency.
try:
self.clean()
except ValidationError as e:
errors = e.update_error_dict(errors)
# Run unique checks, but only for fields that passed validation.
if validate_unique:
for name in errors:
if name != NON_FIELD_ERRORS and name not in exclude:
exclude.add(name)
try:
self.validate_unique(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
# Run constraints checks, but only for fields that passed validation.
if validate_constraints:
for name in errors:
if name != NON_FIELD_ERRORS and name not in exclude:
exclude.add(name)
try:
self.validate_constraints(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
if errors:
raise ValidationError(errors)
def clean_fields(self, exclude=None):
"""
Clean all fields and raise a ValidationError containing a dict
of all validation errors if any occur.
"""
if exclude is None:
exclude = set()
errors = {}
for f in self._meta.fields:
if f.name in exclude:
continue
# Skip validation for empty fields with blank=True. The developer
# is responsible for making sure they have a valid value.
raw_value = getattr(self, f.attname)
if f.blank and raw_value in f.empty_values:
continue
try:
setattr(self, f.attname, f.clean(raw_value, self))
except ValidationError as e:
errors[f.name] = e.error_list
if errors:
raise ValidationError(errors)
@classmethod
def check(cls, **kwargs):
errors = [
*cls._check_swappable(),
*cls._check_model(),
*cls._check_managers(**kwargs),
]
if not cls._meta.swapped:
databases = kwargs.get("databases") or []
errors += [
*cls._check_fields(**kwargs),
*cls._check_m2m_through_same_relationship(),
*cls._check_long_column_names(databases),
]
clash_errors = (
*cls._check_id_field(),
*cls._check_field_name_clashes(),
*cls._check_model_name_db_lookup_clashes(),
*cls._check_property_name_related_field_accessor_clashes(),
*cls._check_single_primary_key(),
)
errors.extend(clash_errors)
# If there are field name clashes, hide consequent column name
# clashes.
if not clash_errors:
errors.extend(cls._check_column_name_clashes())
errors += [
*cls._check_index_together(),
*cls._check_unique_together(),
*cls._check_indexes(databases),
*cls._check_ordering(),
*cls._check_constraints(databases),
*cls._check_default_pk(),
]
return errors
@classmethod
def _check_default_pk(cls):
if (
not cls._meta.abstract
and cls._meta.pk.auto_created
and
# Inherited PKs are checked in parents models.
not (
isinstance(cls._meta.pk, OneToOneField)
and cls._meta.pk.remote_field.parent_link
)
and not settings.is_overridden("DEFAULT_AUTO_FIELD")
and cls._meta.app_config
and not cls._meta.app_config._is_default_auto_field_overridden
):
return [
checks.Warning(
f"Auto-created primary key used when not defining a "
f"primary key type, by default "
f"'{settings.DEFAULT_AUTO_FIELD}'.",
hint=(
f"Configure the DEFAULT_AUTO_FIELD setting or the "
f"{cls._meta.app_config.__class__.__qualname__}."
f"default_auto_field attribute to point to a subclass "
f"of AutoField, e.g. 'django.db.models.BigAutoField'."
),
obj=cls,
id="models.W042",
),
]
return []
@classmethod
def _check_swappable(cls):
"""Check if the swapped model exists."""
errors = []
if cls._meta.swapped:
try:
apps.get_model(cls._meta.swapped)
except ValueError:
errors.append(
checks.Error(
"'%s' is not of the form 'app_label.app_name'."
% cls._meta.swappable,
id="models.E001",
)
)
except LookupError:
app_label, model_name = cls._meta.swapped.split(".")
errors.append(
checks.Error(
"'%s' references '%s.%s', which has not been "
"installed, or is abstract."
% (cls._meta.swappable, app_label, model_name),
id="models.E002",
)
)
return errors
@classmethod
def _check_model(cls):
errors = []
if cls._meta.proxy:
if cls._meta.local_fields or cls._meta.local_many_to_many:
errors.append(
checks.Error(
"Proxy model '%s' contains model fields." % cls.__name__,
id="models.E017",
)
)
return errors
@classmethod
def _check_managers(cls, **kwargs):
"""Perform all manager checks."""
errors = []
for manager in cls._meta.managers:
errors.extend(manager.check(**kwargs))
return errors
@classmethod
def _check_fields(cls, **kwargs):
"""Perform all field checks."""
errors = []
for field in cls._meta.local_fields:
errors.extend(field.check(**kwargs))
for field in cls._meta.local_many_to_many:
errors.extend(field.check(from_model=cls, **kwargs))
return errors
@classmethod
def _check_m2m_through_same_relationship(cls):
"""Check if no relationship model is used by more than one m2m field."""
errors = []
seen_intermediary_signatures = []
fields = cls._meta.local_many_to_many
# Skip when the target model wasn't found.
fields = (f for f in fields if isinstance(f.remote_field.model, ModelBase))
# Skip when the relationship model wasn't found.
fields = (f for f in fields if isinstance(f.remote_field.through, ModelBase))
for f in fields:
signature = (
f.remote_field.model,
cls,
f.remote_field.through,
f.remote_field.through_fields,
)
if signature in seen_intermediary_signatures:
errors.append(
checks.Error(
"The model has two identical many-to-many relations "
"through the intermediate model '%s'."
% f.remote_field.through._meta.label,
obj=cls,
id="models.E003",
)
)
else:
seen_intermediary_signatures.append(signature)
return errors
@classmethod
def _check_id_field(cls):
"""Check if `id` field is a primary key."""
fields = [
f for f in cls._meta.local_fields if f.name == "id" and f != cls._meta.pk
]
# fields is empty or consists of the invalid "id" field
if fields and not fields[0].primary_key and cls._meta.pk.name == "id":
return [
checks.Error(
"'id' can only be used as a field name if the field also "
"sets 'primary_key=True'.",
obj=cls,
id="models.E004",
)
]
else:
return []
@classmethod
def _check_field_name_clashes(cls):
"""Forbid field shadowing in multi-table inheritance."""
errors = []
used_fields = {} # name or attname -> field
# Check that multi-inheritance doesn't cause field name shadowing.
for parent in cls._meta.get_parent_list():
for f in parent._meta.local_fields:
clash = used_fields.get(f.name) or used_fields.get(f.attname) or None
if clash:
errors.append(
checks.Error(
"The field '%s' from parent model "
"'%s' clashes with the field '%s' "
"from parent model '%s'."
% (clash.name, clash.model._meta, f.name, f.model._meta),
obj=cls,
id="models.E005",
)
)
used_fields[f.name] = f
used_fields[f.attname] = f
# Check that fields defined in the model don't clash with fields from
# parents, including auto-generated fields like multi-table inheritance
# child accessors.
for parent in cls._meta.get_parent_list():
for f in parent._meta.get_fields():
if f not in used_fields:
used_fields[f.name] = f
for f in cls._meta.local_fields:
clash = used_fields.get(f.name) or used_fields.get(f.attname) or None
# Note that we may detect clash between user-defined non-unique
# field "id" and automatically added unique field "id", both
# defined at the same model. This special case is considered in
# _check_id_field and here we ignore it.
id_conflict = (
f.name == "id" and clash and clash.name == "id" and clash.model == cls
)
if clash and not id_conflict:
errors.append(
checks.Error(
"The field '%s' clashes with the field '%s' "
"from model '%s'." % (f.name, clash.name, clash.model._meta),
obj=f,
id="models.E006",
)
)
used_fields[f.name] = f
used_fields[f.attname] = f
return errors
@classmethod
def _check_column_name_clashes(cls):
# Store a list of column names which have already been used by other fields.
used_column_names = []
errors = []
for f in cls._meta.local_fields:
_, column_name = f.get_attname_column()
# Ensure the column name is not already in use.
if column_name and column_name in used_column_names:
errors.append(
checks.Error(
"Field '%s' has column name '%s' that is used by "
"another field." % (f.name, column_name),
hint="Specify a 'db_column' for the field.",
obj=cls,
id="models.E007",
)
)
else:
used_column_names.append(column_name)
return errors
@classmethod
def _check_model_name_db_lookup_clashes(cls):
errors = []
model_name = cls.__name__
if model_name.startswith("_") or model_name.endswith("_"):
errors.append(
checks.Error(
"The model name '%s' cannot start or end with an underscore "
"as it collides with the query lookup syntax." % model_name,
obj=cls,
id="models.E023",
)
)
elif LOOKUP_SEP in model_name:
errors.append(
checks.Error(
"The model name '%s' cannot contain double underscores as "
"it collides with the query lookup syntax." % model_name,
obj=cls,
id="models.E024",
)
)
return errors
@classmethod
def _check_property_name_related_field_accessor_clashes(cls):
errors = []
property_names = cls._meta._property_names
related_field_accessors = (
f.get_attname()
for f in cls._meta._get_fields(reverse=False)
if f.is_relation and f.related_model is not None
)
for accessor in related_field_accessors:
if accessor in property_names:
errors.append(
checks.Error(
"The property '%s' clashes with a related field "
"accessor." % accessor,
obj=cls,
id="models.E025",
)
)
return errors
@classmethod
def _check_single_primary_key(cls):
errors = []
if sum(1 for f in cls._meta.local_fields if f.primary_key) > 1:
errors.append(
checks.Error(
"The model cannot have more than one field with "
"'primary_key=True'.",
obj=cls,
id="models.E026",
)
)
return errors
# RemovedInDjango51Warning.
@classmethod
def _check_index_together(cls):
"""Check the value of "index_together" option."""
if not isinstance(cls._meta.index_together, (tuple, list)):
return [
checks.Error(
"'index_together' must be a list or tuple.",
obj=cls,
id="models.E008",
)
]
elif any(
not isinstance(fields, (tuple, list)) for fields in cls._meta.index_together
):
return [
checks.Error(
"All 'index_together' elements must be lists or tuples.",
obj=cls,
id="models.E009",
)
]
else:
errors = []
for fields in cls._meta.index_together:
errors.extend(cls._check_local_fields(fields, "index_together"))
return errors
@classmethod
def _check_unique_together(cls):
"""Check the value of "unique_together" option."""
if not isinstance(cls._meta.unique_together, (tuple, list)):
return [
checks.Error(
"'unique_together' must be a list or tuple.",
obj=cls,
id="models.E010",
)
]
elif any(
not isinstance(fields, (tuple, list))
for fields in cls._meta.unique_together
):
return [
checks.Error(
"All 'unique_together' elements must be lists or tuples.",
obj=cls,
id="models.E011",
)
]
else:
errors = []
for fields in cls._meta.unique_together:
errors.extend(cls._check_local_fields(fields, "unique_together"))
return errors
@classmethod
def _check_indexes(cls, databases):
"""Check fields, names, and conditions of indexes."""
errors = []
references = set()
for index in cls._meta.indexes:
# Index name can't start with an underscore or a number, restricted
# for cross-database compatibility with Oracle.
if index.name[0] == "_" or index.name[0].isdigit():
errors.append(
checks.Error(
"The index name '%s' cannot start with an underscore "
"or a number." % index.name,
obj=cls,
id="models.E033",
),
)
if len(index.name) > index.max_name_length:
errors.append(
checks.Error(
"The index name '%s' cannot be longer than %d "
"characters." % (index.name, index.max_name_length),
obj=cls,
id="models.E034",
),
)
if index.contains_expressions:
for expression in index.expressions:
references.update(
ref[0] for ref in cls._get_expr_references(expression)
)
for db in databases:
if not router.allow_migrate_model(db, cls):
continue
connection = connections[db]
if not (
connection.features.supports_partial_indexes
or "supports_partial_indexes" in cls._meta.required_db_features
) and any(index.condition is not None for index in cls._meta.indexes):
errors.append(
checks.Warning(
"%s does not support indexes with conditions."
% connection.display_name,
hint=(
"Conditions will be ignored. Silence this warning "
"if you don't care about it."
),
obj=cls,
id="models.W037",
)
)
if not (
connection.features.supports_covering_indexes
or "supports_covering_indexes" in cls._meta.required_db_features
) and any(index.include for index in cls._meta.indexes):
errors.append(
checks.Warning(
"%s does not support indexes with non-key columns."
% connection.display_name,
hint=(
"Non-key columns will be ignored. Silence this "
"warning if you don't care about it."
),
obj=cls,
id="models.W040",
)
)
if not (
connection.features.supports_expression_indexes
or "supports_expression_indexes" in cls._meta.required_db_features
) and any(index.contains_expressions for index in cls._meta.indexes):
errors.append(
checks.Warning(
"%s does not support indexes on expressions."
% connection.display_name,
hint=(
"An index won't be created. Silence this warning "
"if you don't care about it."
),
obj=cls,
id="models.W043",
)
)
fields = [
field for index in cls._meta.indexes for field, _ in index.fields_orders
]
fields += [include for index in cls._meta.indexes for include in index.include]
fields += references
errors.extend(cls._check_local_fields(fields, "indexes"))
return errors
@classmethod
def _check_local_fields(cls, fields, option):
from django.db import models
# In order to avoid hitting the relation tree prematurely, we use our
# own fields_map instead of using get_field()
forward_fields_map = {}
for field in cls._meta._get_fields(reverse=False):
forward_fields_map[field.name] = field
if hasattr(field, "attname"):
forward_fields_map[field.attname] = field
errors = []
for field_name in fields:
try:
field = forward_fields_map[field_name]
except KeyError:
errors.append(
checks.Error(
"'%s' refers to the nonexistent field '%s'."
% (
option,
field_name,
),
obj=cls,
id="models.E012",
)
)
else:
if isinstance(field.remote_field, models.ManyToManyRel):
errors.append(
checks.Error(
"'%s' refers to a ManyToManyField '%s', but "
"ManyToManyFields are not permitted in '%s'."
% (
option,
field_name,
option,
),
obj=cls,
id="models.E013",
)
)
elif field not in cls._meta.local_fields:
errors.append(
checks.Error(
"'%s' refers to field '%s' which is not local to model "
"'%s'." % (option, field_name, cls._meta.object_name),
hint="This issue may be caused by multi-table inheritance.",
obj=cls,
id="models.E016",
)
)
return errors
@classmethod
def _check_ordering(cls):
"""
Check "ordering" option -- is it a list of strings and do all fields
exist?
"""
if cls._meta._ordering_clash:
return [
checks.Error(
"'ordering' and 'order_with_respect_to' cannot be used together.",
obj=cls,
id="models.E021",
),
]
if cls._meta.order_with_respect_to or not cls._meta.ordering:
return []
if not isinstance(cls._meta.ordering, (list, tuple)):
return [
checks.Error(
"'ordering' must be a tuple or list (even if you want to order by "
"only one field).",
obj=cls,
id="models.E014",
)
]
errors = []
fields = cls._meta.ordering
# Skip expressions and '?' fields.
fields = (f for f in fields if isinstance(f, str) and f != "?")
# Convert "-field" to "field".
fields = ((f[1:] if f.startswith("-") else f) for f in fields)
# Separate related fields and non-related fields.
_fields = []
related_fields = []
for f in fields:
if LOOKUP_SEP in f:
related_fields.append(f)
else:
_fields.append(f)
fields = _fields
# Check related fields.
for field in related_fields:
_cls = cls
fld = None
for part in field.split(LOOKUP_SEP):
try:
# pk is an alias that won't be found by opts.get_field.
if part == "pk":
fld = _cls._meta.pk
else:
fld = _cls._meta.get_field(part)
if fld.is_relation:
_cls = fld.path_infos[-1].to_opts.model
else:
_cls = None
except (FieldDoesNotExist, AttributeError):
if fld is None or (
fld.get_transform(part) is None and fld.get_lookup(part) is None
):
errors.append(
checks.Error(
"'ordering' refers to the nonexistent field, "
"related field, or lookup '%s'." % field,
obj=cls,
id="models.E015",
)
)
# Skip ordering on pk. This is always a valid order_by field
# but is an alias and therefore won't be found by opts.get_field.
fields = {f for f in fields if f != "pk"}
# Check for invalid or nonexistent fields in ordering.
invalid_fields = []
# Any field name that is not present in field_names does not exist.
# Also, ordering by m2m fields is not allowed.
opts = cls._meta
valid_fields = set(
chain.from_iterable(
(f.name, f.attname)
if not (f.auto_created and not f.concrete)
else (f.field.related_query_name(),)
for f in chain(opts.fields, opts.related_objects)
)
)
invalid_fields.extend(fields - valid_fields)
for invalid_field in invalid_fields:
errors.append(
checks.Error(
"'ordering' refers to the nonexistent field, related "
"field, or lookup '%s'." % invalid_field,
obj=cls,
id="models.E015",
)
)
return errors
@classmethod
def _check_long_column_names(cls, databases):
"""
Check that any auto-generated column names are shorter than the limits
for each database in which the model will be created.
"""
if not databases:
return []
errors = []
allowed_len = None
db_alias = None
# Find the minimum max allowed length among all specified db_aliases.
for db in databases:
# skip databases where the model won't be created
if not router.allow_migrate_model(db, cls):
continue
connection = connections[db]
max_name_length = connection.ops.max_name_length()
if max_name_length is None or connection.features.truncates_names:
continue
else:
if allowed_len is None:
allowed_len = max_name_length
db_alias = db
elif max_name_length < allowed_len:
allowed_len = max_name_length
db_alias = db
if allowed_len is None:
return errors
for f in cls._meta.local_fields:
_, column_name = f.get_attname_column()
# Check if auto-generated name for the field is too long
# for the database.
if (
f.db_column is None
and column_name is not None
and len(column_name) > allowed_len
):
errors.append(
checks.Error(
'Autogenerated column name too long for field "%s". '
'Maximum length is "%s" for database "%s".'
% (column_name, allowed_len, db_alias),
hint="Set the column name manually using 'db_column'.",
obj=cls,
id="models.E018",
)
)
for f in cls._meta.local_many_to_many:
# Skip nonexistent models.
if isinstance(f.remote_field.through, str):
continue
# Check if auto-generated name for the M2M field is too long
# for the database.
for m2m in f.remote_field.through._meta.local_fields:
_, rel_name = m2m.get_attname_column()
if (
m2m.db_column is None
and rel_name is not None
and len(rel_name) > allowed_len
):
errors.append(
checks.Error(
"Autogenerated column name too long for M2M field "
'"%s". Maximum length is "%s" for database "%s".'
% (rel_name, allowed_len, db_alias),
hint=(
"Use 'through' to create a separate model for "
"M2M and then set column_name using 'db_column'."
),
obj=cls,
id="models.E019",
)
)
return errors
@classmethod
def _get_expr_references(cls, expr):
if isinstance(expr, Q):
for child in expr.children:
if isinstance(child, tuple):
lookup, value = child
yield tuple(lookup.split(LOOKUP_SEP))
yield from cls._get_expr_references(value)
else:
yield from cls._get_expr_references(child)
elif isinstance(expr, F):
yield tuple(expr.name.split(LOOKUP_SEP))
elif hasattr(expr, "get_source_expressions"):
for src_expr in expr.get_source_expressions():
yield from cls._get_expr_references(src_expr)
@classmethod
def _check_constraints(cls, databases):
errors = []
for db in databases:
if not router.allow_migrate_model(db, cls):
continue
connection = connections[db]
if not (
connection.features.supports_table_check_constraints
or "supports_table_check_constraints" in cls._meta.required_db_features
) and any(
isinstance(constraint, CheckConstraint)
for constraint in cls._meta.constraints
):
errors.append(
checks.Warning(
"%s does not support check constraints."
% connection.display_name,
hint=(
"A constraint won't be created. Silence this "
"warning if you don't care about it."
),
obj=cls,
id="models.W027",
)
)
if not (
connection.features.supports_partial_indexes
or "supports_partial_indexes" in cls._meta.required_db_features
) and any(
isinstance(constraint, UniqueConstraint)
and constraint.condition is not None
for constraint in cls._meta.constraints
):
errors.append(
checks.Warning(
"%s does not support unique constraints with "
"conditions." % connection.display_name,
hint=(
"A constraint won't be created. Silence this "
"warning if you don't care about it."
),
obj=cls,
id="models.W036",
)
)
if not (
connection.features.supports_deferrable_unique_constraints
or "supports_deferrable_unique_constraints"
in cls._meta.required_db_features
) and any(
isinstance(constraint, UniqueConstraint)
and constraint.deferrable is not None
for constraint in cls._meta.constraints
):
errors.append(
checks.Warning(
"%s does not support deferrable unique constraints."
% connection.display_name,
hint=(
"A constraint won't be created. Silence this "
"warning if you don't care about it."
),
obj=cls,
id="models.W038",
)
)
if not (
connection.features.supports_covering_indexes
or "supports_covering_indexes" in cls._meta.required_db_features
) and any(
isinstance(constraint, UniqueConstraint) and constraint.include
for constraint in cls._meta.constraints
):
errors.append(
checks.Warning(
"%s does not support unique constraints with non-key "
"columns." % connection.display_name,
hint=(
"A constraint won't be created. Silence this "
"warning if you don't care about it."
),
obj=cls,
id="models.W039",
)
)
if not (
connection.features.supports_expression_indexes
or "supports_expression_indexes" in cls._meta.required_db_features
) and any(
isinstance(constraint, UniqueConstraint)
and constraint.contains_expressions
for constraint in cls._meta.constraints
):
errors.append(
checks.Warning(
"%s does not support unique constraints on "
"expressions." % connection.display_name,
hint=(
"A constraint won't be created. Silence this "
"warning if you don't care about it."
),
obj=cls,
id="models.W044",
)
)
fields = set(
chain.from_iterable(
(*constraint.fields, *constraint.include)
for constraint in cls._meta.constraints
if isinstance(constraint, UniqueConstraint)
)
)
references = set()
for constraint in cls._meta.constraints:
if isinstance(constraint, UniqueConstraint):
if (
connection.features.supports_partial_indexes
or "supports_partial_indexes"
not in cls._meta.required_db_features
) and isinstance(constraint.condition, Q):
references.update(
cls._get_expr_references(constraint.condition)
)
if (
connection.features.supports_expression_indexes
or "supports_expression_indexes"
not in cls._meta.required_db_features
) and constraint.contains_expressions:
for expression in constraint.expressions:
references.update(cls._get_expr_references(expression))
elif isinstance(constraint, CheckConstraint):
if (
connection.features.supports_table_check_constraints
or "supports_table_check_constraints"
not in cls._meta.required_db_features
):
if isinstance(constraint.check, Q):
references.update(
cls._get_expr_references(constraint.check)
)
if any(
isinstance(expr, RawSQL)
for expr in constraint.check.flatten()
):
errors.append(
checks.Warning(
f"Check constraint {constraint.name!r} contains "
f"RawSQL() expression and won't be validated "
f"during the model full_clean().",
hint=(
"Silence this warning if you don't care about "
"it."
),
obj=cls,
id="models.W045",
),
)
for field_name, *lookups in references:
# pk is an alias that won't be found by opts.get_field.
if field_name != "pk":
fields.add(field_name)
if not lookups:
# If it has no lookups it cannot result in a JOIN.
continue
try:
if field_name == "pk":
field = cls._meta.pk
else:
field = cls._meta.get_field(field_name)
if not field.is_relation or field.many_to_many or field.one_to_many:
continue
except FieldDoesNotExist:
continue
# JOIN must happen at the first lookup.
first_lookup = lookups[0]
if (
hasattr(field, "get_transform")
and hasattr(field, "get_lookup")
and field.get_transform(first_lookup) is None
and field.get_lookup(first_lookup) is None
):
errors.append(
checks.Error(
"'constraints' refers to the joined field '%s'."
% LOOKUP_SEP.join([field_name] + lookups),
obj=cls,
id="models.E041",
)
)
errors.extend(cls._check_local_fields(fields, "constraints"))
return errors
############################################
# HELPER FUNCTIONS (CURRIED MODEL METHODS) #
############################################
# ORDERING METHODS #########################
def method_set_order(self, ordered_obj, id_list, using=None):
order_wrt = ordered_obj._meta.order_with_respect_to
filter_args = order_wrt.get_forward_related_filter(self)
ordered_obj.objects.db_manager(using).filter(**filter_args).bulk_update(
[ordered_obj(pk=pk, _order=order) for order, pk in enumerate(id_list)],
["_order"],
)
def method_get_order(self, ordered_obj):
order_wrt = ordered_obj._meta.order_with_respect_to
filter_args = order_wrt.get_forward_related_filter(self)
pk_name = ordered_obj._meta.pk.name
return ordered_obj.objects.filter(**filter_args).values_list(pk_name, flat=True)
def make_foreign_order_accessors(model, related_model):
setattr(
related_model,
"get_%s_order" % model.__name__.lower(),
partialmethod(method_get_order, model),
)
setattr(
related_model,
"set_%s_order" % model.__name__.lower(),
partialmethod(method_set_order, model),
)
########
# MISC #
########
def model_unpickle(model_id):
"""Used to unpickle Model subclasses with deferred fields."""
if isinstance(model_id, tuple):
model = apps.get_model(*model_id)
else:
# Backwards compat - the model was cached directly in earlier versions.
model = model_id
return model.__new__(model)
model_unpickle.__safe_for_unpickle__ = True
|
bee034b0f3b57dcd22a980e6ff057c950f2e41ef9e262395437954bbf3db9312 | """
Various data structures used in query construction.
Factored out from django.db.models.query to avoid making the main module very
large and/or so that they can be used by other modules without getting into
circular import difficulties.
"""
import functools
import inspect
import logging
from collections import namedtuple
from django.core.exceptions import FieldError
from django.db import DEFAULT_DB_ALIAS, DatabaseError
from django.db.models.constants import LOOKUP_SEP
from django.utils import tree
logger = logging.getLogger("django.db.models")
# PathInfo is used when converting lookups (fk__somecol). The contents
# describe the relation in Model terms (model Options and Fields for both
# sides of the relation. The join_field is the field backing the relation.
PathInfo = namedtuple(
"PathInfo",
"from_opts to_opts target_fields join_field m2m direct filtered_relation",
)
def subclasses(cls):
yield cls
for subclass in cls.__subclasses__():
yield from subclasses(subclass)
class Q(tree.Node):
"""
Encapsulate filters as objects that can then be combined logically (using
`&` and `|`).
"""
# Connection types
AND = "AND"
OR = "OR"
XOR = "XOR"
default = AND
conditional = True
def __init__(self, *args, _connector=None, _negated=False, **kwargs):
super().__init__(
children=[*args, *sorted(kwargs.items())],
connector=_connector,
negated=_negated,
)
def _combine(self, other, conn):
if getattr(other, "conditional", False) is False:
raise TypeError(other)
if not self:
return other.copy()
if not other and isinstance(other, Q):
return self.copy()
obj = self.create(connector=conn)
obj.add(self, conn)
obj.add(other, conn)
return obj
def __or__(self, other):
return self._combine(other, self.OR)
def __and__(self, other):
return self._combine(other, self.AND)
def __xor__(self, other):
return self._combine(other, self.XOR)
def __invert__(self):
obj = self.copy()
obj.negate()
return obj
def resolve_expression(
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
):
# We must promote any new joins to left outer joins so that when Q is
# used as an expression, rows aren't filtered due to joins.
clause, joins = query._add_q(
self,
reuse,
allow_joins=allow_joins,
split_subq=False,
check_filterable=False,
)
query.promote_joins(joins)
return clause
def flatten(self):
"""
Recursively yield this Q object and all subexpressions, in depth-first
order.
"""
yield self
for child in self.children:
if isinstance(child, tuple):
# Use the lookup.
child = child[1]
if hasattr(child, "flatten"):
yield from child.flatten()
else:
yield child
def check(self, against, using=DEFAULT_DB_ALIAS):
"""
Do a database query to check if the expressions of the Q instance
matches against the expressions.
"""
# Avoid circular imports.
from django.db.models import Value
from django.db.models.sql import Query
from django.db.models.sql.constants import SINGLE
query = Query(None)
for name, value in against.items():
if not hasattr(value, "resolve_expression"):
value = Value(value)
query.add_annotation(value, name, select=False)
query.add_annotation(Value(1), "_check")
# This will raise a FieldError if a field is missing in "against".
query.add_q(self)
compiler = query.get_compiler(using=using)
try:
return compiler.execute_sql(SINGLE) is not None
except DatabaseError as e:
logger.warning("Got a database error calling check() on %r: %s", self, e)
return True
def deconstruct(self):
path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
if path.startswith("django.db.models.query_utils"):
path = path.replace("django.db.models.query_utils", "django.db.models")
args = tuple(self.children)
kwargs = {}
if self.connector != self.default:
kwargs["_connector"] = self.connector
if self.negated:
kwargs["_negated"] = True
return path, args, kwargs
class DeferredAttribute:
"""
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
"""
def __init__(self, field):
self.field = field
def __get__(self, instance, cls=None):
"""
Retrieve and caches the value from the datastore on the first lookup.
Return the cached value.
"""
if instance is None:
return self
data = instance.__dict__
field_name = self.field.attname
if field_name not in data:
# Let's see if the field is part of the parent chain. If so we
# might be able to reuse the already loaded value. Refs #18343.
val = self._check_parent_chain(instance)
if val is None:
instance.refresh_from_db(fields=[field_name])
else:
data[field_name] = val
return data[field_name]
def _check_parent_chain(self, instance):
"""
Check if the field value can be fetched from a parent field already
loaded in the instance. This can be done if the to-be fetched
field is a primary key field.
"""
opts = instance._meta
link_field = opts.get_ancestor_link(self.field.model)
if self.field.primary_key and self.field != link_field:
return getattr(instance, link_field.attname)
return None
class RegisterLookupMixin:
@classmethod
def _get_lookup(cls, lookup_name):
return cls.get_lookups().get(lookup_name, None)
@classmethod
@functools.lru_cache(maxsize=None)
def get_lookups(cls):
class_lookups = [
parent.__dict__.get("class_lookups", {}) for parent in inspect.getmro(cls)
]
return cls.merge_dicts(class_lookups)
def get_lookup(self, lookup_name):
from django.db.models.lookups import Lookup
found = self._get_lookup(lookup_name)
if found is None and hasattr(self, "output_field"):
return self.output_field.get_lookup(lookup_name)
if found is not None and not issubclass(found, Lookup):
return None
return found
def get_transform(self, lookup_name):
from django.db.models.lookups import Transform
found = self._get_lookup(lookup_name)
if found is None and hasattr(self, "output_field"):
return self.output_field.get_transform(lookup_name)
if found is not None and not issubclass(found, Transform):
return None
return found
@staticmethod
def merge_dicts(dicts):
"""
Merge dicts in reverse to preference the order of the original list. e.g.,
merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'.
"""
merged = {}
for d in reversed(dicts):
merged.update(d)
return merged
@classmethod
def _clear_cached_lookups(cls):
for subclass in subclasses(cls):
subclass.get_lookups.cache_clear()
@classmethod
def register_lookup(cls, lookup, lookup_name=None):
if lookup_name is None:
lookup_name = lookup.lookup_name
if "class_lookups" not in cls.__dict__:
cls.class_lookups = {}
cls.class_lookups[lookup_name] = lookup
cls._clear_cached_lookups()
return lookup
@classmethod
def _unregister_lookup(cls, lookup, lookup_name=None):
"""
Remove given lookup from cls lookups. For use in tests only as it's
not thread-safe.
"""
if lookup_name is None:
lookup_name = lookup.lookup_name
del cls.class_lookups[lookup_name]
cls._clear_cached_lookups()
def select_related_descend(field, restricted, requested, load_fields, reverse=False):
"""
Return True if this field should be used to descend deeper for
select_related() purposes. Used by both the query construction code
(compiler.get_related_selections()) and the model instance creation code
(compiler.klass_info).
Arguments:
* field - the field to be checked
* restricted - a boolean field, indicating if the field list has been
manually restricted using a requested clause)
* requested - The select_related() dictionary.
* load_fields - the set of fields to be loaded on this model
* reverse - boolean, True if we are checking a reverse select related
"""
if not field.remote_field:
return False
if field.remote_field.parent_link and not reverse:
return False
if restricted:
if reverse and field.related_query_name() not in requested:
return False
if not reverse and field.name not in requested:
return False
if not restricted and field.null:
return False
if load_fields:
if field.attname not in load_fields:
if restricted and field.name in requested:
msg = (
"Field %s.%s cannot be both deferred and traversed using "
"select_related at the same time."
) % (field.model._meta.object_name, field.name)
raise FieldError(msg)
return True
def refs_expression(lookup_parts, annotations):
"""
Check if the lookup_parts contains references to the given annotations set.
Because the LOOKUP_SEP is contained in the default annotation names, check
each prefix of the lookup_parts for a match.
"""
for n in range(1, len(lookup_parts) + 1):
level_n_lookup = LOOKUP_SEP.join(lookup_parts[0:n])
if level_n_lookup in annotations and annotations[level_n_lookup]:
return annotations[level_n_lookup], lookup_parts[n:]
return False, ()
def check_rel_lookup_compatibility(model, target_opts, field):
"""
Check that self.model is compatible with target_opts. Compatibility
is OK if:
1) model and opts match (where proxy inheritance is removed)
2) model is parent of opts' model or the other way around
"""
def check(opts):
return (
model._meta.concrete_model == opts.concrete_model
or opts.concrete_model in model._meta.get_parent_list()
or model in opts.get_parent_list()
)
# If the field is a primary key, then doing a query against the field's
# model is ok, too. Consider the case:
# class Restaurant(models.Model):
# place = OneToOneField(Place, primary_key=True):
# Restaurant.objects.filter(pk__in=Restaurant.objects.all()).
# If we didn't have the primary key check, then pk__in (== place__in) would
# give Place's opts as the target opts, but Restaurant isn't compatible
# with that. This logic applies only to primary keys, as when doing __in=qs,
# we are going to turn this into __in=qs.values('pk') later on.
return check(target_opts) or (
getattr(field, "primary_key", False) and check(field.model._meta)
)
class FilteredRelation:
"""Specify custom filtering in the ON clause of SQL joins."""
def __init__(self, relation_name, *, condition=Q()):
if not relation_name:
raise ValueError("relation_name cannot be empty.")
self.relation_name = relation_name
self.alias = None
if not isinstance(condition, Q):
raise ValueError("condition argument must be a Q() instance.")
self.condition = condition
self.path = []
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return (
self.relation_name == other.relation_name
and self.alias == other.alias
and self.condition == other.condition
)
def clone(self):
clone = FilteredRelation(self.relation_name, condition=self.condition)
clone.alias = self.alias
clone.path = self.path[:]
return clone
def resolve_expression(self, *args, **kwargs):
"""
QuerySet.annotate() only accepts expression-like arguments
(with a resolve_expression() method).
"""
raise NotImplementedError("FilteredRelation.resolve_expression() is unused.")
def as_sql(self, compiler, connection):
# Resolve the condition in Join.filtered_relation.
query = compiler.query
where = query.build_filtered_relation_q(self.condition, reuse=set(self.path))
return compiler.compile(where)
|
3547a6d2563047f279eb4bcf7e2bad950bb32f91ded3aebf706f28028b90d4f2 | import copy
import datetime
import functools
import inspect
import warnings
from collections import defaultdict
from decimal import Decimal
from uuid import UUID
from django.core.exceptions import EmptyResultSet, FieldError
from django.db import DatabaseError, NotSupportedError, connection
from django.db.models import fields
from django.db.models.constants import LOOKUP_SEP
from django.db.models.query_utils import Q
from django.utils.deconstruct import deconstructible
from django.utils.deprecation import RemovedInDjango50Warning
from django.utils.functional import cached_property
from django.utils.hashable import make_hashable
class SQLiteNumericMixin:
"""
Some expressions with output_field=DecimalField() must be cast to
numeric to be properly filtered.
"""
def as_sqlite(self, compiler, connection, **extra_context):
sql, params = self.as_sql(compiler, connection, **extra_context)
try:
if self.output_field.get_internal_type() == "DecimalField":
sql = "CAST(%s AS NUMERIC)" % sql
except FieldError:
pass
return sql, params
class Combinable:
"""
Provide the ability to combine one or two objects with
some connector. For example F('foo') + F('bar').
"""
# Arithmetic connectors
ADD = "+"
SUB = "-"
MUL = "*"
DIV = "/"
POW = "^"
# The following is a quoted % operator - it is quoted because it can be
# used in strings that also have parameter substitution.
MOD = "%%"
# Bitwise operators - note that these are generated by .bitand()
# and .bitor(), the '&' and '|' are reserved for boolean operator
# usage.
BITAND = "&"
BITOR = "|"
BITLEFTSHIFT = "<<"
BITRIGHTSHIFT = ">>"
BITXOR = "#"
def _combine(self, other, connector, reversed):
if not hasattr(other, "resolve_expression"):
# everything must be resolvable to an expression
other = Value(other)
if reversed:
return CombinedExpression(other, connector, self)
return CombinedExpression(self, connector, other)
#############
# OPERATORS #
#############
def __neg__(self):
return self._combine(-1, self.MUL, False)
def __add__(self, other):
return self._combine(other, self.ADD, False)
def __sub__(self, other):
return self._combine(other, self.SUB, False)
def __mul__(self, other):
return self._combine(other, self.MUL, False)
def __truediv__(self, other):
return self._combine(other, self.DIV, False)
def __mod__(self, other):
return self._combine(other, self.MOD, False)
def __pow__(self, other):
return self._combine(other, self.POW, False)
def __and__(self, other):
if getattr(self, "conditional", False) and getattr(other, "conditional", False):
return Q(self) & Q(other)
raise NotImplementedError(
"Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
)
def bitand(self, other):
return self._combine(other, self.BITAND, False)
def bitleftshift(self, other):
return self._combine(other, self.BITLEFTSHIFT, False)
def bitrightshift(self, other):
return self._combine(other, self.BITRIGHTSHIFT, False)
def __xor__(self, other):
if getattr(self, "conditional", False) and getattr(other, "conditional", False):
return Q(self) ^ Q(other)
raise NotImplementedError(
"Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
)
def bitxor(self, other):
return self._combine(other, self.BITXOR, False)
def __or__(self, other):
if getattr(self, "conditional", False) and getattr(other, "conditional", False):
return Q(self) | Q(other)
raise NotImplementedError(
"Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
)
def bitor(self, other):
return self._combine(other, self.BITOR, False)
def __radd__(self, other):
return self._combine(other, self.ADD, True)
def __rsub__(self, other):
return self._combine(other, self.SUB, True)
def __rmul__(self, other):
return self._combine(other, self.MUL, True)
def __rtruediv__(self, other):
return self._combine(other, self.DIV, True)
def __rmod__(self, other):
return self._combine(other, self.MOD, True)
def __rpow__(self, other):
return self._combine(other, self.POW, True)
def __rand__(self, other):
raise NotImplementedError(
"Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
)
def __ror__(self, other):
raise NotImplementedError(
"Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
)
def __rxor__(self, other):
raise NotImplementedError(
"Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
)
class BaseExpression:
"""Base class for all query expressions."""
empty_result_set_value = NotImplemented
# aggregate specific fields
is_summary = False
_output_field_resolved_to_none = False
# Can the expression be used in a WHERE clause?
filterable = True
# Can the expression can be used as a source expression in Window?
window_compatible = False
def __init__(self, output_field=None):
if output_field is not None:
self.output_field = output_field
def __getstate__(self):
state = self.__dict__.copy()
state.pop("convert_value", None)
return state
def get_db_converters(self, connection):
return (
[]
if self.convert_value is self._convert_value_noop
else [self.convert_value]
) + self.output_field.get_db_converters(connection)
def get_source_expressions(self):
return []
def set_source_expressions(self, exprs):
assert not exprs
def _parse_expressions(self, *expressions):
return [
arg
if hasattr(arg, "resolve_expression")
else (F(arg) if isinstance(arg, str) else Value(arg))
for arg in expressions
]
def as_sql(self, compiler, connection):
"""
Responsible for returning a (sql, [params]) tuple to be included
in the current query.
Different backends can provide their own implementation, by
providing an `as_{vendor}` method and patching the Expression:
```
def override_as_sql(self, compiler, connection):
# custom logic
return super().as_sql(compiler, connection)
setattr(Expression, 'as_' + connection.vendor, override_as_sql)
```
Arguments:
* compiler: the query compiler responsible for generating the query.
Must have a compile method, returning a (sql, [params]) tuple.
Calling compiler(value) will return a quoted `value`.
* connection: the database connection used for the current query.
Return: (sql, params)
Where `sql` is a string containing ordered sql parameters to be
replaced with the elements of the list `params`.
"""
raise NotImplementedError("Subclasses must implement as_sql()")
@cached_property
def contains_aggregate(self):
return any(
expr and expr.contains_aggregate for expr in self.get_source_expressions()
)
@cached_property
def contains_over_clause(self):
return any(
expr and expr.contains_over_clause for expr in self.get_source_expressions()
)
@cached_property
def contains_column_references(self):
return any(
expr and expr.contains_column_references
for expr in self.get_source_expressions()
)
def resolve_expression(
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
):
"""
Provide the chance to do any preprocessing or validation before being
added to the query.
Arguments:
* query: the backend query implementation
* allow_joins: boolean allowing or denying use of joins
in this query
* reuse: a set of reusable joins for multijoins
* summarize: a terminal aggregate clause
* for_save: whether this expression about to be used in a save or update
Return: an Expression to be added to the query.
"""
c = self.copy()
c.is_summary = summarize
c.set_source_expressions(
[
expr.resolve_expression(query, allow_joins, reuse, summarize)
if expr
else None
for expr in c.get_source_expressions()
]
)
return c
@property
def conditional(self):
return isinstance(self.output_field, fields.BooleanField)
@property
def field(self):
return self.output_field
@cached_property
def output_field(self):
"""Return the output type of this expressions."""
output_field = self._resolve_output_field()
if output_field is None:
self._output_field_resolved_to_none = True
raise FieldError("Cannot resolve expression type, unknown output_field")
return output_field
@cached_property
def _output_field_or_none(self):
"""
Return the output field of this expression, or None if
_resolve_output_field() didn't return an output type.
"""
try:
return self.output_field
except FieldError:
if not self._output_field_resolved_to_none:
raise
def _resolve_output_field(self):
"""
Attempt to infer the output type of the expression.
As a guess, if the output fields of all source fields match then simply
infer the same type here.
If a source's output field resolves to None, exclude it from this check.
If all sources are None, then an error is raised higher up the stack in
the output_field property.
"""
# This guess is mostly a bad idea, but there is quite a lot of code
# (especially 3rd party Func subclasses) that depend on it, we'd need a
# deprecation path to fix it.
sources_iter = (
source for source in self.get_source_fields() if source is not None
)
for output_field in sources_iter:
for source in sources_iter:
if not isinstance(output_field, source.__class__):
raise FieldError(
"Expression contains mixed types: %s, %s. You must "
"set output_field."
% (
output_field.__class__.__name__,
source.__class__.__name__,
)
)
return output_field
@staticmethod
def _convert_value_noop(value, expression, connection):
return value
@cached_property
def convert_value(self):
"""
Expressions provide their own converters because users have the option
of manually specifying the output_field which may be a different type
from the one the database returns.
"""
field = self.output_field
internal_type = field.get_internal_type()
if internal_type == "FloatField":
return (
lambda value, expression, connection: None
if value is None
else float(value)
)
elif internal_type.endswith("IntegerField"):
return (
lambda value, expression, connection: None
if value is None
else int(value)
)
elif internal_type == "DecimalField":
return (
lambda value, expression, connection: None
if value is None
else Decimal(value)
)
return self._convert_value_noop
def get_lookup(self, lookup):
return self.output_field.get_lookup(lookup)
def get_transform(self, name):
return self.output_field.get_transform(name)
def relabeled_clone(self, change_map):
clone = self.copy()
clone.set_source_expressions(
[
e.relabeled_clone(change_map) if e is not None else None
for e in self.get_source_expressions()
]
)
return clone
def replace_references(self, references_map):
clone = self.copy()
clone.set_source_expressions(
[
references_map.get(expr.name, expr)
if isinstance(expr, F)
else expr.replace_references(references_map)
for expr in self.get_source_expressions()
]
)
return clone
def copy(self):
return copy.copy(self)
def prefix_references(self, prefix):
clone = self.copy()
clone.set_source_expressions(
[
F(f"{prefix}{expr.name}")
if isinstance(expr, F)
else expr.prefix_references(prefix)
for expr in self.get_source_expressions()
]
)
return clone
def get_group_by_cols(self, alias=None):
if not self.contains_aggregate:
return [self]
cols = []
for source in self.get_source_expressions():
cols.extend(source.get_group_by_cols())
return cols
def get_source_fields(self):
"""Return the underlying field types used by this aggregate."""
return [e._output_field_or_none for e in self.get_source_expressions()]
def asc(self, **kwargs):
return OrderBy(self, **kwargs)
def desc(self, **kwargs):
return OrderBy(self, descending=True, **kwargs)
def reverse_ordering(self):
return self
def flatten(self):
"""
Recursively yield this expression and all subexpressions, in
depth-first order.
"""
yield self
for expr in self.get_source_expressions():
if expr:
if hasattr(expr, "flatten"):
yield from expr.flatten()
else:
yield expr
def select_format(self, compiler, sql, params):
"""
Custom format for select clauses. For example, EXISTS expressions need
to be wrapped in CASE WHEN on Oracle.
"""
if hasattr(self.output_field, "select_format"):
return self.output_field.select_format(compiler, sql, params)
return sql, params
@deconstructible
class Expression(BaseExpression, Combinable):
"""An expression that can be combined with other expressions."""
@cached_property
def identity(self):
constructor_signature = inspect.signature(self.__init__)
args, kwargs = self._constructor_args
signature = constructor_signature.bind_partial(*args, **kwargs)
signature.apply_defaults()
arguments = signature.arguments.items()
identity = [self.__class__]
for arg, value in arguments:
if isinstance(value, fields.Field):
if value.name and value.model:
value = (value.model._meta.label, value.name)
else:
value = type(value)
else:
value = make_hashable(value)
identity.append((arg, value))
return tuple(identity)
def __eq__(self, other):
if not isinstance(other, Expression):
return NotImplemented
return other.identity == self.identity
def __hash__(self):
return hash(self.identity)
# Type inference for CombinedExpression.output_field.
# Missing items will result in FieldError, by design.
#
# The current approach for NULL is based on lowest common denominator behavior
# i.e. if one of the supported databases is raising an error (rather than
# return NULL) for `val <op> NULL`, then Django raises FieldError.
NoneType = type(None)
_connector_combinations = [
# Numeric operations - operands of same type.
{
connector: [
(fields.IntegerField, fields.IntegerField, fields.IntegerField),
(fields.FloatField, fields.FloatField, fields.FloatField),
(fields.DecimalField, fields.DecimalField, fields.DecimalField),
]
for connector in (
Combinable.ADD,
Combinable.SUB,
Combinable.MUL,
# Behavior for DIV with integer arguments follows Postgres/SQLite,
# not MySQL/Oracle.
Combinable.DIV,
Combinable.MOD,
Combinable.POW,
)
},
# Numeric operations - operands of different type.
{
connector: [
(fields.IntegerField, fields.DecimalField, fields.DecimalField),
(fields.DecimalField, fields.IntegerField, fields.DecimalField),
(fields.IntegerField, fields.FloatField, fields.FloatField),
(fields.FloatField, fields.IntegerField, fields.FloatField),
]
for connector in (
Combinable.ADD,
Combinable.SUB,
Combinable.MUL,
Combinable.DIV,
)
},
# Bitwise operators.
{
connector: [
(fields.IntegerField, fields.IntegerField, fields.IntegerField),
]
for connector in (
Combinable.BITAND,
Combinable.BITOR,
Combinable.BITLEFTSHIFT,
Combinable.BITRIGHTSHIFT,
Combinable.BITXOR,
)
},
# Numeric with NULL.
{
connector: [
(field_type, NoneType, field_type),
(NoneType, field_type, field_type),
]
for connector in (
Combinable.ADD,
Combinable.SUB,
Combinable.MUL,
Combinable.DIV,
Combinable.MOD,
Combinable.POW,
)
for field_type in (fields.IntegerField, fields.DecimalField, fields.FloatField)
},
# Date/DateTimeField/DurationField/TimeField.
{
Combinable.ADD: [
# Date/DateTimeField.
(fields.DateField, fields.DurationField, fields.DateTimeField),
(fields.DateTimeField, fields.DurationField, fields.DateTimeField),
(fields.DurationField, fields.DateField, fields.DateTimeField),
(fields.DurationField, fields.DateTimeField, fields.DateTimeField),
# DurationField.
(fields.DurationField, fields.DurationField, fields.DurationField),
# TimeField.
(fields.TimeField, fields.DurationField, fields.TimeField),
(fields.DurationField, fields.TimeField, fields.TimeField),
],
},
{
Combinable.SUB: [
# Date/DateTimeField.
(fields.DateField, fields.DurationField, fields.DateTimeField),
(fields.DateTimeField, fields.DurationField, fields.DateTimeField),
(fields.DateField, fields.DateField, fields.DurationField),
(fields.DateField, fields.DateTimeField, fields.DurationField),
(fields.DateTimeField, fields.DateField, fields.DurationField),
(fields.DateTimeField, fields.DateTimeField, fields.DurationField),
# DurationField.
(fields.DurationField, fields.DurationField, fields.DurationField),
# TimeField.
(fields.TimeField, fields.DurationField, fields.TimeField),
(fields.TimeField, fields.TimeField, fields.DurationField),
],
},
]
_connector_combinators = defaultdict(list)
def register_combinable_fields(lhs, connector, rhs, result):
"""
Register combinable types:
lhs <connector> rhs -> result
e.g.
register_combinable_fields(
IntegerField, Combinable.ADD, FloatField, FloatField
)
"""
_connector_combinators[connector].append((lhs, rhs, result))
for d in _connector_combinations:
for connector, field_types in d.items():
for lhs, rhs, result in field_types:
register_combinable_fields(lhs, connector, rhs, result)
@functools.lru_cache(maxsize=128)
def _resolve_combined_type(connector, lhs_type, rhs_type):
combinators = _connector_combinators.get(connector, ())
for combinator_lhs_type, combinator_rhs_type, combined_type in combinators:
if issubclass(lhs_type, combinator_lhs_type) and issubclass(
rhs_type, combinator_rhs_type
):
return combined_type
class CombinedExpression(SQLiteNumericMixin, Expression):
def __init__(self, lhs, connector, rhs, output_field=None):
super().__init__(output_field=output_field)
self.connector = connector
self.lhs = lhs
self.rhs = rhs
def __repr__(self):
return "<{}: {}>".format(self.__class__.__name__, self)
def __str__(self):
return "{} {} {}".format(self.lhs, self.connector, self.rhs)
def get_source_expressions(self):
return [self.lhs, self.rhs]
def set_source_expressions(self, exprs):
self.lhs, self.rhs = exprs
def _resolve_output_field(self):
# We avoid using super() here for reasons given in
# Expression._resolve_output_field()
combined_type = _resolve_combined_type(
self.connector,
type(self.lhs._output_field_or_none),
type(self.rhs._output_field_or_none),
)
if combined_type is None:
raise FieldError(
f"Cannot infer type of {self.connector!r} expression involving these "
f"types: {self.lhs.output_field.__class__.__name__}, "
f"{self.rhs.output_field.__class__.__name__}. You must set "
f"output_field."
)
return combined_type()
def as_sql(self, compiler, connection):
expressions = []
expression_params = []
sql, params = compiler.compile(self.lhs)
expressions.append(sql)
expression_params.extend(params)
sql, params = compiler.compile(self.rhs)
expressions.append(sql)
expression_params.extend(params)
# order of precedence
expression_wrapper = "(%s)"
sql = connection.ops.combine_expression(self.connector, expressions)
return expression_wrapper % sql, expression_params
def resolve_expression(
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
):
lhs = self.lhs.resolve_expression(
query, allow_joins, reuse, summarize, for_save
)
rhs = self.rhs.resolve_expression(
query, allow_joins, reuse, summarize, for_save
)
if not isinstance(self, (DurationExpression, TemporalSubtraction)):
try:
lhs_type = lhs.output_field.get_internal_type()
except (AttributeError, FieldError):
lhs_type = None
try:
rhs_type = rhs.output_field.get_internal_type()
except (AttributeError, FieldError):
rhs_type = None
if "DurationField" in {lhs_type, rhs_type} and lhs_type != rhs_type:
return DurationExpression(
self.lhs, self.connector, self.rhs
).resolve_expression(
query,
allow_joins,
reuse,
summarize,
for_save,
)
datetime_fields = {"DateField", "DateTimeField", "TimeField"}
if (
self.connector == self.SUB
and lhs_type in datetime_fields
and lhs_type == rhs_type
):
return TemporalSubtraction(self.lhs, self.rhs).resolve_expression(
query,
allow_joins,
reuse,
summarize,
for_save,
)
c = self.copy()
c.is_summary = summarize
c.lhs = lhs
c.rhs = rhs
return c
class DurationExpression(CombinedExpression):
def compile(self, side, compiler, connection):
try:
output = side.output_field
except FieldError:
pass
else:
if output.get_internal_type() == "DurationField":
sql, params = compiler.compile(side)
return connection.ops.format_for_duration_arithmetic(sql), params
return compiler.compile(side)
def as_sql(self, compiler, connection):
if connection.features.has_native_duration_field:
return super().as_sql(compiler, connection)
connection.ops.check_expression_support(self)
expressions = []
expression_params = []
sql, params = self.compile(self.lhs, compiler, connection)
expressions.append(sql)
expression_params.extend(params)
sql, params = self.compile(self.rhs, compiler, connection)
expressions.append(sql)
expression_params.extend(params)
# order of precedence
expression_wrapper = "(%s)"
sql = connection.ops.combine_duration_expression(self.connector, expressions)
return expression_wrapper % sql, expression_params
def as_sqlite(self, compiler, connection, **extra_context):
sql, params = self.as_sql(compiler, connection, **extra_context)
if self.connector in {Combinable.MUL, Combinable.DIV}:
try:
lhs_type = self.lhs.output_field.get_internal_type()
rhs_type = self.rhs.output_field.get_internal_type()
except (AttributeError, FieldError):
pass
else:
allowed_fields = {
"DecimalField",
"DurationField",
"FloatField",
"IntegerField",
}
if lhs_type not in allowed_fields or rhs_type not in allowed_fields:
raise DatabaseError(
f"Invalid arguments for operator {self.connector}."
)
return sql, params
class TemporalSubtraction(CombinedExpression):
output_field = fields.DurationField()
def __init__(self, lhs, rhs):
super().__init__(lhs, self.SUB, rhs)
def as_sql(self, compiler, connection):
connection.ops.check_expression_support(self)
lhs = compiler.compile(self.lhs)
rhs = compiler.compile(self.rhs)
return connection.ops.subtract_temporals(
self.lhs.output_field.get_internal_type(), lhs, rhs
)
@deconstructible(path="django.db.models.F")
class F(Combinable):
"""An object capable of resolving references to existing query objects."""
def __init__(self, name):
"""
Arguments:
* name: the name of the field this expression references
"""
self.name = name
def __repr__(self):
return "{}({})".format(self.__class__.__name__, self.name)
def resolve_expression(
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
):
return query.resolve_ref(self.name, allow_joins, reuse, summarize)
def asc(self, **kwargs):
return OrderBy(self, **kwargs)
def desc(self, **kwargs):
return OrderBy(self, descending=True, **kwargs)
def __eq__(self, other):
return self.__class__ == other.__class__ and self.name == other.name
def __hash__(self):
return hash(self.name)
class ResolvedOuterRef(F):
"""
An object that contains a reference to an outer query.
In this case, the reference to the outer query has been resolved because
the inner query has been used as a subquery.
"""
contains_aggregate = False
def as_sql(self, *args, **kwargs):
raise ValueError(
"This queryset contains a reference to an outer query and may "
"only be used in a subquery."
)
def resolve_expression(self, *args, **kwargs):
col = super().resolve_expression(*args, **kwargs)
# FIXME: Rename possibly_multivalued to multivalued and fix detection
# for non-multivalued JOINs (e.g. foreign key fields). This should take
# into account only many-to-many and one-to-many relationships.
col.possibly_multivalued = LOOKUP_SEP in self.name
return col
def relabeled_clone(self, relabels):
return self
def get_group_by_cols(self, alias=None):
return []
class OuterRef(F):
contains_aggregate = False
def resolve_expression(self, *args, **kwargs):
if isinstance(self.name, self.__class__):
return self.name
return ResolvedOuterRef(self.name)
def relabeled_clone(self, relabels):
return self
@deconstructible(path="django.db.models.Func")
class Func(SQLiteNumericMixin, Expression):
"""An SQL function call."""
function = None
template = "%(function)s(%(expressions)s)"
arg_joiner = ", "
arity = None # The number of arguments the function accepts.
def __init__(self, *expressions, output_field=None, **extra):
if self.arity is not None and len(expressions) != self.arity:
raise TypeError(
"'%s' takes exactly %s %s (%s given)"
% (
self.__class__.__name__,
self.arity,
"argument" if self.arity == 1 else "arguments",
len(expressions),
)
)
super().__init__(output_field=output_field)
self.source_expressions = self._parse_expressions(*expressions)
self.extra = extra
def __repr__(self):
args = self.arg_joiner.join(str(arg) for arg in self.source_expressions)
extra = {**self.extra, **self._get_repr_options()}
if extra:
extra = ", ".join(
str(key) + "=" + str(val) for key, val in sorted(extra.items())
)
return "{}({}, {})".format(self.__class__.__name__, args, extra)
return "{}({})".format(self.__class__.__name__, args)
def _get_repr_options(self):
"""Return a dict of extra __init__() options to include in the repr."""
return {}
def get_source_expressions(self):
return self.source_expressions
def set_source_expressions(self, exprs):
self.source_expressions = exprs
def resolve_expression(
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
):
c = self.copy()
c.is_summary = summarize
for pos, arg in enumerate(c.source_expressions):
c.source_expressions[pos] = arg.resolve_expression(
query, allow_joins, reuse, summarize, for_save
)
return c
def as_sql(
self,
compiler,
connection,
function=None,
template=None,
arg_joiner=None,
**extra_context,
):
connection.ops.check_expression_support(self)
sql_parts = []
params = []
for arg in self.source_expressions:
try:
arg_sql, arg_params = compiler.compile(arg)
except EmptyResultSet:
empty_result_set_value = getattr(
arg, "empty_result_set_value", NotImplemented
)
if empty_result_set_value is NotImplemented:
raise
arg_sql, arg_params = compiler.compile(Value(empty_result_set_value))
sql_parts.append(arg_sql)
params.extend(arg_params)
data = {**self.extra, **extra_context}
# Use the first supplied value in this order: the parameter to this
# method, a value supplied in __init__()'s **extra (the value in
# `data`), or the value defined on the class.
if function is not None:
data["function"] = function
else:
data.setdefault("function", self.function)
template = template or data.get("template", self.template)
arg_joiner = arg_joiner or data.get("arg_joiner", self.arg_joiner)
data["expressions"] = data["field"] = arg_joiner.join(sql_parts)
return template % data, params
def copy(self):
copy = super().copy()
copy.source_expressions = self.source_expressions[:]
copy.extra = self.extra.copy()
return copy
@deconstructible(path="django.db.models.Value")
class Value(SQLiteNumericMixin, Expression):
"""Represent a wrapped value as a node within an expression."""
# Provide a default value for `for_save` in order to allow unresolved
# instances to be compiled until a decision is taken in #25425.
for_save = False
def __init__(self, value, output_field=None):
"""
Arguments:
* value: the value this expression represents. The value will be
added into the sql parameter list and properly quoted.
* output_field: an instance of the model field type that this
expression will return, such as IntegerField() or CharField().
"""
super().__init__(output_field=output_field)
self.value = value
def __repr__(self):
return f"{self.__class__.__name__}({self.value!r})"
def as_sql(self, compiler, connection):
connection.ops.check_expression_support(self)
val = self.value
output_field = self._output_field_or_none
if output_field is not None:
if self.for_save:
val = output_field.get_db_prep_save(val, connection=connection)
else:
val = output_field.get_db_prep_value(val, connection=connection)
if hasattr(output_field, "get_placeholder"):
return output_field.get_placeholder(val, compiler, connection), [val]
if val is None:
# cx_Oracle does not always convert None to the appropriate
# NULL type (like in case expressions using numbers), so we
# use a literal SQL NULL
return "NULL", []
return "%s", [val]
def resolve_expression(
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
):
c = super().resolve_expression(query, allow_joins, reuse, summarize, for_save)
c.for_save = for_save
return c
def get_group_by_cols(self, alias=None):
return []
def _resolve_output_field(self):
if isinstance(self.value, str):
return fields.CharField()
if isinstance(self.value, bool):
return fields.BooleanField()
if isinstance(self.value, int):
return fields.IntegerField()
if isinstance(self.value, float):
return fields.FloatField()
if isinstance(self.value, datetime.datetime):
return fields.DateTimeField()
if isinstance(self.value, datetime.date):
return fields.DateField()
if isinstance(self.value, datetime.time):
return fields.TimeField()
if isinstance(self.value, datetime.timedelta):
return fields.DurationField()
if isinstance(self.value, Decimal):
return fields.DecimalField()
if isinstance(self.value, bytes):
return fields.BinaryField()
if isinstance(self.value, UUID):
return fields.UUIDField()
@property
def empty_result_set_value(self):
return self.value
class RawSQL(Expression):
def __init__(self, sql, params, output_field=None):
if output_field is None:
output_field = fields.Field()
self.sql, self.params = sql, params
super().__init__(output_field=output_field)
def __repr__(self):
return "{}({}, {})".format(self.__class__.__name__, self.sql, self.params)
def as_sql(self, compiler, connection):
return "(%s)" % self.sql, self.params
def get_group_by_cols(self, alias=None):
return [self]
def resolve_expression(
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
):
# Resolve parents fields used in raw SQL.
if query.model:
for parent in query.model._meta.get_parent_list():
for parent_field in parent._meta.local_fields:
_, column_name = parent_field.get_attname_column()
if column_name.lower() in self.sql.lower():
query.resolve_ref(
parent_field.name, allow_joins, reuse, summarize
)
break
return super().resolve_expression(
query, allow_joins, reuse, summarize, for_save
)
class Star(Expression):
def __repr__(self):
return "'*'"
def as_sql(self, compiler, connection):
return "*", []
class Col(Expression):
contains_column_references = True
possibly_multivalued = False
def __init__(self, alias, target, output_field=None):
if output_field is None:
output_field = target
super().__init__(output_field=output_field)
self.alias, self.target = alias, target
def __repr__(self):
alias, target = self.alias, self.target
identifiers = (alias, str(target)) if alias else (str(target),)
return "{}({})".format(self.__class__.__name__, ", ".join(identifiers))
def as_sql(self, compiler, connection):
alias, column = self.alias, self.target.column
identifiers = (alias, column) if alias else (column,)
sql = ".".join(map(compiler.quote_name_unless_alias, identifiers))
return sql, []
def relabeled_clone(self, relabels):
if self.alias is None:
return self
return self.__class__(
relabels.get(self.alias, self.alias), self.target, self.output_field
)
def get_group_by_cols(self, alias=None):
return [self]
def get_db_converters(self, connection):
if self.target == self.output_field:
return self.output_field.get_db_converters(connection)
return self.output_field.get_db_converters(
connection
) + self.target.get_db_converters(connection)
class Ref(Expression):
"""
Reference to column alias of the query. For example, Ref('sum_cost') in
qs.annotate(sum_cost=Sum('cost')) query.
"""
def __init__(self, refs, source):
super().__init__()
self.refs, self.source = refs, source
def __repr__(self):
return "{}({}, {})".format(self.__class__.__name__, self.refs, self.source)
def get_source_expressions(self):
return [self.source]
def set_source_expressions(self, exprs):
(self.source,) = exprs
def resolve_expression(
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
):
# The sub-expression `source` has already been resolved, as this is
# just a reference to the name of `source`.
return self
def relabeled_clone(self, relabels):
return self
def as_sql(self, compiler, connection):
return connection.ops.quote_name(self.refs), []
def get_group_by_cols(self, alias=None):
return [self]
class ExpressionList(Func):
"""
An expression containing multiple expressions. Can be used to provide a
list of expressions as an argument to another expression, like a partition
clause.
"""
template = "%(expressions)s"
def __init__(self, *expressions, **extra):
if not expressions:
raise ValueError(
"%s requires at least one expression." % self.__class__.__name__
)
super().__init__(*expressions, **extra)
def __str__(self):
return self.arg_joiner.join(str(arg) for arg in self.source_expressions)
def as_sqlite(self, compiler, connection, **extra_context):
# Casting to numeric is unnecessary.
return self.as_sql(compiler, connection, **extra_context)
class OrderByList(Func):
template = "ORDER BY %(expressions)s"
def __init__(self, *expressions, **extra):
expressions = (
(
OrderBy(F(expr[1:]), descending=True)
if isinstance(expr, str) and expr[0] == "-"
else expr
)
for expr in expressions
)
super().__init__(*expressions, **extra)
def as_sql(self, *args, **kwargs):
if not self.source_expressions:
return "", ()
return super().as_sql(*args, **kwargs)
@deconstructible(path="django.db.models.ExpressionWrapper")
class ExpressionWrapper(SQLiteNumericMixin, Expression):
"""
An expression that can wrap another expression so that it can provide
extra context to the inner expression, such as the output_field.
"""
def __init__(self, expression, output_field):
super().__init__(output_field=output_field)
self.expression = expression
def set_source_expressions(self, exprs):
self.expression = exprs[0]
def get_source_expressions(self):
return [self.expression]
def get_group_by_cols(self, alias=None):
if isinstance(self.expression, Expression):
expression = self.expression.copy()
expression.output_field = self.output_field
return expression.get_group_by_cols(alias=alias)
# For non-expressions e.g. an SQL WHERE clause, the entire
# `expression` must be included in the GROUP BY clause.
return super().get_group_by_cols()
def as_sql(self, compiler, connection):
return compiler.compile(self.expression)
def __repr__(self):
return "{}({})".format(self.__class__.__name__, self.expression)
@deconstructible(path="django.db.models.When")
class When(Expression):
template = "WHEN %(condition)s THEN %(result)s"
# This isn't a complete conditional expression, must be used in Case().
conditional = False
def __init__(self, condition=None, then=None, **lookups):
if lookups:
if condition is None:
condition, lookups = Q(**lookups), None
elif getattr(condition, "conditional", False):
condition, lookups = Q(condition, **lookups), None
if condition is None or not getattr(condition, "conditional", False) or lookups:
raise TypeError(
"When() supports a Q object, a boolean expression, or lookups "
"as a condition."
)
if isinstance(condition, Q) and not condition:
raise ValueError("An empty Q() can't be used as a When() condition.")
super().__init__(output_field=None)
self.condition = condition
self.result = self._parse_expressions(then)[0]
def __str__(self):
return "WHEN %r THEN %r" % (self.condition, self.result)
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self)
def get_source_expressions(self):
return [self.condition, self.result]
def set_source_expressions(self, exprs):
self.condition, self.result = exprs
def get_source_fields(self):
# We're only interested in the fields of the result expressions.
return [self.result._output_field_or_none]
def resolve_expression(
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
):
c = self.copy()
c.is_summary = summarize
if hasattr(c.condition, "resolve_expression"):
c.condition = c.condition.resolve_expression(
query, allow_joins, reuse, summarize, False
)
c.result = c.result.resolve_expression(
query, allow_joins, reuse, summarize, for_save
)
return c
def as_sql(self, compiler, connection, template=None, **extra_context):
connection.ops.check_expression_support(self)
template_params = extra_context
sql_params = []
condition_sql, condition_params = compiler.compile(self.condition)
template_params["condition"] = condition_sql
sql_params.extend(condition_params)
result_sql, result_params = compiler.compile(self.result)
template_params["result"] = result_sql
sql_params.extend(result_params)
template = template or self.template
return template % template_params, sql_params
def get_group_by_cols(self, alias=None):
# This is not a complete expression and cannot be used in GROUP BY.
cols = []
for source in self.get_source_expressions():
cols.extend(source.get_group_by_cols())
return cols
@deconstructible(path="django.db.models.Case")
class Case(SQLiteNumericMixin, Expression):
"""
An SQL searched CASE expression:
CASE
WHEN n > 0
THEN 'positive'
WHEN n < 0
THEN 'negative'
ELSE 'zero'
END
"""
template = "CASE %(cases)s ELSE %(default)s END"
case_joiner = " "
def __init__(self, *cases, default=None, output_field=None, **extra):
if not all(isinstance(case, When) for case in cases):
raise TypeError("Positional arguments must all be When objects.")
super().__init__(output_field)
self.cases = list(cases)
self.default = self._parse_expressions(default)[0]
self.extra = extra
def __str__(self):
return "CASE %s, ELSE %r" % (
", ".join(str(c) for c in self.cases),
self.default,
)
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self)
def get_source_expressions(self):
return self.cases + [self.default]
def set_source_expressions(self, exprs):
*self.cases, self.default = exprs
def resolve_expression(
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
):
c = self.copy()
c.is_summary = summarize
for pos, case in enumerate(c.cases):
c.cases[pos] = case.resolve_expression(
query, allow_joins, reuse, summarize, for_save
)
c.default = c.default.resolve_expression(
query, allow_joins, reuse, summarize, for_save
)
return c
def copy(self):
c = super().copy()
c.cases = c.cases[:]
return c
def as_sql(
self, compiler, connection, template=None, case_joiner=None, **extra_context
):
connection.ops.check_expression_support(self)
if not self.cases:
return compiler.compile(self.default)
template_params = {**self.extra, **extra_context}
case_parts = []
sql_params = []
for case in self.cases:
try:
case_sql, case_params = compiler.compile(case)
except EmptyResultSet:
continue
case_parts.append(case_sql)
sql_params.extend(case_params)
default_sql, default_params = compiler.compile(self.default)
if not case_parts:
return default_sql, default_params
case_joiner = case_joiner or self.case_joiner
template_params["cases"] = case_joiner.join(case_parts)
template_params["default"] = default_sql
sql_params.extend(default_params)
template = template or template_params.get("template", self.template)
sql = template % template_params
if self._output_field_or_none is not None:
sql = connection.ops.unification_cast_sql(self.output_field) % sql
return sql, sql_params
def get_group_by_cols(self, alias=None):
if not self.cases:
return self.default.get_group_by_cols(alias)
return super().get_group_by_cols(alias)
class Subquery(BaseExpression, Combinable):
"""
An explicit subquery. It may contain OuterRef() references to the outer
query which will be resolved when it is applied to that query.
"""
template = "(%(subquery)s)"
contains_aggregate = False
empty_result_set_value = None
def __init__(self, queryset, output_field=None, **extra):
# Allow the usage of both QuerySet and sql.Query objects.
self.query = getattr(queryset, "query", queryset).clone()
self.query.subquery = True
self.extra = extra
super().__init__(output_field)
def get_source_expressions(self):
return [self.query]
def set_source_expressions(self, exprs):
self.query = exprs[0]
def _resolve_output_field(self):
return self.query.output_field
def copy(self):
clone = super().copy()
clone.query = clone.query.clone()
return clone
@property
def external_aliases(self):
return self.query.external_aliases
def get_external_cols(self):
return self.query.get_external_cols()
def as_sql(self, compiler, connection, template=None, query=None, **extra_context):
connection.ops.check_expression_support(self)
template_params = {**self.extra, **extra_context}
query = query or self.query
subquery_sql, sql_params = query.as_sql(compiler, connection)
template_params["subquery"] = subquery_sql[1:-1]
template = template or template_params.get("template", self.template)
sql = template % template_params
return sql, sql_params
def get_group_by_cols(self, alias=None):
# If this expression is referenced by an alias for an explicit GROUP BY
# through values() a reference to this expression and not the
# underlying .query must be returned to ensure external column
# references are not grouped against as well.
if alias:
return [Ref(alias, self)]
return self.query.get_group_by_cols()
class Exists(Subquery):
template = "EXISTS(%(subquery)s)"
output_field = fields.BooleanField()
def __init__(self, queryset, negated=False, **kwargs):
self.negated = negated
super().__init__(queryset, **kwargs)
def __invert__(self):
clone = self.copy()
clone.negated = not self.negated
return clone
def as_sql(self, compiler, connection, template=None, **extra_context):
query = self.query.exists(using=connection.alias)
try:
sql, params = super().as_sql(
compiler,
connection,
template=template,
query=query,
**extra_context,
)
except EmptyResultSet:
if self.negated:
features = compiler.connection.features
if not features.supports_boolean_expr_in_select_clause:
return "1=1", ()
return compiler.compile(Value(True))
raise
if self.negated:
sql = "NOT {}".format(sql)
return sql, params
def select_format(self, compiler, sql, params):
# Wrap EXISTS() with a CASE WHEN expression if a database backend
# (e.g. Oracle) doesn't support boolean expression in SELECT or GROUP
# BY list.
if not compiler.connection.features.supports_boolean_expr_in_select_clause:
sql = "CASE WHEN {} THEN 1 ELSE 0 END".format(sql)
return sql, params
@deconstructible(path="django.db.models.OrderBy")
class OrderBy(Expression):
template = "%(expression)s %(ordering)s"
conditional = False
def __init__(self, expression, descending=False, nulls_first=None, nulls_last=None):
if nulls_first and nulls_last:
raise ValueError("nulls_first and nulls_last are mutually exclusive")
if nulls_first is False or nulls_last is False:
# When the deprecation ends, replace with:
# raise ValueError(
# "nulls_first and nulls_last values must be True or None."
# )
warnings.warn(
"Passing nulls_first=False or nulls_last=False is deprecated, use None "
"instead.",
RemovedInDjango50Warning,
stacklevel=2,
)
self.nulls_first = nulls_first
self.nulls_last = nulls_last
self.descending = descending
if not hasattr(expression, "resolve_expression"):
raise ValueError("expression must be an expression type")
self.expression = expression
def __repr__(self):
return "{}({}, descending={})".format(
self.__class__.__name__, self.expression, self.descending
)
def set_source_expressions(self, exprs):
self.expression = exprs[0]
def get_source_expressions(self):
return [self.expression]
def as_sql(self, compiler, connection, template=None, **extra_context):
template = template or self.template
if connection.features.supports_order_by_nulls_modifier:
if self.nulls_last:
template = "%s NULLS LAST" % template
elif self.nulls_first:
template = "%s NULLS FIRST" % template
else:
if self.nulls_last and not (
self.descending and connection.features.order_by_nulls_first
):
template = "%%(expression)s IS NULL, %s" % template
elif self.nulls_first and not (
not self.descending and connection.features.order_by_nulls_first
):
template = "%%(expression)s IS NOT NULL, %s" % template
connection.ops.check_expression_support(self)
expression_sql, params = compiler.compile(self.expression)
placeholders = {
"expression": expression_sql,
"ordering": "DESC" if self.descending else "ASC",
**extra_context,
}
params *= template.count("%(expression)s")
return (template % placeholders).rstrip(), params
def as_oracle(self, compiler, connection):
# Oracle doesn't allow ORDER BY EXISTS() or filters unless it's wrapped
# in a CASE WHEN.
if connection.ops.conditional_expression_supported_in_where_clause(
self.expression
):
copy = self.copy()
copy.expression = Case(
When(self.expression, then=True),
default=False,
)
return copy.as_sql(compiler, connection)
return self.as_sql(compiler, connection)
def get_group_by_cols(self, alias=None):
cols = []
for source in self.get_source_expressions():
cols.extend(source.get_group_by_cols())
return cols
def reverse_ordering(self):
self.descending = not self.descending
if self.nulls_first:
self.nulls_last = True
self.nulls_first = None
elif self.nulls_last:
self.nulls_first = True
self.nulls_last = None
return self
def asc(self):
self.descending = False
def desc(self):
self.descending = True
class Window(SQLiteNumericMixin, Expression):
template = "%(expression)s OVER (%(window)s)"
# Although the main expression may either be an aggregate or an
# expression with an aggregate function, the GROUP BY that will
# be introduced in the query as a result is not desired.
contains_aggregate = False
contains_over_clause = True
filterable = False
def __init__(
self,
expression,
partition_by=None,
order_by=None,
frame=None,
output_field=None,
):
self.partition_by = partition_by
self.order_by = order_by
self.frame = frame
if not getattr(expression, "window_compatible", False):
raise ValueError(
"Expression '%s' isn't compatible with OVER clauses."
% expression.__class__.__name__
)
if self.partition_by is not None:
if not isinstance(self.partition_by, (tuple, list)):
self.partition_by = (self.partition_by,)
self.partition_by = ExpressionList(*self.partition_by)
if self.order_by is not None:
if isinstance(self.order_by, (list, tuple)):
self.order_by = OrderByList(*self.order_by)
elif isinstance(self.order_by, (BaseExpression, str)):
self.order_by = OrderByList(self.order_by)
else:
raise ValueError(
"Window.order_by must be either a string reference to a "
"field, an expression, or a list or tuple of them."
)
super().__init__(output_field=output_field)
self.source_expression = self._parse_expressions(expression)[0]
def _resolve_output_field(self):
return self.source_expression.output_field
def get_source_expressions(self):
return [self.source_expression, self.partition_by, self.order_by, self.frame]
def set_source_expressions(self, exprs):
self.source_expression, self.partition_by, self.order_by, self.frame = exprs
def as_sql(self, compiler, connection, template=None):
connection.ops.check_expression_support(self)
if not connection.features.supports_over_clause:
raise NotSupportedError("This backend does not support window expressions.")
expr_sql, params = compiler.compile(self.source_expression)
window_sql, window_params = [], ()
if self.partition_by is not None:
sql_expr, sql_params = self.partition_by.as_sql(
compiler=compiler,
connection=connection,
template="PARTITION BY %(expressions)s",
)
window_sql.append(sql_expr)
window_params += tuple(sql_params)
if self.order_by is not None:
order_sql, order_params = compiler.compile(self.order_by)
window_sql.append(order_sql)
window_params += tuple(order_params)
if self.frame:
frame_sql, frame_params = compiler.compile(self.frame)
window_sql.append(frame_sql)
window_params += tuple(frame_params)
template = template or self.template
return (
template % {"expression": expr_sql, "window": " ".join(window_sql).strip()},
(*params, *window_params),
)
def as_sqlite(self, compiler, connection):
if isinstance(self.output_field, fields.DecimalField):
# Casting to numeric must be outside of the window expression.
copy = self.copy()
source_expressions = copy.get_source_expressions()
source_expressions[0].output_field = fields.FloatField()
copy.set_source_expressions(source_expressions)
return super(Window, copy).as_sqlite(compiler, connection)
return self.as_sql(compiler, connection)
def __str__(self):
return "{} OVER ({}{}{})".format(
str(self.source_expression),
"PARTITION BY " + str(self.partition_by) if self.partition_by else "",
str(self.order_by or ""),
str(self.frame or ""),
)
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self)
def get_group_by_cols(self, alias=None):
return []
class WindowFrame(Expression):
"""
Model the frame clause in window expressions. There are two types of frame
clauses which are subclasses, however, all processing and validation (by no
means intended to be complete) is done here. Thus, providing an end for a
frame is optional (the default is UNBOUNDED FOLLOWING, which is the last
row in the frame).
"""
template = "%(frame_type)s BETWEEN %(start)s AND %(end)s"
def __init__(self, start=None, end=None):
self.start = Value(start)
self.end = Value(end)
def set_source_expressions(self, exprs):
self.start, self.end = exprs
def get_source_expressions(self):
return [self.start, self.end]
def as_sql(self, compiler, connection):
connection.ops.check_expression_support(self)
start, end = self.window_frame_start_end(
connection, self.start.value, self.end.value
)
return (
self.template
% {
"frame_type": self.frame_type,
"start": start,
"end": end,
},
[],
)
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self)
def get_group_by_cols(self, alias=None):
return []
def __str__(self):
if self.start.value is not None and self.start.value < 0:
start = "%d %s" % (abs(self.start.value), connection.ops.PRECEDING)
elif self.start.value is not None and self.start.value == 0:
start = connection.ops.CURRENT_ROW
else:
start = connection.ops.UNBOUNDED_PRECEDING
if self.end.value is not None and self.end.value > 0:
end = "%d %s" % (self.end.value, connection.ops.FOLLOWING)
elif self.end.value is not None and self.end.value == 0:
end = connection.ops.CURRENT_ROW
else:
end = connection.ops.UNBOUNDED_FOLLOWING
return self.template % {
"frame_type": self.frame_type,
"start": start,
"end": end,
}
def window_frame_start_end(self, connection, start, end):
raise NotImplementedError("Subclasses must implement window_frame_start_end().")
class RowRange(WindowFrame):
frame_type = "ROWS"
def window_frame_start_end(self, connection, start, end):
return connection.ops.window_frame_rows_start_end(start, end)
class ValueRange(WindowFrame):
frame_type = "RANGE"
def window_frame_start_end(self, connection, start, end):
return connection.ops.window_frame_range_start_end(start, end)
|
d0890d801fa7525bdac959aa2de684610e0d7da906b6e92a79aa2c95418367ba | from collections import Counter, defaultdict
from functools import partial
from itertools import chain
from operator import attrgetter
from django.db import IntegrityError, connections, transaction
from django.db.models import query_utils, signals, sql
class ProtectedError(IntegrityError):
def __init__(self, msg, protected_objects):
self.protected_objects = protected_objects
super().__init__(msg, protected_objects)
class RestrictedError(IntegrityError):
def __init__(self, msg, restricted_objects):
self.restricted_objects = restricted_objects
super().__init__(msg, restricted_objects)
def CASCADE(collector, field, sub_objs, using):
collector.collect(
sub_objs,
source=field.remote_field.model,
source_attr=field.name,
nullable=field.null,
fail_on_restricted=False,
)
if field.null and not connections[using].features.can_defer_constraint_checks:
collector.add_field_update(field, None, sub_objs)
def PROTECT(collector, field, sub_objs, using):
raise ProtectedError(
"Cannot delete some instances of model '%s' because they are "
"referenced through a protected foreign key: '%s.%s'"
% (
field.remote_field.model.__name__,
sub_objs[0].__class__.__name__,
field.name,
),
sub_objs,
)
def RESTRICT(collector, field, sub_objs, using):
collector.add_restricted_objects(field, sub_objs)
collector.add_dependency(field.remote_field.model, field.model)
def SET(value):
if callable(value):
def set_on_delete(collector, field, sub_objs, using):
collector.add_field_update(field, value(), sub_objs)
else:
def set_on_delete(collector, field, sub_objs, using):
collector.add_field_update(field, value, sub_objs)
set_on_delete.deconstruct = lambda: ("django.db.models.SET", (value,), {})
return set_on_delete
def SET_NULL(collector, field, sub_objs, using):
collector.add_field_update(field, None, sub_objs)
def SET_DEFAULT(collector, field, sub_objs, using):
collector.add_field_update(field, field.get_default(), sub_objs)
def DO_NOTHING(collector, field, sub_objs, using):
pass
def get_candidate_relations_to_delete(opts):
# The candidate relations are the ones that come from N-1 and 1-1 relations.
# N-N (i.e., many-to-many) relations aren't candidates for deletion.
return (
f
for f in opts.get_fields(include_hidden=True)
if f.auto_created and not f.concrete and (f.one_to_one or f.one_to_many)
)
class Collector:
def __init__(self, using, origin=None):
self.using = using
# A Model or QuerySet object.
self.origin = origin
# Initially, {model: {instances}}, later values become lists.
self.data = defaultdict(set)
# {model: {(field, value): {instances}}}
self.field_updates = defaultdict(partial(defaultdict, set))
# {model: {field: {instances}}}
self.restricted_objects = defaultdict(partial(defaultdict, set))
# fast_deletes is a list of queryset-likes that can be deleted without
# fetching the objects into memory.
self.fast_deletes = []
# Tracks deletion-order dependency for databases without transactions
# or ability to defer constraint checks. Only concrete model classes
# should be included, as the dependencies exist only between actual
# database tables; proxy models are represented here by their concrete
# parent.
self.dependencies = defaultdict(set) # {model: {models}}
def add(self, objs, source=None, nullable=False, reverse_dependency=False):
"""
Add 'objs' to the collection of objects to be deleted. If the call is
the result of a cascade, 'source' should be the model that caused it,
and 'nullable' should be set to True if the relation can be null.
Return a list of all objects that were not already collected.
"""
if not objs:
return []
new_objs = []
model = objs[0].__class__
instances = self.data[model]
for obj in objs:
if obj not in instances:
new_objs.append(obj)
instances.update(new_objs)
# Nullable relationships can be ignored -- they are nulled out before
# deleting, and therefore do not affect the order in which objects have
# to be deleted.
if source is not None and not nullable:
self.add_dependency(source, model, reverse_dependency=reverse_dependency)
return new_objs
def add_dependency(self, model, dependency, reverse_dependency=False):
if reverse_dependency:
model, dependency = dependency, model
self.dependencies[model._meta.concrete_model].add(
dependency._meta.concrete_model
)
self.data.setdefault(dependency, self.data.default_factory())
def add_field_update(self, field, value, objs):
"""
Schedule a field update. 'objs' must be a homogeneous iterable
collection of model instances (e.g. a QuerySet).
"""
if not objs:
return
model = objs[0].__class__
self.field_updates[model][field, value].update(objs)
def add_restricted_objects(self, field, objs):
if objs:
model = objs[0].__class__
self.restricted_objects[model][field].update(objs)
def clear_restricted_objects_from_set(self, model, objs):
if model in self.restricted_objects:
self.restricted_objects[model] = {
field: items - objs
for field, items in self.restricted_objects[model].items()
}
def clear_restricted_objects_from_queryset(self, model, qs):
if model in self.restricted_objects:
objs = set(
qs.filter(
pk__in=[
obj.pk
for objs in self.restricted_objects[model].values()
for obj in objs
]
)
)
self.clear_restricted_objects_from_set(model, objs)
def _has_signal_listeners(self, model):
return signals.pre_delete.has_listeners(
model
) or signals.post_delete.has_listeners(model)
def can_fast_delete(self, objs, from_field=None):
"""
Determine if the objects in the given queryset-like or single object
can be fast-deleted. This can be done if there are no cascades, no
parents and no signal listeners for the object class.
The 'from_field' tells where we are coming from - we need this to
determine if the objects are in fact to be deleted. Allow also
skipping parent -> child -> parent chain preventing fast delete of
the child.
"""
if from_field and from_field.remote_field.on_delete is not CASCADE:
return False
if hasattr(objs, "_meta"):
model = objs._meta.model
elif hasattr(objs, "model") and hasattr(objs, "_raw_delete"):
model = objs.model
else:
return False
if self._has_signal_listeners(model):
return False
# The use of from_field comes from the need to avoid cascade back to
# parent when parent delete is cascading to child.
opts = model._meta
return (
all(
link == from_field
for link in opts.concrete_model._meta.parents.values()
)
and
# Foreign keys pointing to this model.
all(
related.field.remote_field.on_delete is DO_NOTHING
for related in get_candidate_relations_to_delete(opts)
)
and (
# Something like generic foreign key.
not any(
hasattr(field, "bulk_related_objects")
for field in opts.private_fields
)
)
)
def get_del_batches(self, objs, fields):
"""
Return the objs in suitably sized batches for the used connection.
"""
field_names = [field.name for field in fields]
conn_batch_size = max(
connections[self.using].ops.bulk_batch_size(field_names, objs), 1
)
if len(objs) > conn_batch_size:
return [
objs[i : i + conn_batch_size]
for i in range(0, len(objs), conn_batch_size)
]
else:
return [objs]
def collect(
self,
objs,
source=None,
nullable=False,
collect_related=True,
source_attr=None,
reverse_dependency=False,
keep_parents=False,
fail_on_restricted=True,
):
"""
Add 'objs' to the collection of objects to be deleted as well as all
parent instances. 'objs' must be a homogeneous iterable collection of
model instances (e.g. a QuerySet). If 'collect_related' is True,
related objects will be handled by their respective on_delete handler.
If the call is the result of a cascade, 'source' should be the model
that caused it and 'nullable' should be set to True, if the relation
can be null.
If 'reverse_dependency' is True, 'source' will be deleted before the
current model, rather than after. (Needed for cascading to parent
models, the one case in which the cascade follows the forwards
direction of an FK rather than the reverse direction.)
If 'keep_parents' is True, data of parent model's will be not deleted.
If 'fail_on_restricted' is False, error won't be raised even if it's
prohibited to delete such objects due to RESTRICT, that defers
restricted object checking in recursive calls where the top-level call
may need to collect more objects to determine whether restricted ones
can be deleted.
"""
if self.can_fast_delete(objs):
self.fast_deletes.append(objs)
return
new_objs = self.add(
objs, source, nullable, reverse_dependency=reverse_dependency
)
if not new_objs:
return
model = new_objs[0].__class__
if not keep_parents:
# Recursively collect concrete model's parent models, but not their
# related objects. These will be found by meta.get_fields()
concrete_model = model._meta.concrete_model
for ptr in concrete_model._meta.parents.values():
if ptr:
parent_objs = [getattr(obj, ptr.name) for obj in new_objs]
self.collect(
parent_objs,
source=model,
source_attr=ptr.remote_field.related_name,
collect_related=False,
reverse_dependency=True,
fail_on_restricted=False,
)
if not collect_related:
return
if keep_parents:
parents = set(model._meta.get_parent_list())
model_fast_deletes = defaultdict(list)
protected_objects = defaultdict(list)
for related in get_candidate_relations_to_delete(model._meta):
# Preserve parent reverse relationships if keep_parents=True.
if keep_parents and related.model in parents:
continue
field = related.field
if field.remote_field.on_delete == DO_NOTHING:
continue
related_model = related.related_model
if self.can_fast_delete(related_model, from_field=field):
model_fast_deletes[related_model].append(field)
continue
batches = self.get_del_batches(new_objs, [field])
for batch in batches:
sub_objs = self.related_objects(related_model, [field], batch)
# Non-referenced fields can be deferred if no signal receivers
# are connected for the related model as they'll never be
# exposed to the user. Skip field deferring when some
# relationships are select_related as interactions between both
# features are hard to get right. This should only happen in
# the rare cases where .related_objects is overridden anyway.
if not (
sub_objs.query.select_related
or self._has_signal_listeners(related_model)
):
referenced_fields = set(
chain.from_iterable(
(rf.attname for rf in rel.field.foreign_related_fields)
for rel in get_candidate_relations_to_delete(
related_model._meta
)
)
)
sub_objs = sub_objs.only(*tuple(referenced_fields))
if sub_objs:
try:
field.remote_field.on_delete(self, field, sub_objs, self.using)
except ProtectedError as error:
key = "'%s.%s'" % (field.model.__name__, field.name)
protected_objects[key] += error.protected_objects
if protected_objects:
raise ProtectedError(
"Cannot delete some instances of model %r because they are "
"referenced through protected foreign keys: %s."
% (
model.__name__,
", ".join(protected_objects),
),
set(chain.from_iterable(protected_objects.values())),
)
for related_model, related_fields in model_fast_deletes.items():
batches = self.get_del_batches(new_objs, related_fields)
for batch in batches:
sub_objs = self.related_objects(related_model, related_fields, batch)
self.fast_deletes.append(sub_objs)
for field in model._meta.private_fields:
if hasattr(field, "bulk_related_objects"):
# It's something like generic foreign key.
sub_objs = field.bulk_related_objects(new_objs, self.using)
self.collect(
sub_objs, source=model, nullable=True, fail_on_restricted=False
)
if fail_on_restricted:
# Raise an error if collected restricted objects (RESTRICT) aren't
# candidates for deletion also collected via CASCADE.
for related_model, instances in self.data.items():
self.clear_restricted_objects_from_set(related_model, instances)
for qs in self.fast_deletes:
self.clear_restricted_objects_from_queryset(qs.model, qs)
if self.restricted_objects.values():
restricted_objects = defaultdict(list)
for related_model, fields in self.restricted_objects.items():
for field, objs in fields.items():
if objs:
key = "'%s.%s'" % (related_model.__name__, field.name)
restricted_objects[key] += objs
if restricted_objects:
raise RestrictedError(
"Cannot delete some instances of model %r because "
"they are referenced through restricted foreign keys: "
"%s."
% (
model.__name__,
", ".join(restricted_objects),
),
set(chain.from_iterable(restricted_objects.values())),
)
def related_objects(self, related_model, related_fields, objs):
"""
Get a QuerySet of the related model to objs via related fields.
"""
predicate = query_utils.Q.create(
[(f"{related_field.name}__in", objs) for related_field in related_fields],
connector=query_utils.Q.OR,
)
return related_model._base_manager.using(self.using).filter(predicate)
def instances_with_model(self):
for model, instances in self.data.items():
for obj in instances:
yield model, obj
def sort(self):
sorted_models = []
concrete_models = set()
models = list(self.data)
while len(sorted_models) < len(models):
found = False
for model in models:
if model in sorted_models:
continue
dependencies = self.dependencies.get(model._meta.concrete_model)
if not (dependencies and dependencies.difference(concrete_models)):
sorted_models.append(model)
concrete_models.add(model._meta.concrete_model)
found = True
if not found:
return
self.data = {model: self.data[model] for model in sorted_models}
def delete(self):
# sort instance collections
for model, instances in self.data.items():
self.data[model] = sorted(instances, key=attrgetter("pk"))
# if possible, bring the models in an order suitable for databases that
# don't support transactions or cannot defer constraint checks until the
# end of a transaction.
self.sort()
# number of objects deleted for each model label
deleted_counter = Counter()
# Optimize for the case with a single obj and no dependencies
if len(self.data) == 1 and len(instances) == 1:
instance = list(instances)[0]
if self.can_fast_delete(instance):
with transaction.mark_for_rollback_on_error(self.using):
count = sql.DeleteQuery(model).delete_batch(
[instance.pk], self.using
)
setattr(instance, model._meta.pk.attname, None)
return count, {model._meta.label: count}
with transaction.atomic(using=self.using, savepoint=False):
# send pre_delete signals
for model, obj in self.instances_with_model():
if not model._meta.auto_created:
signals.pre_delete.send(
sender=model,
instance=obj,
using=self.using,
origin=self.origin,
)
# fast deletes
for qs in self.fast_deletes:
count = qs._raw_delete(using=self.using)
if count:
deleted_counter[qs.model._meta.label] += count
# update fields
for model, instances_for_fieldvalues in self.field_updates.items():
for (field, value), instances in instances_for_fieldvalues.items():
query = sql.UpdateQuery(model)
query.update_batch(
[obj.pk for obj in instances], {field.name: value}, self.using
)
# reverse instance collections
for instances in self.data.values():
instances.reverse()
# delete instances
for model, instances in self.data.items():
query = sql.DeleteQuery(model)
pk_list = [obj.pk for obj in instances]
count = query.delete_batch(pk_list, self.using)
if count:
deleted_counter[model._meta.label] += count
if not model._meta.auto_created:
for obj in instances:
signals.post_delete.send(
sender=model,
instance=obj,
using=self.using,
origin=self.origin,
)
# update collected instances
for instances_for_fieldvalues in self.field_updates.values():
for (field, value), instances in instances_for_fieldvalues.items():
for obj in instances:
setattr(obj, field.attname, value)
for model, instances in self.data.items():
for instance in instances:
setattr(instance, model._meta.pk.attname, None)
return sum(deleted_counter.values()), dict(deleted_counter)
|
dfd1327abd125337fe8b1ac3a0c23d1c0f37f6ec774b943461950860f0f40581 | import functools
import inspect
from functools import partial
from django import forms
from django.apps import apps
from django.conf import SettingsReference, settings
from django.core import checks, exceptions
from django.db import connection, router
from django.db.backends import utils
from django.db.models import Q
from django.db.models.constants import LOOKUP_SEP
from django.db.models.deletion import CASCADE, SET_DEFAULT, SET_NULL
from django.db.models.query_utils import PathInfo
from django.db.models.utils import make_model_tuple
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from . import Field
from .mixins import FieldCacheMixin
from .related_descriptors import (
ForeignKeyDeferredAttribute,
ForwardManyToOneDescriptor,
ForwardOneToOneDescriptor,
ManyToManyDescriptor,
ReverseManyToOneDescriptor,
ReverseOneToOneDescriptor,
)
from .related_lookups import (
RelatedExact,
RelatedGreaterThan,
RelatedGreaterThanOrEqual,
RelatedIn,
RelatedIsNull,
RelatedLessThan,
RelatedLessThanOrEqual,
)
from .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel
RECURSIVE_RELATIONSHIP_CONSTANT = "self"
def resolve_relation(scope_model, relation):
"""
Transform relation into a model or fully-qualified model string of the form
"app_label.ModelName", relative to scope_model.
The relation argument can be:
* RECURSIVE_RELATIONSHIP_CONSTANT, i.e. the string "self", in which case
the model argument will be returned.
* A bare model name without an app_label, in which case scope_model's
app_label will be prepended.
* An "app_label.ModelName" string.
* A model class, which will be returned unchanged.
"""
# Check for recursive relations
if relation == RECURSIVE_RELATIONSHIP_CONSTANT:
relation = scope_model
# Look for an "app.Model" relation
if isinstance(relation, str):
if "." not in relation:
relation = "%s.%s" % (scope_model._meta.app_label, relation)
return relation
def lazy_related_operation(function, model, *related_models, **kwargs):
"""
Schedule `function` to be called once `model` and all `related_models`
have been imported and registered with the app registry. `function` will
be called with the newly-loaded model classes as its positional arguments,
plus any optional keyword arguments.
The `model` argument must be a model class. Each subsequent positional
argument is another model, or a reference to another model - see
`resolve_relation()` for the various forms these may take. Any relative
references will be resolved relative to `model`.
This is a convenience wrapper for `Apps.lazy_model_operation` - the app
registry model used is the one found in `model._meta.apps`.
"""
models = [model] + [resolve_relation(model, rel) for rel in related_models]
model_keys = (make_model_tuple(m) for m in models)
apps = model._meta.apps
return apps.lazy_model_operation(partial(function, **kwargs), *model_keys)
class RelatedField(FieldCacheMixin, Field):
"""Base class that all relational fields inherit from."""
# Field flags
one_to_many = False
one_to_one = False
many_to_many = False
many_to_one = False
def __init__(
self,
related_name=None,
related_query_name=None,
limit_choices_to=None,
**kwargs,
):
self._related_name = related_name
self._related_query_name = related_query_name
self._limit_choices_to = limit_choices_to
super().__init__(**kwargs)
@cached_property
def related_model(self):
# Can't cache this property until all the models are loaded.
apps.check_models_ready()
return self.remote_field.model
def check(self, **kwargs):
return [
*super().check(**kwargs),
*self._check_related_name_is_valid(),
*self._check_related_query_name_is_valid(),
*self._check_relation_model_exists(),
*self._check_referencing_to_swapped_model(),
*self._check_clashes(),
]
def _check_related_name_is_valid(self):
import keyword
related_name = self.remote_field.related_name
if related_name is None:
return []
is_valid_id = (
not keyword.iskeyword(related_name) and related_name.isidentifier()
)
if not (is_valid_id or related_name.endswith("+")):
return [
checks.Error(
"The name '%s' is invalid related_name for field %s.%s"
% (
self.remote_field.related_name,
self.model._meta.object_name,
self.name,
),
hint=(
"Related name must be a valid Python identifier or end with a "
"'+'"
),
obj=self,
id="fields.E306",
)
]
return []
def _check_related_query_name_is_valid(self):
if self.remote_field.is_hidden():
return []
rel_query_name = self.related_query_name()
errors = []
if rel_query_name.endswith("_"):
errors.append(
checks.Error(
"Reverse query name '%s' must not end with an underscore."
% rel_query_name,
hint=(
"Add or change a related_name or related_query_name "
"argument for this field."
),
obj=self,
id="fields.E308",
)
)
if LOOKUP_SEP in rel_query_name:
errors.append(
checks.Error(
"Reverse query name '%s' must not contain '%s'."
% (rel_query_name, LOOKUP_SEP),
hint=(
"Add or change a related_name or related_query_name "
"argument for this field."
),
obj=self,
id="fields.E309",
)
)
return errors
def _check_relation_model_exists(self):
rel_is_missing = self.remote_field.model not in self.opts.apps.get_models()
rel_is_string = isinstance(self.remote_field.model, str)
model_name = (
self.remote_field.model
if rel_is_string
else self.remote_field.model._meta.object_name
)
if rel_is_missing and (
rel_is_string or not self.remote_field.model._meta.swapped
):
return [
checks.Error(
"Field defines a relation with model '%s', which is either "
"not installed, or is abstract." % model_name,
obj=self,
id="fields.E300",
)
]
return []
def _check_referencing_to_swapped_model(self):
if (
self.remote_field.model not in self.opts.apps.get_models()
and not isinstance(self.remote_field.model, str)
and self.remote_field.model._meta.swapped
):
return [
checks.Error(
"Field defines a relation with the model '%s', which has "
"been swapped out." % self.remote_field.model._meta.label,
hint="Update the relation to point at 'settings.%s'."
% self.remote_field.model._meta.swappable,
obj=self,
id="fields.E301",
)
]
return []
def _check_clashes(self):
"""Check accessor and reverse query name clashes."""
from django.db.models.base import ModelBase
errors = []
opts = self.model._meta
# f.remote_field.model may be a string instead of a model. Skip if
# model name is not resolved.
if not isinstance(self.remote_field.model, ModelBase):
return []
# Consider that we are checking field `Model.foreign` and the models
# are:
#
# class Target(models.Model):
# model = models.IntegerField()
# model_set = models.IntegerField()
#
# class Model(models.Model):
# foreign = models.ForeignKey(Target)
# m2m = models.ManyToManyField(Target)
# rel_opts.object_name == "Target"
rel_opts = self.remote_field.model._meta
# If the field doesn't install a backward relation on the target model
# (so `is_hidden` returns True), then there are no clashes to check
# and we can skip these fields.
rel_is_hidden = self.remote_field.is_hidden()
rel_name = self.remote_field.get_accessor_name() # i. e. "model_set"
rel_query_name = self.related_query_name() # i. e. "model"
# i.e. "app_label.Model.field".
field_name = "%s.%s" % (opts.label, self.name)
# Check clashes between accessor or reverse query name of `field`
# and any other field name -- i.e. accessor for Model.foreign is
# model_set and it clashes with Target.model_set.
potential_clashes = rel_opts.fields + rel_opts.many_to_many
for clash_field in potential_clashes:
# i.e. "app_label.Target.model_set".
clash_name = "%s.%s" % (rel_opts.label, clash_field.name)
if not rel_is_hidden and clash_field.name == rel_name:
errors.append(
checks.Error(
f"Reverse accessor '{rel_opts.object_name}.{rel_name}' "
f"for '{field_name}' clashes with field name "
f"'{clash_name}'.",
hint=(
"Rename field '%s', or add/change a related_name "
"argument to the definition for field '%s'."
)
% (clash_name, field_name),
obj=self,
id="fields.E302",
)
)
if clash_field.name == rel_query_name:
errors.append(
checks.Error(
"Reverse query name for '%s' clashes with field name '%s'."
% (field_name, clash_name),
hint=(
"Rename field '%s', or add/change a related_name "
"argument to the definition for field '%s'."
)
% (clash_name, field_name),
obj=self,
id="fields.E303",
)
)
# Check clashes between accessors/reverse query names of `field` and
# any other field accessor -- i. e. Model.foreign accessor clashes with
# Model.m2m accessor.
potential_clashes = (r for r in rel_opts.related_objects if r.field is not self)
for clash_field in potential_clashes:
# i.e. "app_label.Model.m2m".
clash_name = "%s.%s" % (
clash_field.related_model._meta.label,
clash_field.field.name,
)
if not rel_is_hidden and clash_field.get_accessor_name() == rel_name:
errors.append(
checks.Error(
f"Reverse accessor '{rel_opts.object_name}.{rel_name}' "
f"for '{field_name}' clashes with reverse accessor for "
f"'{clash_name}'.",
hint=(
"Add or change a related_name argument "
"to the definition for '%s' or '%s'."
)
% (field_name, clash_name),
obj=self,
id="fields.E304",
)
)
if clash_field.get_accessor_name() == rel_query_name:
errors.append(
checks.Error(
"Reverse query name for '%s' clashes with reverse query name "
"for '%s'." % (field_name, clash_name),
hint=(
"Add or change a related_name argument "
"to the definition for '%s' or '%s'."
)
% (field_name, clash_name),
obj=self,
id="fields.E305",
)
)
return errors
def db_type(self, connection):
# By default related field will not have a column as it relates to
# columns from another table.
return None
def contribute_to_class(self, cls, name, private_only=False, **kwargs):
super().contribute_to_class(cls, name, private_only=private_only, **kwargs)
self.opts = cls._meta
if not cls._meta.abstract:
if self.remote_field.related_name:
related_name = self.remote_field.related_name
else:
related_name = self.opts.default_related_name
if related_name:
related_name = related_name % {
"class": cls.__name__.lower(),
"model_name": cls._meta.model_name.lower(),
"app_label": cls._meta.app_label.lower(),
}
self.remote_field.related_name = related_name
if self.remote_field.related_query_name:
related_query_name = self.remote_field.related_query_name % {
"class": cls.__name__.lower(),
"app_label": cls._meta.app_label.lower(),
}
self.remote_field.related_query_name = related_query_name
def resolve_related_class(model, related, field):
field.remote_field.model = related
field.do_related_class(related, model)
lazy_related_operation(
resolve_related_class, cls, self.remote_field.model, field=self
)
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
if self._limit_choices_to:
kwargs["limit_choices_to"] = self._limit_choices_to
if self._related_name is not None:
kwargs["related_name"] = self._related_name
if self._related_query_name is not None:
kwargs["related_query_name"] = self._related_query_name
return name, path, args, kwargs
def get_forward_related_filter(self, obj):
"""
Return the keyword arguments that when supplied to
self.model.object.filter(), would select all instances related through
this field to the remote obj. This is used to build the querysets
returned by related descriptors. obj is an instance of
self.related_field.model.
"""
return {
"%s__%s" % (self.name, rh_field.name): getattr(obj, rh_field.attname)
for _, rh_field in self.related_fields
}
def get_reverse_related_filter(self, obj):
"""
Complement to get_forward_related_filter(). Return the keyword
arguments that when passed to self.related_field.model.object.filter()
select all instances of self.related_field.model related through
this field to obj. obj is an instance of self.model.
"""
base_q = Q.create(
[
(rh_field.attname, getattr(obj, lh_field.attname))
for lh_field, rh_field in self.related_fields
]
)
descriptor_filter = self.get_extra_descriptor_filter(obj)
if isinstance(descriptor_filter, dict):
return base_q & Q(**descriptor_filter)
elif descriptor_filter:
return base_q & descriptor_filter
return base_q
@property
def swappable_setting(self):
"""
Get the setting that this is powered from for swapping, or None
if it's not swapped in / marked with swappable=False.
"""
if self.swappable:
# Work out string form of "to"
if isinstance(self.remote_field.model, str):
to_string = self.remote_field.model
else:
to_string = self.remote_field.model._meta.label
return apps.get_swappable_settings_name(to_string)
return None
def set_attributes_from_rel(self):
self.name = self.name or (
self.remote_field.model._meta.model_name
+ "_"
+ self.remote_field.model._meta.pk.name
)
if self.verbose_name is None:
self.verbose_name = self.remote_field.model._meta.verbose_name
self.remote_field.set_field_name()
def do_related_class(self, other, cls):
self.set_attributes_from_rel()
self.contribute_to_related_class(other, self.remote_field)
def get_limit_choices_to(self):
"""
Return ``limit_choices_to`` for this model field.
If it is a callable, it will be invoked and the result will be
returned.
"""
if callable(self.remote_field.limit_choices_to):
return self.remote_field.limit_choices_to()
return self.remote_field.limit_choices_to
def formfield(self, **kwargs):
"""
Pass ``limit_choices_to`` to the field being constructed.
Only passes it if there is a type that supports related fields.
This is a similar strategy used to pass the ``queryset`` to the field
being constructed.
"""
defaults = {}
if hasattr(self.remote_field, "get_related_field"):
# If this is a callable, do not invoke it here. Just pass
# it in the defaults for when the form class will later be
# instantiated.
limit_choices_to = self.remote_field.limit_choices_to
defaults.update(
{
"limit_choices_to": limit_choices_to,
}
)
defaults.update(kwargs)
return super().formfield(**defaults)
def related_query_name(self):
"""
Define the name that can be used to identify this related object in a
table-spanning query.
"""
return (
self.remote_field.related_query_name
or self.remote_field.related_name
or self.opts.model_name
)
@property
def target_field(self):
"""
When filtering against this relation, return the field on the remote
model against which the filtering should happen.
"""
target_fields = self.path_infos[-1].target_fields
if len(target_fields) > 1:
raise exceptions.FieldError(
"The relation has multiple target fields, but only single target field "
"was asked for"
)
return target_fields[0]
def get_cache_name(self):
return self.name
class ForeignObject(RelatedField):
"""
Abstraction of the ForeignKey relation to support multi-column relations.
"""
# Field flags
many_to_many = False
many_to_one = True
one_to_many = False
one_to_one = False
requires_unique_target = True
related_accessor_class = ReverseManyToOneDescriptor
forward_related_accessor_class = ForwardManyToOneDescriptor
rel_class = ForeignObjectRel
def __init__(
self,
to,
on_delete,
from_fields,
to_fields,
rel=None,
related_name=None,
related_query_name=None,
limit_choices_to=None,
parent_link=False,
swappable=True,
**kwargs,
):
if rel is None:
rel = self.rel_class(
self,
to,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
parent_link=parent_link,
on_delete=on_delete,
)
super().__init__(
rel=rel,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
**kwargs,
)
self.from_fields = from_fields
self.to_fields = to_fields
self.swappable = swappable
def __copy__(self):
obj = super().__copy__()
# Remove any cached PathInfo values.
obj.__dict__.pop("path_infos", None)
obj.__dict__.pop("reverse_path_infos", None)
return obj
def check(self, **kwargs):
return [
*super().check(**kwargs),
*self._check_to_fields_exist(),
*self._check_unique_target(),
]
def _check_to_fields_exist(self):
# Skip nonexistent models.
if isinstance(self.remote_field.model, str):
return []
errors = []
for to_field in self.to_fields:
if to_field:
try:
self.remote_field.model._meta.get_field(to_field)
except exceptions.FieldDoesNotExist:
errors.append(
checks.Error(
"The to_field '%s' doesn't exist on the related "
"model '%s'."
% (to_field, self.remote_field.model._meta.label),
obj=self,
id="fields.E312",
)
)
return errors
def _check_unique_target(self):
rel_is_string = isinstance(self.remote_field.model, str)
if rel_is_string or not self.requires_unique_target:
return []
try:
self.foreign_related_fields
except exceptions.FieldDoesNotExist:
return []
if not self.foreign_related_fields:
return []
unique_foreign_fields = {
frozenset([f.name])
for f in self.remote_field.model._meta.get_fields()
if getattr(f, "unique", False)
}
unique_foreign_fields.update(
{frozenset(ut) for ut in self.remote_field.model._meta.unique_together}
)
unique_foreign_fields.update(
{
frozenset(uc.fields)
for uc in self.remote_field.model._meta.total_unique_constraints
}
)
foreign_fields = {f.name for f in self.foreign_related_fields}
has_unique_constraint = any(u <= foreign_fields for u in unique_foreign_fields)
if not has_unique_constraint and len(self.foreign_related_fields) > 1:
field_combination = ", ".join(
"'%s'" % rel_field.name for rel_field in self.foreign_related_fields
)
model_name = self.remote_field.model.__name__
return [
checks.Error(
"No subset of the fields %s on model '%s' is unique."
% (field_combination, model_name),
hint=(
"Mark a single field as unique=True or add a set of "
"fields to a unique constraint (via unique_together "
"or a UniqueConstraint (without condition) in the "
"model Meta.constraints)."
),
obj=self,
id="fields.E310",
)
]
elif not has_unique_constraint:
field_name = self.foreign_related_fields[0].name
model_name = self.remote_field.model.__name__
return [
checks.Error(
"'%s.%s' must be unique because it is referenced by "
"a foreign key." % (model_name, field_name),
hint=(
"Add unique=True to this field or add a "
"UniqueConstraint (without condition) in the model "
"Meta.constraints."
),
obj=self,
id="fields.E311",
)
]
else:
return []
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
kwargs["on_delete"] = self.remote_field.on_delete
kwargs["from_fields"] = self.from_fields
kwargs["to_fields"] = self.to_fields
if self.remote_field.parent_link:
kwargs["parent_link"] = self.remote_field.parent_link
if isinstance(self.remote_field.model, str):
if "." in self.remote_field.model:
app_label, model_name = self.remote_field.model.split(".")
kwargs["to"] = "%s.%s" % (app_label, model_name.lower())
else:
kwargs["to"] = self.remote_field.model.lower()
else:
kwargs["to"] = self.remote_field.model._meta.label_lower
# If swappable is True, then see if we're actually pointing to the target
# of a swap.
swappable_setting = self.swappable_setting
if swappable_setting is not None:
# If it's already a settings reference, error
if hasattr(kwargs["to"], "setting_name"):
if kwargs["to"].setting_name != swappable_setting:
raise ValueError(
"Cannot deconstruct a ForeignKey pointing to a model "
"that is swapped in place of more than one model (%s and %s)"
% (kwargs["to"].setting_name, swappable_setting)
)
# Set it
kwargs["to"] = SettingsReference(
kwargs["to"],
swappable_setting,
)
return name, path, args, kwargs
def resolve_related_fields(self):
if not self.from_fields or len(self.from_fields) != len(self.to_fields):
raise ValueError(
"Foreign Object from and to fields must be the same non-zero length"
)
if isinstance(self.remote_field.model, str):
raise ValueError(
"Related model %r cannot be resolved" % self.remote_field.model
)
related_fields = []
for index in range(len(self.from_fields)):
from_field_name = self.from_fields[index]
to_field_name = self.to_fields[index]
from_field = (
self
if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT
else self.opts.get_field(from_field_name)
)
to_field = (
self.remote_field.model._meta.pk
if to_field_name is None
else self.remote_field.model._meta.get_field(to_field_name)
)
related_fields.append((from_field, to_field))
return related_fields
@cached_property
def related_fields(self):
return self.resolve_related_fields()
@cached_property
def reverse_related_fields(self):
return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields]
@cached_property
def local_related_fields(self):
return tuple(lhs_field for lhs_field, rhs_field in self.related_fields)
@cached_property
def foreign_related_fields(self):
return tuple(
rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field
)
def get_local_related_value(self, instance):
return self.get_instance_value_for_fields(instance, self.local_related_fields)
def get_foreign_related_value(self, instance):
return self.get_instance_value_for_fields(instance, self.foreign_related_fields)
@staticmethod
def get_instance_value_for_fields(instance, fields):
ret = []
opts = instance._meta
for field in fields:
# Gotcha: in some cases (like fixture loading) a model can have
# different values in parent_ptr_id and parent's id. So, use
# instance.pk (that is, parent_ptr_id) when asked for instance.id.
if field.primary_key:
possible_parent_link = opts.get_ancestor_link(field.model)
if (
not possible_parent_link
or possible_parent_link.primary_key
or possible_parent_link.model._meta.abstract
):
ret.append(instance.pk)
continue
ret.append(getattr(instance, field.attname))
return tuple(ret)
def get_attname_column(self):
attname, column = super().get_attname_column()
return attname, None
def get_joining_columns(self, reverse_join=False):
source = self.reverse_related_fields if reverse_join else self.related_fields
return tuple(
(lhs_field.column, rhs_field.column) for lhs_field, rhs_field in source
)
def get_reverse_joining_columns(self):
return self.get_joining_columns(reverse_join=True)
def get_extra_descriptor_filter(self, instance):
"""
Return an extra filter condition for related object fetching when
user does 'instance.fieldname', that is the extra filter is used in
the descriptor of the field.
The filter should be either a dict usable in .filter(**kwargs) call or
a Q-object. The condition will be ANDed together with the relation's
joining columns.
A parallel method is get_extra_restriction() which is used in
JOIN and subquery conditions.
"""
return {}
def get_extra_restriction(self, alias, related_alias):
"""
Return a pair condition used for joining and subquery pushdown. The
condition is something that responds to as_sql(compiler, connection)
method.
Note that currently referring both the 'alias' and 'related_alias'
will not work in some conditions, like subquery pushdown.
A parallel method is get_extra_descriptor_filter() which is used in
instance.fieldname related object fetching.
"""
return None
def get_path_info(self, filtered_relation=None):
"""Get path from this field to the related model."""
opts = self.remote_field.model._meta
from_opts = self.model._meta
return [
PathInfo(
from_opts=from_opts,
to_opts=opts,
target_fields=self.foreign_related_fields,
join_field=self,
m2m=False,
direct=True,
filtered_relation=filtered_relation,
)
]
@cached_property
def path_infos(self):
return self.get_path_info()
def get_reverse_path_info(self, filtered_relation=None):
"""Get path from the related model to this field's model."""
opts = self.model._meta
from_opts = self.remote_field.model._meta
return [
PathInfo(
from_opts=from_opts,
to_opts=opts,
target_fields=(opts.pk,),
join_field=self.remote_field,
m2m=not self.unique,
direct=False,
filtered_relation=filtered_relation,
)
]
@cached_property
def reverse_path_infos(self):
return self.get_reverse_path_info()
@classmethod
@functools.lru_cache(maxsize=None)
def get_lookups(cls):
bases = inspect.getmro(cls)
bases = bases[: bases.index(ForeignObject) + 1]
class_lookups = [parent.__dict__.get("class_lookups", {}) for parent in bases]
return cls.merge_dicts(class_lookups)
def contribute_to_class(self, cls, name, private_only=False, **kwargs):
super().contribute_to_class(cls, name, private_only=private_only, **kwargs)
setattr(cls, self.name, self.forward_related_accessor_class(self))
def contribute_to_related_class(self, cls, related):
# Internal FK's - i.e., those with a related name ending with '+' -
# and swapped models don't get a related descriptor.
if (
not self.remote_field.is_hidden()
and not related.related_model._meta.swapped
):
setattr(
cls._meta.concrete_model,
related.get_accessor_name(),
self.related_accessor_class(related),
)
# While 'limit_choices_to' might be a callable, simply pass
# it along for later - this is too early because it's still
# model load time.
if self.remote_field.limit_choices_to:
cls._meta.related_fkey_lookups.append(
self.remote_field.limit_choices_to
)
ForeignObject.register_lookup(RelatedIn)
ForeignObject.register_lookup(RelatedExact)
ForeignObject.register_lookup(RelatedLessThan)
ForeignObject.register_lookup(RelatedGreaterThan)
ForeignObject.register_lookup(RelatedGreaterThanOrEqual)
ForeignObject.register_lookup(RelatedLessThanOrEqual)
ForeignObject.register_lookup(RelatedIsNull)
class ForeignKey(ForeignObject):
"""
Provide a many-to-one relation by adding a column to the local model
to hold the remote value.
By default ForeignKey will target the pk of the remote model but this
behavior can be changed by using the ``to_field`` argument.
"""
descriptor_class = ForeignKeyDeferredAttribute
# Field flags
many_to_many = False
many_to_one = True
one_to_many = False
one_to_one = False
rel_class = ManyToOneRel
empty_strings_allowed = False
default_error_messages = {
"invalid": _("%(model)s instance with %(field)s %(value)r does not exist.")
}
description = _("Foreign Key (type determined by related field)")
def __init__(
self,
to,
on_delete,
related_name=None,
related_query_name=None,
limit_choices_to=None,
parent_link=False,
to_field=None,
db_constraint=True,
**kwargs,
):
try:
to._meta.model_name
except AttributeError:
if not isinstance(to, str):
raise TypeError(
"%s(%r) is invalid. First parameter to ForeignKey must be "
"either a model, a model name, or the string %r"
% (
self.__class__.__name__,
to,
RECURSIVE_RELATIONSHIP_CONSTANT,
)
)
else:
# For backwards compatibility purposes, we need to *try* and set
# the to_field during FK construction. It won't be guaranteed to
# be correct until contribute_to_class is called. Refs #12190.
to_field = to_field or (to._meta.pk and to._meta.pk.name)
if not callable(on_delete):
raise TypeError("on_delete must be callable.")
kwargs["rel"] = self.rel_class(
self,
to,
to_field,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
parent_link=parent_link,
on_delete=on_delete,
)
kwargs.setdefault("db_index", True)
super().__init__(
to,
on_delete,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
from_fields=[RECURSIVE_RELATIONSHIP_CONSTANT],
to_fields=[to_field],
**kwargs,
)
self.db_constraint = db_constraint
def __class_getitem__(cls, *args, **kwargs):
return cls
def check(self, **kwargs):
return [
*super().check(**kwargs),
*self._check_on_delete(),
*self._check_unique(),
]
def _check_on_delete(self):
on_delete = getattr(self.remote_field, "on_delete", None)
if on_delete == SET_NULL and not self.null:
return [
checks.Error(
"Field specifies on_delete=SET_NULL, but cannot be null.",
hint=(
"Set null=True argument on the field, or change the on_delete "
"rule."
),
obj=self,
id="fields.E320",
)
]
elif on_delete == SET_DEFAULT and not self.has_default():
return [
checks.Error(
"Field specifies on_delete=SET_DEFAULT, but has no default value.",
hint="Set a default value, or change the on_delete rule.",
obj=self,
id="fields.E321",
)
]
else:
return []
def _check_unique(self, **kwargs):
return (
[
checks.Warning(
"Setting unique=True on a ForeignKey has the same effect as using "
"a OneToOneField.",
hint=(
"ForeignKey(unique=True) is usually better served by a "
"OneToOneField."
),
obj=self,
id="fields.W342",
)
]
if self.unique
else []
)
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
del kwargs["to_fields"]
del kwargs["from_fields"]
# Handle the simpler arguments
if self.db_index:
del kwargs["db_index"]
else:
kwargs["db_index"] = False
if self.db_constraint is not True:
kwargs["db_constraint"] = self.db_constraint
# Rel needs more work.
to_meta = getattr(self.remote_field.model, "_meta", None)
if self.remote_field.field_name and (
not to_meta
or (to_meta.pk and self.remote_field.field_name != to_meta.pk.name)
):
kwargs["to_field"] = self.remote_field.field_name
return name, path, args, kwargs
def to_python(self, value):
return self.target_field.to_python(value)
@property
def target_field(self):
return self.foreign_related_fields[0]
def get_reverse_path_info(self, filtered_relation=None):
"""Get path from the related model to this field's model."""
opts = self.model._meta
from_opts = self.remote_field.model._meta
return [
PathInfo(
from_opts=from_opts,
to_opts=opts,
target_fields=(opts.pk,),
join_field=self.remote_field,
m2m=not self.unique,
direct=False,
filtered_relation=filtered_relation,
)
]
def validate(self, value, model_instance):
if self.remote_field.parent_link:
return
super().validate(value, model_instance)
if value is None:
return
using = router.db_for_read(self.remote_field.model, instance=model_instance)
qs = self.remote_field.model._base_manager.using(using).filter(
**{self.remote_field.field_name: value}
)
qs = qs.complex_filter(self.get_limit_choices_to())
if not qs.exists():
raise exceptions.ValidationError(
self.error_messages["invalid"],
code="invalid",
params={
"model": self.remote_field.model._meta.verbose_name,
"pk": value,
"field": self.remote_field.field_name,
"value": value,
}, # 'pk' is included for backwards compatibility
)
def resolve_related_fields(self):
related_fields = super().resolve_related_fields()
for from_field, to_field in related_fields:
if (
to_field
and to_field.model != self.remote_field.model._meta.concrete_model
):
raise exceptions.FieldError(
"'%s.%s' refers to field '%s' which is not local to model "
"'%s'."
% (
self.model._meta.label,
self.name,
to_field.name,
self.remote_field.model._meta.concrete_model._meta.label,
)
)
return related_fields
def get_attname(self):
return "%s_id" % self.name
def get_attname_column(self):
attname = self.get_attname()
column = self.db_column or attname
return attname, column
def get_default(self):
"""Return the to_field if the default value is an object."""
field_default = super().get_default()
if isinstance(field_default, self.remote_field.model):
return getattr(field_default, self.target_field.attname)
return field_default
def get_db_prep_save(self, value, connection):
if value is None or (
value == ""
and (
not self.target_field.empty_strings_allowed
or connection.features.interprets_empty_strings_as_nulls
)
):
return None
else:
return self.target_field.get_db_prep_save(value, connection=connection)
def get_db_prep_value(self, value, connection, prepared=False):
return self.target_field.get_db_prep_value(value, connection, prepared)
def get_prep_value(self, value):
return self.target_field.get_prep_value(value)
def contribute_to_related_class(self, cls, related):
super().contribute_to_related_class(cls, related)
if self.remote_field.field_name is None:
self.remote_field.field_name = cls._meta.pk.name
def formfield(self, *, using=None, **kwargs):
if isinstance(self.remote_field.model, str):
raise ValueError(
"Cannot create form field for %r yet, because "
"its related model %r has not been loaded yet"
% (self.name, self.remote_field.model)
)
return super().formfield(
**{
"form_class": forms.ModelChoiceField,
"queryset": self.remote_field.model._default_manager.using(using),
"to_field_name": self.remote_field.field_name,
**kwargs,
"blank": self.blank,
}
)
def db_check(self, connection):
return None
def db_type(self, connection):
return self.target_field.rel_db_type(connection=connection)
def db_parameters(self, connection):
target_db_parameters = self.target_field.db_parameters(connection)
return {
"type": self.db_type(connection),
"check": self.db_check(connection),
"collation": target_db_parameters.get("collation"),
}
def convert_empty_strings(self, value, expression, connection):
if (not value) and isinstance(value, str):
return None
return value
def get_db_converters(self, connection):
converters = super().get_db_converters(connection)
if connection.features.interprets_empty_strings_as_nulls:
converters += [self.convert_empty_strings]
return converters
def get_col(self, alias, output_field=None):
if output_field is None:
output_field = self.target_field
while isinstance(output_field, ForeignKey):
output_field = output_field.target_field
if output_field is self:
raise ValueError("Cannot resolve output_field.")
return super().get_col(alias, output_field)
class OneToOneField(ForeignKey):
"""
A OneToOneField is essentially the same as a ForeignKey, with the exception
that it always carries a "unique" constraint with it and the reverse
relation always returns the object pointed to (since there will only ever
be one), rather than returning a list.
"""
# Field flags
many_to_many = False
many_to_one = False
one_to_many = False
one_to_one = True
related_accessor_class = ReverseOneToOneDescriptor
forward_related_accessor_class = ForwardOneToOneDescriptor
rel_class = OneToOneRel
description = _("One-to-one relationship")
def __init__(self, to, on_delete, to_field=None, **kwargs):
kwargs["unique"] = True
super().__init__(to, on_delete, to_field=to_field, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
if "unique" in kwargs:
del kwargs["unique"]
return name, path, args, kwargs
def formfield(self, **kwargs):
if self.remote_field.parent_link:
return None
return super().formfield(**kwargs)
def save_form_data(self, instance, data):
if isinstance(data, self.remote_field.model):
setattr(instance, self.name, data)
else:
setattr(instance, self.attname, data)
# Remote field object must be cleared otherwise Model.save()
# will reassign attname using the related object pk.
if data is None:
setattr(instance, self.name, data)
def _check_unique(self, **kwargs):
# Override ForeignKey since check isn't applicable here.
return []
def create_many_to_many_intermediary_model(field, klass):
from django.db import models
def set_managed(model, related, through):
through._meta.managed = model._meta.managed or related._meta.managed
to_model = resolve_relation(klass, field.remote_field.model)
name = "%s_%s" % (klass._meta.object_name, field.name)
lazy_related_operation(set_managed, klass, to_model, name)
to = make_model_tuple(to_model)[1]
from_ = klass._meta.model_name
if to == from_:
to = "to_%s" % to
from_ = "from_%s" % from_
meta = type(
"Meta",
(),
{
"db_table": field._get_m2m_db_table(klass._meta),
"auto_created": klass,
"app_label": klass._meta.app_label,
"db_tablespace": klass._meta.db_tablespace,
"unique_together": (from_, to),
"verbose_name": _("%(from)s-%(to)s relationship")
% {"from": from_, "to": to},
"verbose_name_plural": _("%(from)s-%(to)s relationships")
% {"from": from_, "to": to},
"apps": field.model._meta.apps,
},
)
# Construct and return the new class.
return type(
name,
(models.Model,),
{
"Meta": meta,
"__module__": klass.__module__,
from_: models.ForeignKey(
klass,
related_name="%s+" % name,
db_tablespace=field.db_tablespace,
db_constraint=field.remote_field.db_constraint,
on_delete=CASCADE,
),
to: models.ForeignKey(
to_model,
related_name="%s+" % name,
db_tablespace=field.db_tablespace,
db_constraint=field.remote_field.db_constraint,
on_delete=CASCADE,
),
},
)
class ManyToManyField(RelatedField):
"""
Provide a many-to-many relation by using an intermediary model that
holds two ForeignKey fields pointed at the two sides of the relation.
Unless a ``through`` model was provided, ManyToManyField will use the
create_many_to_many_intermediary_model factory to automatically generate
the intermediary model.
"""
# Field flags
many_to_many = True
many_to_one = False
one_to_many = False
one_to_one = False
rel_class = ManyToManyRel
description = _("Many-to-many relationship")
def __init__(
self,
to,
related_name=None,
related_query_name=None,
limit_choices_to=None,
symmetrical=None,
through=None,
through_fields=None,
db_constraint=True,
db_table=None,
swappable=True,
**kwargs,
):
try:
to._meta
except AttributeError:
if not isinstance(to, str):
raise TypeError(
"%s(%r) is invalid. First parameter to ManyToManyField "
"must be either a model, a model name, or the string %r"
% (
self.__class__.__name__,
to,
RECURSIVE_RELATIONSHIP_CONSTANT,
)
)
if symmetrical is None:
symmetrical = to == RECURSIVE_RELATIONSHIP_CONSTANT
if through is not None and db_table is not None:
raise ValueError(
"Cannot specify a db_table if an intermediary model is used."
)
kwargs["rel"] = self.rel_class(
self,
to,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
symmetrical=symmetrical,
through=through,
through_fields=through_fields,
db_constraint=db_constraint,
)
self.has_null_arg = "null" in kwargs
super().__init__(
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
**kwargs,
)
self.db_table = db_table
self.swappable = swappable
def check(self, **kwargs):
return [
*super().check(**kwargs),
*self._check_unique(**kwargs),
*self._check_relationship_model(**kwargs),
*self._check_ignored_options(**kwargs),
*self._check_table_uniqueness(**kwargs),
]
def _check_unique(self, **kwargs):
if self.unique:
return [
checks.Error(
"ManyToManyFields cannot be unique.",
obj=self,
id="fields.E330",
)
]
return []
def _check_ignored_options(self, **kwargs):
warnings = []
if self.has_null_arg:
warnings.append(
checks.Warning(
"null has no effect on ManyToManyField.",
obj=self,
id="fields.W340",
)
)
if self._validators:
warnings.append(
checks.Warning(
"ManyToManyField does not support validators.",
obj=self,
id="fields.W341",
)
)
if self.remote_field.symmetrical and self._related_name:
warnings.append(
checks.Warning(
"related_name has no effect on ManyToManyField "
'with a symmetrical relationship, e.g. to "self".',
obj=self,
id="fields.W345",
)
)
return warnings
def _check_relationship_model(self, from_model=None, **kwargs):
if hasattr(self.remote_field.through, "_meta"):
qualified_model_name = "%s.%s" % (
self.remote_field.through._meta.app_label,
self.remote_field.through.__name__,
)
else:
qualified_model_name = self.remote_field.through
errors = []
if self.remote_field.through not in self.opts.apps.get_models(
include_auto_created=True
):
# The relationship model is not installed.
errors.append(
checks.Error(
"Field specifies a many-to-many relation through model "
"'%s', which has not been installed." % qualified_model_name,
obj=self,
id="fields.E331",
)
)
else:
assert from_model is not None, (
"ManyToManyField with intermediate "
"tables cannot be checked if you don't pass the model "
"where the field is attached to."
)
# Set some useful local variables
to_model = resolve_relation(from_model, self.remote_field.model)
from_model_name = from_model._meta.object_name
if isinstance(to_model, str):
to_model_name = to_model
else:
to_model_name = to_model._meta.object_name
relationship_model_name = self.remote_field.through._meta.object_name
self_referential = from_model == to_model
# Count foreign keys in intermediate model
if self_referential:
seen_self = sum(
from_model == getattr(field.remote_field, "model", None)
for field in self.remote_field.through._meta.fields
)
if seen_self > 2 and not self.remote_field.through_fields:
errors.append(
checks.Error(
"The model is used as an intermediate model by "
"'%s', but it has more than two foreign keys "
"to '%s', which is ambiguous. You must specify "
"which two foreign keys Django should use via the "
"through_fields keyword argument."
% (self, from_model_name),
hint=(
"Use through_fields to specify which two foreign keys "
"Django should use."
),
obj=self.remote_field.through,
id="fields.E333",
)
)
else:
# Count foreign keys in relationship model
seen_from = sum(
from_model == getattr(field.remote_field, "model", None)
for field in self.remote_field.through._meta.fields
)
seen_to = sum(
to_model == getattr(field.remote_field, "model", None)
for field in self.remote_field.through._meta.fields
)
if seen_from > 1 and not self.remote_field.through_fields:
errors.append(
checks.Error(
(
"The model is used as an intermediate model by "
"'%s', but it has more than one foreign key "
"from '%s', which is ambiguous. You must specify "
"which foreign key Django should use via the "
"through_fields keyword argument."
)
% (self, from_model_name),
hint=(
"If you want to create a recursive relationship, "
'use ManyToManyField("%s", through="%s").'
)
% (
RECURSIVE_RELATIONSHIP_CONSTANT,
relationship_model_name,
),
obj=self,
id="fields.E334",
)
)
if seen_to > 1 and not self.remote_field.through_fields:
errors.append(
checks.Error(
"The model is used as an intermediate model by "
"'%s', but it has more than one foreign key "
"to '%s', which is ambiguous. You must specify "
"which foreign key Django should use via the "
"through_fields keyword argument." % (self, to_model_name),
hint=(
"If you want to create a recursive relationship, "
'use ManyToManyField("%s", through="%s").'
)
% (
RECURSIVE_RELATIONSHIP_CONSTANT,
relationship_model_name,
),
obj=self,
id="fields.E335",
)
)
if seen_from == 0 or seen_to == 0:
errors.append(
checks.Error(
"The model is used as an intermediate model by "
"'%s', but it does not have a foreign key to '%s' or '%s'."
% (self, from_model_name, to_model_name),
obj=self.remote_field.through,
id="fields.E336",
)
)
# Validate `through_fields`.
if self.remote_field.through_fields is not None:
# Validate that we're given an iterable of at least two items
# and that none of them is "falsy".
if not (
len(self.remote_field.through_fields) >= 2
and self.remote_field.through_fields[0]
and self.remote_field.through_fields[1]
):
errors.append(
checks.Error(
"Field specifies 'through_fields' but does not provide "
"the names of the two link fields that should be used "
"for the relation through model '%s'." % qualified_model_name,
hint=(
"Make sure you specify 'through_fields' as "
"through_fields=('field1', 'field2')"
),
obj=self,
id="fields.E337",
)
)
# Validate the given through fields -- they should be actual
# fields on the through model, and also be foreign keys to the
# expected models.
else:
assert from_model is not None, (
"ManyToManyField with intermediate "
"tables cannot be checked if you don't pass the model "
"where the field is attached to."
)
source, through, target = (
from_model,
self.remote_field.through,
self.remote_field.model,
)
source_field_name, target_field_name = self.remote_field.through_fields[
:2
]
for field_name, related_model in (
(source_field_name, source),
(target_field_name, target),
):
possible_field_names = []
for f in through._meta.fields:
if (
hasattr(f, "remote_field")
and getattr(f.remote_field, "model", None) == related_model
):
possible_field_names.append(f.name)
if possible_field_names:
hint = (
"Did you mean one of the following foreign keys to '%s': "
"%s?"
% (
related_model._meta.object_name,
", ".join(possible_field_names),
)
)
else:
hint = None
try:
field = through._meta.get_field(field_name)
except exceptions.FieldDoesNotExist:
errors.append(
checks.Error(
"The intermediary model '%s' has no field '%s'."
% (qualified_model_name, field_name),
hint=hint,
obj=self,
id="fields.E338",
)
)
else:
if not (
hasattr(field, "remote_field")
and getattr(field.remote_field, "model", None)
== related_model
):
errors.append(
checks.Error(
"'%s.%s' is not a foreign key to '%s'."
% (
through._meta.object_name,
field_name,
related_model._meta.object_name,
),
hint=hint,
obj=self,
id="fields.E339",
)
)
return errors
def _check_table_uniqueness(self, **kwargs):
if (
isinstance(self.remote_field.through, str)
or not self.remote_field.through._meta.managed
):
return []
registered_tables = {
model._meta.db_table: model
for model in self.opts.apps.get_models(include_auto_created=True)
if model != self.remote_field.through and model._meta.managed
}
m2m_db_table = self.m2m_db_table()
model = registered_tables.get(m2m_db_table)
# The second condition allows multiple m2m relations on a model if
# some point to a through model that proxies another through model.
if (
model
and model._meta.concrete_model
!= self.remote_field.through._meta.concrete_model
):
if model._meta.auto_created:
def _get_field_name(model):
for field in model._meta.auto_created._meta.many_to_many:
if field.remote_field.through is model:
return field.name
opts = model._meta.auto_created._meta
clashing_obj = "%s.%s" % (opts.label, _get_field_name(model))
else:
clashing_obj = model._meta.label
if settings.DATABASE_ROUTERS:
error_class, error_id = checks.Warning, "fields.W344"
error_hint = (
"You have configured settings.DATABASE_ROUTERS. Verify "
"that the table of %r is correctly routed to a separate "
"database." % clashing_obj
)
else:
error_class, error_id = checks.Error, "fields.E340"
error_hint = None
return [
error_class(
"The field's intermediary table '%s' clashes with the "
"table name of '%s'." % (m2m_db_table, clashing_obj),
obj=self,
hint=error_hint,
id=error_id,
)
]
return []
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
# Handle the simpler arguments.
if self.db_table is not None:
kwargs["db_table"] = self.db_table
if self.remote_field.db_constraint is not True:
kwargs["db_constraint"] = self.remote_field.db_constraint
# Lowercase model names as they should be treated as case-insensitive.
if isinstance(self.remote_field.model, str):
if "." in self.remote_field.model:
app_label, model_name = self.remote_field.model.split(".")
kwargs["to"] = "%s.%s" % (app_label, model_name.lower())
else:
kwargs["to"] = self.remote_field.model.lower()
else:
kwargs["to"] = self.remote_field.model._meta.label_lower
if getattr(self.remote_field, "through", None) is not None:
if isinstance(self.remote_field.through, str):
kwargs["through"] = self.remote_field.through
elif not self.remote_field.through._meta.auto_created:
kwargs["through"] = self.remote_field.through._meta.label
# If swappable is True, then see if we're actually pointing to the target
# of a swap.
swappable_setting = self.swappable_setting
if swappable_setting is not None:
# If it's already a settings reference, error.
if hasattr(kwargs["to"], "setting_name"):
if kwargs["to"].setting_name != swappable_setting:
raise ValueError(
"Cannot deconstruct a ManyToManyField pointing to a "
"model that is swapped in place of more than one model "
"(%s and %s)" % (kwargs["to"].setting_name, swappable_setting)
)
kwargs["to"] = SettingsReference(
kwargs["to"],
swappable_setting,
)
return name, path, args, kwargs
def _get_path_info(self, direct=False, filtered_relation=None):
"""Called by both direct and indirect m2m traversal."""
int_model = self.remote_field.through
linkfield1 = int_model._meta.get_field(self.m2m_field_name())
linkfield2 = int_model._meta.get_field(self.m2m_reverse_field_name())
if direct:
join1infos = linkfield1.reverse_path_infos
if filtered_relation:
join2infos = linkfield2.get_path_info(filtered_relation)
else:
join2infos = linkfield2.path_infos
else:
join1infos = linkfield2.reverse_path_infos
if filtered_relation:
join2infos = linkfield1.get_path_info(filtered_relation)
else:
join2infos = linkfield1.path_infos
# Get join infos between the last model of join 1 and the first model
# of join 2. Assume the only reason these may differ is due to model
# inheritance.
join1_final = join1infos[-1].to_opts
join2_initial = join2infos[0].from_opts
if join1_final is join2_initial:
intermediate_infos = []
elif issubclass(join1_final.model, join2_initial.model):
intermediate_infos = join1_final.get_path_to_parent(join2_initial.model)
else:
intermediate_infos = join2_initial.get_path_from_parent(join1_final.model)
return [*join1infos, *intermediate_infos, *join2infos]
def get_path_info(self, filtered_relation=None):
return self._get_path_info(direct=True, filtered_relation=filtered_relation)
@cached_property
def path_infos(self):
return self.get_path_info()
def get_reverse_path_info(self, filtered_relation=None):
return self._get_path_info(direct=False, filtered_relation=filtered_relation)
@cached_property
def reverse_path_infos(self):
return self.get_reverse_path_info()
def _get_m2m_db_table(self, opts):
"""
Function that can be curried to provide the m2m table name for this
relation.
"""
if self.remote_field.through is not None:
return self.remote_field.through._meta.db_table
elif self.db_table:
return self.db_table
else:
m2m_table_name = "%s_%s" % (utils.strip_quotes(opts.db_table), self.name)
return utils.truncate_name(m2m_table_name, connection.ops.max_name_length())
def _get_m2m_attr(self, related, attr):
"""
Function that can be curried to provide the source accessor or DB
column name for the m2m table.
"""
cache_attr = "_m2m_%s_cache" % attr
if hasattr(self, cache_attr):
return getattr(self, cache_attr)
if self.remote_field.through_fields is not None:
link_field_name = self.remote_field.through_fields[0]
else:
link_field_name = None
for f in self.remote_field.through._meta.fields:
if (
f.is_relation
and f.remote_field.model == related.related_model
and (link_field_name is None or link_field_name == f.name)
):
setattr(self, cache_attr, getattr(f, attr))
return getattr(self, cache_attr)
def _get_m2m_reverse_attr(self, related, attr):
"""
Function that can be curried to provide the related accessor or DB
column name for the m2m table.
"""
cache_attr = "_m2m_reverse_%s_cache" % attr
if hasattr(self, cache_attr):
return getattr(self, cache_attr)
found = False
if self.remote_field.through_fields is not None:
link_field_name = self.remote_field.through_fields[1]
else:
link_field_name = None
for f in self.remote_field.through._meta.fields:
if f.is_relation and f.remote_field.model == related.model:
if link_field_name is None and related.related_model == related.model:
# If this is an m2m-intermediate to self,
# the first foreign key you find will be
# the source column. Keep searching for
# the second foreign key.
if found:
setattr(self, cache_attr, getattr(f, attr))
break
else:
found = True
elif link_field_name is None or link_field_name == f.name:
setattr(self, cache_attr, getattr(f, attr))
break
return getattr(self, cache_attr)
def contribute_to_class(self, cls, name, **kwargs):
# To support multiple relations to self, it's useful to have a non-None
# related name on symmetrical relations for internal reasons. The
# concept doesn't make a lot of sense externally ("you want me to
# specify *what* on my non-reversible relation?!"), so we set it up
# automatically. The funky name reduces the chance of an accidental
# clash.
if self.remote_field.symmetrical and (
self.remote_field.model == RECURSIVE_RELATIONSHIP_CONSTANT
or self.remote_field.model == cls._meta.object_name
):
self.remote_field.related_name = "%s_rel_+" % name
elif self.remote_field.is_hidden():
# If the backwards relation is disabled, replace the original
# related_name with one generated from the m2m field name. Django
# still uses backwards relations internally and we need to avoid
# clashes between multiple m2m fields with related_name == '+'.
self.remote_field.related_name = "_%s_%s_%s_+" % (
cls._meta.app_label,
cls.__name__.lower(),
name,
)
super().contribute_to_class(cls, name, **kwargs)
# The intermediate m2m model is not auto created if:
# 1) There is a manually specified intermediate, or
# 2) The class owning the m2m field is abstract.
# 3) The class owning the m2m field has been swapped out.
if not cls._meta.abstract:
if self.remote_field.through:
def resolve_through_model(_, model, field):
field.remote_field.through = model
lazy_related_operation(
resolve_through_model, cls, self.remote_field.through, field=self
)
elif not cls._meta.swapped:
self.remote_field.through = create_many_to_many_intermediary_model(
self, cls
)
# Add the descriptor for the m2m relation.
setattr(cls, self.name, ManyToManyDescriptor(self.remote_field, reverse=False))
# Set up the accessor for the m2m table name for the relation.
self.m2m_db_table = partial(self._get_m2m_db_table, cls._meta)
def contribute_to_related_class(self, cls, related):
# Internal M2Ms (i.e., those with a related name ending with '+')
# and swapped models don't get a related descriptor.
if (
not self.remote_field.is_hidden()
and not related.related_model._meta.swapped
):
setattr(
cls,
related.get_accessor_name(),
ManyToManyDescriptor(self.remote_field, reverse=True),
)
# Set up the accessors for the column names on the m2m table.
self.m2m_column_name = partial(self._get_m2m_attr, related, "column")
self.m2m_reverse_name = partial(self._get_m2m_reverse_attr, related, "column")
self.m2m_field_name = partial(self._get_m2m_attr, related, "name")
self.m2m_reverse_field_name = partial(
self._get_m2m_reverse_attr, related, "name"
)
get_m2m_rel = partial(self._get_m2m_attr, related, "remote_field")
self.m2m_target_field_name = lambda: get_m2m_rel().field_name
get_m2m_reverse_rel = partial(
self._get_m2m_reverse_attr, related, "remote_field"
)
self.m2m_reverse_target_field_name = lambda: get_m2m_reverse_rel().field_name
def set_attributes_from_rel(self):
pass
def value_from_object(self, obj):
return [] if obj.pk is None else list(getattr(obj, self.attname).all())
def save_form_data(self, instance, data):
getattr(instance, self.attname).set(data)
def formfield(self, *, using=None, **kwargs):
defaults = {
"form_class": forms.ModelMultipleChoiceField,
"queryset": self.remote_field.model._default_manager.using(using),
**kwargs,
}
# If initial is passed in, it's a list of related objects, but the
# MultipleChoiceField takes a list of IDs.
if defaults.get("initial") is not None:
initial = defaults["initial"]
if callable(initial):
initial = initial()
defaults["initial"] = [i.pk for i in initial]
return super().formfield(**defaults)
def db_check(self, connection):
return None
def db_type(self, connection):
# A ManyToManyField is not represented by a single column,
# so return None.
return None
def db_parameters(self, connection):
return {"type": None, "check": None}
|
9818ea0fc7f2ffe299bff4b171c498eb654a1e50959369013382569b367cf32b | """
Accessors for related objects.
When a field defines a relation between two models, each model class provides
an attribute to access related instances of the other model class (unless the
reverse accessor has been disabled with related_name='+').
Accessors are implemented as descriptors in order to customize access and
assignment. This module defines the descriptor classes.
Forward accessors follow foreign keys. Reverse accessors trace them back. For
example, with the following models::
class Parent(Model):
pass
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
``child.parent`` is a forward many-to-one relation. ``parent.children`` is a
reverse many-to-one relation.
There are three types of relations (many-to-one, one-to-one, and many-to-many)
and two directions (forward and reverse) for a total of six combinations.
1. Related instance on the forward side of a many-to-one relation:
``ForwardManyToOneDescriptor``.
Uniqueness of foreign key values is irrelevant to accessing the related
instance, making the many-to-one and one-to-one cases identical as far as
the descriptor is concerned. The constraint is checked upstream (unicity
validation in forms) or downstream (unique indexes in the database).
2. Related instance on the forward side of a one-to-one
relation: ``ForwardOneToOneDescriptor``.
It avoids querying the database when accessing the parent link field in
a multi-table inheritance scenario.
3. Related instance on the reverse side of a one-to-one relation:
``ReverseOneToOneDescriptor``.
One-to-one relations are asymmetrical, despite the apparent symmetry of the
name, because they're implemented in the database with a foreign key from
one table to another. As a consequence ``ReverseOneToOneDescriptor`` is
slightly different from ``ForwardManyToOneDescriptor``.
4. Related objects manager for related instances on the reverse side of a
many-to-one relation: ``ReverseManyToOneDescriptor``.
Unlike the previous two classes, this one provides access to a collection
of objects. It returns a manager rather than an instance.
5. Related objects manager for related instances on the forward or reverse
sides of a many-to-many relation: ``ManyToManyDescriptor``.
Many-to-many relations are symmetrical. The syntax of Django models
requires declaring them on one side but that's an implementation detail.
They could be declared on the other side without any change in behavior.
Therefore the forward and reverse descriptors can be the same.
If you're looking for ``ForwardManyToManyDescriptor`` or
``ReverseManyToManyDescriptor``, use ``ManyToManyDescriptor`` instead.
"""
from django.core.exceptions import FieldError
from django.db import connections, router, transaction
from django.db.models import Q, signals
from django.db.models.query import QuerySet
from django.db.models.query_utils import DeferredAttribute
from django.db.models.utils import resolve_callables
from django.utils.functional import cached_property
class ForeignKeyDeferredAttribute(DeferredAttribute):
def __set__(self, instance, value):
if instance.__dict__.get(self.field.attname) != value and self.field.is_cached(
instance
):
self.field.delete_cached_value(instance)
instance.__dict__[self.field.attname] = value
class ForwardManyToOneDescriptor:
"""
Accessor to the related object on the forward side of a many-to-one or
one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
``Child.parent`` is a ``ForwardManyToOneDescriptor`` instance.
"""
def __init__(self, field_with_rel):
self.field = field_with_rel
@cached_property
def RelatedObjectDoesNotExist(self):
# The exception can't be created at initialization time since the
# related model might not be resolved yet; `self.field.model` might
# still be a string model reference.
return type(
"RelatedObjectDoesNotExist",
(self.field.remote_field.model.DoesNotExist, AttributeError),
{
"__module__": self.field.model.__module__,
"__qualname__": "%s.%s.RelatedObjectDoesNotExist"
% (
self.field.model.__qualname__,
self.field.name,
),
},
)
def is_cached(self, instance):
return self.field.is_cached(instance)
def get_queryset(self, **hints):
return self.field.remote_field.model._base_manager.db_manager(hints=hints).all()
def get_prefetch_queryset(self, instances, queryset=None):
if queryset is None:
queryset = self.get_queryset()
queryset._add_hints(instance=instances[0])
rel_obj_attr = self.field.get_foreign_related_value
instance_attr = self.field.get_local_related_value
instances_dict = {instance_attr(inst): inst for inst in instances}
related_field = self.field.foreign_related_fields[0]
remote_field = self.field.remote_field
# FIXME: This will need to be revisited when we introduce support for
# composite fields. In the meantime we take this practical approach to
# solve a regression on 1.6 when the reverse manager in hidden
# (related_name ends with a '+'). Refs #21410.
# The check for len(...) == 1 is a special case that allows the query
# to be join-less and smaller. Refs #21760.
if remote_field.is_hidden() or len(self.field.foreign_related_fields) == 1:
query = {
"%s__in"
% related_field.name: {instance_attr(inst)[0] for inst in instances}
}
else:
query = {"%s__in" % self.field.related_query_name(): instances}
queryset = queryset.filter(**query)
# Since we're going to assign directly in the cache,
# we must manage the reverse relation cache manually.
if not remote_field.multiple:
for rel_obj in queryset:
instance = instances_dict[rel_obj_attr(rel_obj)]
remote_field.set_cached_value(rel_obj, instance)
return (
queryset,
rel_obj_attr,
instance_attr,
True,
self.field.get_cache_name(),
False,
)
def get_object(self, instance):
qs = self.get_queryset(instance=instance)
# Assuming the database enforces foreign keys, this won't fail.
return qs.get(self.field.get_reverse_related_filter(instance))
def __get__(self, instance, cls=None):
"""
Get the related instance through the forward relation.
With the example above, when getting ``child.parent``:
- ``self`` is the descriptor managing the ``parent`` attribute
- ``instance`` is the ``child`` instance
- ``cls`` is the ``Child`` class (we don't need it)
"""
if instance is None:
return self
# The related instance is loaded from the database and then cached
# by the field on the model instance state. It can also be pre-cached
# by the reverse accessor (ReverseOneToOneDescriptor).
try:
rel_obj = self.field.get_cached_value(instance)
except KeyError:
has_value = None not in self.field.get_local_related_value(instance)
ancestor_link = (
instance._meta.get_ancestor_link(self.field.model)
if has_value
else None
)
if ancestor_link and ancestor_link.is_cached(instance):
# An ancestor link will exist if this field is defined on a
# multi-table inheritance parent of the instance's class.
ancestor = ancestor_link.get_cached_value(instance)
# The value might be cached on an ancestor if the instance
# originated from walking down the inheritance chain.
rel_obj = self.field.get_cached_value(ancestor, default=None)
else:
rel_obj = None
if rel_obj is None and has_value:
rel_obj = self.get_object(instance)
remote_field = self.field.remote_field
# If this is a one-to-one relation, set the reverse accessor
# cache on the related object to the current instance to avoid
# an extra SQL query if it's accessed later on.
if not remote_field.multiple:
remote_field.set_cached_value(rel_obj, instance)
self.field.set_cached_value(instance, rel_obj)
if rel_obj is None and not self.field.null:
raise self.RelatedObjectDoesNotExist(
"%s has no %s." % (self.field.model.__name__, self.field.name)
)
else:
return rel_obj
def __set__(self, instance, value):
"""
Set the related instance through the forward relation.
With the example above, when setting ``child.parent = parent``:
- ``self`` is the descriptor managing the ``parent`` attribute
- ``instance`` is the ``child`` instance
- ``value`` is the ``parent`` instance on the right of the equal sign
"""
# An object must be an instance of the related class.
if value is not None and not isinstance(
value, self.field.remote_field.model._meta.concrete_model
):
raise ValueError(
'Cannot assign "%r": "%s.%s" must be a "%s" instance.'
% (
value,
instance._meta.object_name,
self.field.name,
self.field.remote_field.model._meta.object_name,
)
)
elif value is not None:
if instance._state.db is None:
instance._state.db = router.db_for_write(
instance.__class__, instance=value
)
if value._state.db is None:
value._state.db = router.db_for_write(
value.__class__, instance=instance
)
if not router.allow_relation(value, instance):
raise ValueError(
'Cannot assign "%r": the current database router prevents this '
"relation." % value
)
remote_field = self.field.remote_field
# If we're setting the value of a OneToOneField to None, we need to clear
# out the cache on any old related object. Otherwise, deleting the
# previously-related object will also cause this object to be deleted,
# which is wrong.
if value is None:
# Look up the previously-related object, which may still be available
# since we've not yet cleared out the related field.
# Use the cache directly, instead of the accessor; if we haven't
# populated the cache, then we don't care - we're only accessing
# the object to invalidate the accessor cache, so there's no
# need to populate the cache just to expire it again.
related = self.field.get_cached_value(instance, default=None)
# If we've got an old related object, we need to clear out its
# cache. This cache also might not exist if the related object
# hasn't been accessed yet.
if related is not None:
remote_field.set_cached_value(related, None)
for lh_field, rh_field in self.field.related_fields:
setattr(instance, lh_field.attname, None)
# Set the values of the related field.
else:
for lh_field, rh_field in self.field.related_fields:
setattr(instance, lh_field.attname, getattr(value, rh_field.attname))
# Set the related instance cache used by __get__ to avoid an SQL query
# when accessing the attribute we just set.
self.field.set_cached_value(instance, value)
# If this is a one-to-one relation, set the reverse accessor cache on
# the related object to the current instance to avoid an extra SQL
# query if it's accessed later on.
if value is not None and not remote_field.multiple:
remote_field.set_cached_value(value, instance)
def __reduce__(self):
"""
Pickling should return the instance attached by self.field on the
model, not a new copy of that descriptor. Use getattr() to retrieve
the instance directly from the model.
"""
return getattr, (self.field.model, self.field.name)
class ForwardOneToOneDescriptor(ForwardManyToOneDescriptor):
"""
Accessor to the related object on the forward side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
``Restaurant.place`` is a ``ForwardOneToOneDescriptor`` instance.
"""
def get_object(self, instance):
if self.field.remote_field.parent_link:
deferred = instance.get_deferred_fields()
# Because it's a parent link, all the data is available in the
# instance, so populate the parent model with this data.
rel_model = self.field.remote_field.model
fields = [field.attname for field in rel_model._meta.concrete_fields]
# If any of the related model's fields are deferred, fallback to
# fetching all fields from the related model. This avoids a query
# on the related model for every deferred field.
if not any(field in fields for field in deferred):
kwargs = {field: getattr(instance, field) for field in fields}
obj = rel_model(**kwargs)
obj._state.adding = instance._state.adding
obj._state.db = instance._state.db
return obj
return super().get_object(instance)
def __set__(self, instance, value):
super().__set__(instance, value)
# If the primary key is a link to a parent model and a parent instance
# is being set, update the value of the inherited pk(s).
if self.field.primary_key and self.field.remote_field.parent_link:
opts = instance._meta
# Inherited primary key fields from this object's base classes.
inherited_pk_fields = [
field
for field in opts.concrete_fields
if field.primary_key and field.remote_field
]
for field in inherited_pk_fields:
rel_model_pk_name = field.remote_field.model._meta.pk.attname
raw_value = (
getattr(value, rel_model_pk_name) if value is not None else None
)
setattr(instance, rel_model_pk_name, raw_value)
class ReverseOneToOneDescriptor:
"""
Accessor to the related object on the reverse side of a one-to-one
relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
``Place.restaurant`` is a ``ReverseOneToOneDescriptor`` instance.
"""
def __init__(self, related):
# Following the example above, `related` is an instance of OneToOneRel
# which represents the reverse restaurant field (place.restaurant).
self.related = related
@cached_property
def RelatedObjectDoesNotExist(self):
# The exception isn't created at initialization time for the sake of
# consistency with `ForwardManyToOneDescriptor`.
return type(
"RelatedObjectDoesNotExist",
(self.related.related_model.DoesNotExist, AttributeError),
{
"__module__": self.related.model.__module__,
"__qualname__": "%s.%s.RelatedObjectDoesNotExist"
% (
self.related.model.__qualname__,
self.related.name,
),
},
)
def is_cached(self, instance):
return self.related.is_cached(instance)
def get_queryset(self, **hints):
return self.related.related_model._base_manager.db_manager(hints=hints).all()
def get_prefetch_queryset(self, instances, queryset=None):
if queryset is None:
queryset = self.get_queryset()
queryset._add_hints(instance=instances[0])
rel_obj_attr = self.related.field.get_local_related_value
instance_attr = self.related.field.get_foreign_related_value
instances_dict = {instance_attr(inst): inst for inst in instances}
query = {"%s__in" % self.related.field.name: instances}
queryset = queryset.filter(**query)
# Since we're going to assign directly in the cache,
# we must manage the reverse relation cache manually.
for rel_obj in queryset:
instance = instances_dict[rel_obj_attr(rel_obj)]
self.related.field.set_cached_value(rel_obj, instance)
return (
queryset,
rel_obj_attr,
instance_attr,
True,
self.related.get_cache_name(),
False,
)
def __get__(self, instance, cls=None):
"""
Get the related instance through the reverse relation.
With the example above, when getting ``place.restaurant``:
- ``self`` is the descriptor managing the ``restaurant`` attribute
- ``instance`` is the ``place`` instance
- ``cls`` is the ``Place`` class (unused)
Keep in mind that ``Restaurant`` holds the foreign key to ``Place``.
"""
if instance is None:
return self
# The related instance is loaded from the database and then cached
# by the field on the model instance state. It can also be pre-cached
# by the forward accessor (ForwardManyToOneDescriptor).
try:
rel_obj = self.related.get_cached_value(instance)
except KeyError:
related_pk = instance.pk
if related_pk is None:
rel_obj = None
else:
filter_args = self.related.field.get_forward_related_filter(instance)
try:
rel_obj = self.get_queryset(instance=instance).get(**filter_args)
except self.related.related_model.DoesNotExist:
rel_obj = None
else:
# Set the forward accessor cache on the related object to
# the current instance to avoid an extra SQL query if it's
# accessed later on.
self.related.field.set_cached_value(rel_obj, instance)
self.related.set_cached_value(instance, rel_obj)
if rel_obj is None:
raise self.RelatedObjectDoesNotExist(
"%s has no %s."
% (instance.__class__.__name__, self.related.get_accessor_name())
)
else:
return rel_obj
def __set__(self, instance, value):
"""
Set the related instance through the reverse relation.
With the example above, when setting ``place.restaurant = restaurant``:
- ``self`` is the descriptor managing the ``restaurant`` attribute
- ``instance`` is the ``place`` instance
- ``value`` is the ``restaurant`` instance on the right of the equal sign
Keep in mind that ``Restaurant`` holds the foreign key to ``Place``.
"""
# The similarity of the code below to the code in
# ForwardManyToOneDescriptor is annoying, but there's a bunch
# of small differences that would make a common base class convoluted.
if value is None:
# Update the cached related instance (if any) & clear the cache.
# Following the example above, this would be the cached
# ``restaurant`` instance (if any).
rel_obj = self.related.get_cached_value(instance, default=None)
if rel_obj is not None:
# Remove the ``restaurant`` instance from the ``place``
# instance cache.
self.related.delete_cached_value(instance)
# Set the ``place`` field on the ``restaurant``
# instance to None.
setattr(rel_obj, self.related.field.name, None)
elif not isinstance(value, self.related.related_model):
# An object must be an instance of the related class.
raise ValueError(
'Cannot assign "%r": "%s.%s" must be a "%s" instance.'
% (
value,
instance._meta.object_name,
self.related.get_accessor_name(),
self.related.related_model._meta.object_name,
)
)
else:
if instance._state.db is None:
instance._state.db = router.db_for_write(
instance.__class__, instance=value
)
if value._state.db is None:
value._state.db = router.db_for_write(
value.__class__, instance=instance
)
if not router.allow_relation(value, instance):
raise ValueError(
'Cannot assign "%r": the current database router prevents this '
"relation." % value
)
related_pk = tuple(
getattr(instance, field.attname)
for field in self.related.field.foreign_related_fields
)
# Set the value of the related field to the value of the related
# object's related field.
for index, field in enumerate(self.related.field.local_related_fields):
setattr(value, field.attname, related_pk[index])
# Set the related instance cache used by __get__ to avoid an SQL query
# when accessing the attribute we just set.
self.related.set_cached_value(instance, value)
# Set the forward accessor cache on the related object to the current
# instance to avoid an extra SQL query if it's accessed later on.
self.related.field.set_cached_value(value, instance)
def __reduce__(self):
# Same purpose as ForwardManyToOneDescriptor.__reduce__().
return getattr, (self.related.model, self.related.name)
class ReverseManyToOneDescriptor:
"""
Accessor to the related objects manager on the reverse side of a
many-to-one relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
``Parent.children`` is a ``ReverseManyToOneDescriptor`` instance.
Most of the implementation is delegated to a dynamically defined manager
class built by ``create_forward_many_to_many_manager()`` defined below.
"""
def __init__(self, rel):
self.rel = rel
self.field = rel.field
@cached_property
def related_manager_cache_key(self):
# Being able to access the manager instance precludes it from being
# hidden. The rel's accessor name is used to allow multiple managers
# to the same model to coexist. e.g. post.attached_comment_set and
# post.attached_link_set are separately cached.
return self.rel.get_cache_name()
@cached_property
def related_manager_cls(self):
related_model = self.rel.related_model
return create_reverse_many_to_one_manager(
related_model._default_manager.__class__,
self.rel,
)
def __get__(self, instance, cls=None):
"""
Get the related objects through the reverse relation.
With the example above, when getting ``parent.children``:
- ``self`` is the descriptor managing the ``children`` attribute
- ``instance`` is the ``parent`` instance
- ``cls`` is the ``Parent`` class (unused)
"""
if instance is None:
return self
key = self.related_manager_cache_key
instance_cache = instance._state.related_managers_cache
if key not in instance_cache:
instance_cache[key] = self.related_manager_cls(instance)
return instance_cache[key]
def _get_set_deprecation_msg_params(self):
return (
"reverse side of a related set",
self.rel.get_accessor_name(),
)
def __set__(self, instance, value):
raise TypeError(
"Direct assignment to the %s is prohibited. Use %s.set() instead."
% self._get_set_deprecation_msg_params(),
)
def create_reverse_many_to_one_manager(superclass, rel):
"""
Create a manager for the reverse side of a many-to-one relation.
This manager subclasses another manager, generally the default manager of
the related model, and adds behaviors specific to many-to-one relations.
"""
class RelatedManager(superclass):
def __init__(self, instance):
super().__init__()
self.instance = instance
self.model = rel.related_model
self.field = rel.field
self.core_filters = {self.field.name: instance}
# Even if this relation is not to pk, we require still pk value.
# The wish is that the instance has been already saved to DB,
# although having a pk value isn't a guarantee of that.
if self.instance.pk is None:
raise ValueError(
f"{instance.__class__.__name__!r} instance needs to have a primary "
f"key value before this relationship can be used."
)
def __call__(self, *, manager):
manager = getattr(self.model, manager)
manager_class = create_reverse_many_to_one_manager(manager.__class__, rel)
return manager_class(self.instance)
do_not_call_in_templates = True
def _check_fk_val(self):
for field in self.field.foreign_related_fields:
if getattr(self.instance, field.attname) is None:
raise ValueError(
f'"{self.instance!r}" needs to have a value for field '
f'"{field.attname}" before this relationship can be used.'
)
def _apply_rel_filters(self, queryset):
"""
Filter the queryset for the instance this manager is bound to.
"""
db = self._db or router.db_for_read(self.model, instance=self.instance)
empty_strings_as_null = connections[
db
].features.interprets_empty_strings_as_nulls
queryset._add_hints(instance=self.instance)
if self._db:
queryset = queryset.using(self._db)
queryset._defer_next_filter = True
queryset = queryset.filter(**self.core_filters)
for field in self.field.foreign_related_fields:
val = getattr(self.instance, field.attname)
if val is None or (val == "" and empty_strings_as_null):
return queryset.none()
if self.field.many_to_one:
# Guard against field-like objects such as GenericRelation
# that abuse create_reverse_many_to_one_manager() with reverse
# one-to-many relationships instead and break known related
# objects assignment.
try:
target_field = self.field.target_field
except FieldError:
# The relationship has multiple target fields. Use a tuple
# for related object id.
rel_obj_id = tuple(
[
getattr(self.instance, target_field.attname)
for target_field in self.field.path_infos[-1].target_fields
]
)
else:
rel_obj_id = getattr(self.instance, target_field.attname)
queryset._known_related_objects = {
self.field: {rel_obj_id: self.instance}
}
return queryset
def _remove_prefetched_objects(self):
try:
self.instance._prefetched_objects_cache.pop(
self.field.remote_field.get_cache_name()
)
except (AttributeError, KeyError):
pass # nothing to clear from cache
def get_queryset(self):
try:
return self.instance._prefetched_objects_cache[
self.field.remote_field.get_cache_name()
]
except (AttributeError, KeyError):
queryset = super().get_queryset()
return self._apply_rel_filters(queryset)
def get_prefetch_queryset(self, instances, queryset=None):
if queryset is None:
queryset = super().get_queryset()
queryset._add_hints(instance=instances[0])
queryset = queryset.using(queryset._db or self._db)
rel_obj_attr = self.field.get_local_related_value
instance_attr = self.field.get_foreign_related_value
instances_dict = {instance_attr(inst): inst for inst in instances}
query = {"%s__in" % self.field.name: instances}
queryset = queryset.filter(**query)
# Since we just bypassed this class' get_queryset(), we must manage
# the reverse relation manually.
for rel_obj in queryset:
if not self.field.is_cached(rel_obj):
instance = instances_dict[rel_obj_attr(rel_obj)]
setattr(rel_obj, self.field.name, instance)
cache_name = self.field.remote_field.get_cache_name()
return queryset, rel_obj_attr, instance_attr, False, cache_name, False
def add(self, *objs, bulk=True):
self._check_fk_val()
self._remove_prefetched_objects()
db = router.db_for_write(self.model, instance=self.instance)
def check_and_update_obj(obj):
if not isinstance(obj, self.model):
raise TypeError(
"'%s' instance expected, got %r"
% (
self.model._meta.object_name,
obj,
)
)
setattr(obj, self.field.name, self.instance)
if bulk:
pks = []
for obj in objs:
check_and_update_obj(obj)
if obj._state.adding or obj._state.db != db:
raise ValueError(
"%r instance isn't saved. Use bulk=False or save "
"the object first." % obj
)
pks.append(obj.pk)
self.model._base_manager.using(db).filter(pk__in=pks).update(
**{
self.field.name: self.instance,
}
)
else:
with transaction.atomic(using=db, savepoint=False):
for obj in objs:
check_and_update_obj(obj)
obj.save()
add.alters_data = True
def create(self, **kwargs):
self._check_fk_val()
kwargs[self.field.name] = self.instance
db = router.db_for_write(self.model, instance=self.instance)
return super(RelatedManager, self.db_manager(db)).create(**kwargs)
create.alters_data = True
def get_or_create(self, **kwargs):
self._check_fk_val()
kwargs[self.field.name] = self.instance
db = router.db_for_write(self.model, instance=self.instance)
return super(RelatedManager, self.db_manager(db)).get_or_create(**kwargs)
get_or_create.alters_data = True
def update_or_create(self, **kwargs):
self._check_fk_val()
kwargs[self.field.name] = self.instance
db = router.db_for_write(self.model, instance=self.instance)
return super(RelatedManager, self.db_manager(db)).update_or_create(**kwargs)
update_or_create.alters_data = True
# remove() and clear() are only provided if the ForeignKey can have a
# value of null.
if rel.field.null:
def remove(self, *objs, bulk=True):
if not objs:
return
self._check_fk_val()
val = self.field.get_foreign_related_value(self.instance)
old_ids = set()
for obj in objs:
if not isinstance(obj, self.model):
raise TypeError(
"'%s' instance expected, got %r"
% (
self.model._meta.object_name,
obj,
)
)
# Is obj actually part of this descriptor set?
if self.field.get_local_related_value(obj) == val:
old_ids.add(obj.pk)
else:
raise self.field.remote_field.model.DoesNotExist(
"%r is not related to %r." % (obj, self.instance)
)
self._clear(self.filter(pk__in=old_ids), bulk)
remove.alters_data = True
def clear(self, *, bulk=True):
self._check_fk_val()
self._clear(self, bulk)
clear.alters_data = True
def _clear(self, queryset, bulk):
self._remove_prefetched_objects()
db = router.db_for_write(self.model, instance=self.instance)
queryset = queryset.using(db)
if bulk:
# `QuerySet.update()` is intrinsically atomic.
queryset.update(**{self.field.name: None})
else:
with transaction.atomic(using=db, savepoint=False):
for obj in queryset:
setattr(obj, self.field.name, None)
obj.save(update_fields=[self.field.name])
_clear.alters_data = True
def set(self, objs, *, bulk=True, clear=False):
self._check_fk_val()
# Force evaluation of `objs` in case it's a queryset whose value
# could be affected by `manager.clear()`. Refs #19816.
objs = tuple(objs)
if self.field.null:
db = router.db_for_write(self.model, instance=self.instance)
with transaction.atomic(using=db, savepoint=False):
if clear:
self.clear(bulk=bulk)
self.add(*objs, bulk=bulk)
else:
old_objs = set(self.using(db).all())
new_objs = []
for obj in objs:
if obj in old_objs:
old_objs.remove(obj)
else:
new_objs.append(obj)
self.remove(*old_objs, bulk=bulk)
self.add(*new_objs, bulk=bulk)
else:
self.add(*objs, bulk=bulk)
set.alters_data = True
return RelatedManager
class ManyToManyDescriptor(ReverseManyToOneDescriptor):
"""
Accessor to the related objects manager on the forward and reverse sides of
a many-to-many relation.
In the example::
class Pizza(Model):
toppings = ManyToManyField(Topping, related_name='pizzas')
``Pizza.toppings`` and ``Topping.pizzas`` are ``ManyToManyDescriptor``
instances.
Most of the implementation is delegated to a dynamically defined manager
class built by ``create_forward_many_to_many_manager()`` defined below.
"""
def __init__(self, rel, reverse=False):
super().__init__(rel)
self.reverse = reverse
@property
def through(self):
# through is provided so that you have easy access to the through
# model (Book.authors.through) for inlines, etc. This is done as
# a property to ensure that the fully resolved value is returned.
return self.rel.through
@cached_property
def related_manager_cls(self):
related_model = self.rel.related_model if self.reverse else self.rel.model
return create_forward_many_to_many_manager(
related_model._default_manager.__class__,
self.rel,
reverse=self.reverse,
)
@cached_property
def related_manager_cache_key(self):
if self.reverse:
# Symmetrical M2Ms won't have an accessor name, but should never
# end up in the reverse branch anyway, as the related_name ends up
# being hidden, and no public manager is created.
return self.rel.get_cache_name()
else:
# For forward managers, defer to the field name.
return self.field.get_cache_name()
def _get_set_deprecation_msg_params(self):
return (
"%s side of a many-to-many set"
% ("reverse" if self.reverse else "forward"),
self.rel.get_accessor_name() if self.reverse else self.field.name,
)
def create_forward_many_to_many_manager(superclass, rel, reverse):
"""
Create a manager for the either side of a many-to-many relation.
This manager subclasses another manager, generally the default manager of
the related model, and adds behaviors specific to many-to-many relations.
"""
class ManyRelatedManager(superclass):
def __init__(self, instance=None):
super().__init__()
self.instance = instance
if not reverse:
self.model = rel.model
self.query_field_name = rel.field.related_query_name()
self.prefetch_cache_name = rel.field.name
self.source_field_name = rel.field.m2m_field_name()
self.target_field_name = rel.field.m2m_reverse_field_name()
self.symmetrical = rel.symmetrical
else:
self.model = rel.related_model
self.query_field_name = rel.field.name
self.prefetch_cache_name = rel.field.related_query_name()
self.source_field_name = rel.field.m2m_reverse_field_name()
self.target_field_name = rel.field.m2m_field_name()
self.symmetrical = False
self.through = rel.through
self.reverse = reverse
self.source_field = self.through._meta.get_field(self.source_field_name)
self.target_field = self.through._meta.get_field(self.target_field_name)
self.core_filters = {}
self.pk_field_names = {}
for lh_field, rh_field in self.source_field.related_fields:
core_filter_key = "%s__%s" % (self.query_field_name, rh_field.name)
self.core_filters[core_filter_key] = getattr(instance, rh_field.attname)
self.pk_field_names[lh_field.name] = rh_field.name
self.related_val = self.source_field.get_foreign_related_value(instance)
if None in self.related_val:
raise ValueError(
'"%r" needs to have a value for field "%s" before '
"this many-to-many relationship can be used."
% (instance, self.pk_field_names[self.source_field_name])
)
# Even if this relation is not to pk, we require still pk value.
# The wish is that the instance has been already saved to DB,
# although having a pk value isn't a guarantee of that.
if instance.pk is None:
raise ValueError(
"%r instance needs to have a primary key value before "
"a many-to-many relationship can be used."
% instance.__class__.__name__
)
def __call__(self, *, manager):
manager = getattr(self.model, manager)
manager_class = create_forward_many_to_many_manager(
manager.__class__, rel, reverse
)
return manager_class(instance=self.instance)
do_not_call_in_templates = True
def _build_remove_filters(self, removed_vals):
filters = Q.create([(self.source_field_name, self.related_val)])
# No need to add a subquery condition if removed_vals is a QuerySet without
# filters.
removed_vals_filters = (
not isinstance(removed_vals, QuerySet) or removed_vals._has_filters()
)
if removed_vals_filters:
filters &= Q.create([(f"{self.target_field_name}__in", removed_vals)])
if self.symmetrical:
symmetrical_filters = Q.create(
[(self.target_field_name, self.related_val)]
)
if removed_vals_filters:
symmetrical_filters &= Q.create(
[(f"{self.source_field_name}__in", removed_vals)]
)
filters |= symmetrical_filters
return filters
def _apply_rel_filters(self, queryset):
"""
Filter the queryset for the instance this manager is bound to.
"""
queryset._add_hints(instance=self.instance)
if self._db:
queryset = queryset.using(self._db)
queryset._defer_next_filter = True
return queryset._next_is_sticky().filter(**self.core_filters)
def _remove_prefetched_objects(self):
try:
self.instance._prefetched_objects_cache.pop(self.prefetch_cache_name)
except (AttributeError, KeyError):
pass # nothing to clear from cache
def get_queryset(self):
try:
return self.instance._prefetched_objects_cache[self.prefetch_cache_name]
except (AttributeError, KeyError):
queryset = super().get_queryset()
return self._apply_rel_filters(queryset)
def get_prefetch_queryset(self, instances, queryset=None):
if queryset is None:
queryset = super().get_queryset()
queryset._add_hints(instance=instances[0])
queryset = queryset.using(queryset._db or self._db)
query = {"%s__in" % self.query_field_name: instances}
queryset = queryset._next_is_sticky().filter(**query)
# M2M: need to annotate the query in order to get the primary model
# that the secondary model was actually related to. We know that
# there will already be a join on the join table, so we can just add
# the select.
# For non-autocreated 'through' models, can't assume we are
# dealing with PK values.
fk = self.through._meta.get_field(self.source_field_name)
join_table = fk.model._meta.db_table
connection = connections[queryset.db]
qn = connection.ops.quote_name
queryset = queryset.extra(
select={
"_prefetch_related_val_%s"
% f.attname: "%s.%s"
% (qn(join_table), qn(f.column))
for f in fk.local_related_fields
}
)
return (
queryset,
lambda result: tuple(
getattr(result, "_prefetch_related_val_%s" % f.attname)
for f in fk.local_related_fields
),
lambda inst: tuple(
f.get_db_prep_value(getattr(inst, f.attname), connection)
for f in fk.foreign_related_fields
),
False,
self.prefetch_cache_name,
False,
)
def add(self, *objs, through_defaults=None):
self._remove_prefetched_objects()
db = router.db_for_write(self.through, instance=self.instance)
with transaction.atomic(using=db, savepoint=False):
self._add_items(
self.source_field_name,
self.target_field_name,
*objs,
through_defaults=through_defaults,
)
# If this is a symmetrical m2m relation to self, add the mirror
# entry in the m2m table.
if self.symmetrical:
self._add_items(
self.target_field_name,
self.source_field_name,
*objs,
through_defaults=through_defaults,
)
add.alters_data = True
def remove(self, *objs):
self._remove_prefetched_objects()
self._remove_items(self.source_field_name, self.target_field_name, *objs)
remove.alters_data = True
def clear(self):
db = router.db_for_write(self.through, instance=self.instance)
with transaction.atomic(using=db, savepoint=False):
signals.m2m_changed.send(
sender=self.through,
action="pre_clear",
instance=self.instance,
reverse=self.reverse,
model=self.model,
pk_set=None,
using=db,
)
self._remove_prefetched_objects()
filters = self._build_remove_filters(super().get_queryset().using(db))
self.through._default_manager.using(db).filter(filters).delete()
signals.m2m_changed.send(
sender=self.through,
action="post_clear",
instance=self.instance,
reverse=self.reverse,
model=self.model,
pk_set=None,
using=db,
)
clear.alters_data = True
def set(self, objs, *, clear=False, through_defaults=None):
# Force evaluation of `objs` in case it's a queryset whose value
# could be affected by `manager.clear()`. Refs #19816.
objs = tuple(objs)
db = router.db_for_write(self.through, instance=self.instance)
with transaction.atomic(using=db, savepoint=False):
if clear:
self.clear()
self.add(*objs, through_defaults=through_defaults)
else:
old_ids = set(
self.using(db).values_list(
self.target_field.target_field.attname, flat=True
)
)
new_objs = []
for obj in objs:
fk_val = (
self.target_field.get_foreign_related_value(obj)[0]
if isinstance(obj, self.model)
else self.target_field.get_prep_value(obj)
)
if fk_val in old_ids:
old_ids.remove(fk_val)
else:
new_objs.append(obj)
self.remove(*old_ids)
self.add(*new_objs, through_defaults=through_defaults)
set.alters_data = True
def create(self, *, through_defaults=None, **kwargs):
db = router.db_for_write(self.instance.__class__, instance=self.instance)
new_obj = super(ManyRelatedManager, self.db_manager(db)).create(**kwargs)
self.add(new_obj, through_defaults=through_defaults)
return new_obj
create.alters_data = True
def get_or_create(self, *, through_defaults=None, **kwargs):
db = router.db_for_write(self.instance.__class__, instance=self.instance)
obj, created = super(ManyRelatedManager, self.db_manager(db)).get_or_create(
**kwargs
)
# We only need to add() if created because if we got an object back
# from get() then the relationship already exists.
if created:
self.add(obj, through_defaults=through_defaults)
return obj, created
get_or_create.alters_data = True
def update_or_create(self, *, through_defaults=None, **kwargs):
db = router.db_for_write(self.instance.__class__, instance=self.instance)
obj, created = super(
ManyRelatedManager, self.db_manager(db)
).update_or_create(**kwargs)
# We only need to add() if created because if we got an object back
# from get() then the relationship already exists.
if created:
self.add(obj, through_defaults=through_defaults)
return obj, created
update_or_create.alters_data = True
def _get_target_ids(self, target_field_name, objs):
"""
Return the set of ids of `objs` that the target field references.
"""
from django.db.models import Model
target_ids = set()
target_field = self.through._meta.get_field(target_field_name)
for obj in objs:
if isinstance(obj, self.model):
if not router.allow_relation(obj, self.instance):
raise ValueError(
'Cannot add "%r": instance is on database "%s", '
'value is on database "%s"'
% (obj, self.instance._state.db, obj._state.db)
)
target_id = target_field.get_foreign_related_value(obj)[0]
if target_id is None:
raise ValueError(
'Cannot add "%r": the value for field "%s" is None'
% (obj, target_field_name)
)
target_ids.add(target_id)
elif isinstance(obj, Model):
raise TypeError(
"'%s' instance expected, got %r"
% (self.model._meta.object_name, obj)
)
else:
target_ids.add(target_field.get_prep_value(obj))
return target_ids
def _get_missing_target_ids(
self, source_field_name, target_field_name, db, target_ids
):
"""
Return the subset of ids of `objs` that aren't already assigned to
this relationship.
"""
vals = (
self.through._default_manager.using(db)
.values_list(target_field_name, flat=True)
.filter(
**{
source_field_name: self.related_val[0],
"%s__in" % target_field_name: target_ids,
}
)
)
return target_ids.difference(vals)
def _get_add_plan(self, db, source_field_name):
"""
Return a boolean triple of the way the add should be performed.
The first element is whether or not bulk_create(ignore_conflicts)
can be used, the second whether or not signals must be sent, and
the third element is whether or not the immediate bulk insertion
with conflicts ignored can be performed.
"""
# Conflicts can be ignored when the intermediary model is
# auto-created as the only possible collision is on the
# (source_id, target_id) tuple. The same assertion doesn't hold for
# user-defined intermediary models as they could have other fields
# causing conflicts which must be surfaced.
can_ignore_conflicts = (
self.through._meta.auto_created is not False
and connections[db].features.supports_ignore_conflicts
)
# Don't send the signal when inserting duplicate data row
# for symmetrical reverse entries.
must_send_signals = (
self.reverse or source_field_name == self.source_field_name
) and (signals.m2m_changed.has_listeners(self.through))
# Fast addition through bulk insertion can only be performed
# if no m2m_changed listeners are connected for self.through
# as they require the added set of ids to be provided via
# pk_set.
return (
can_ignore_conflicts,
must_send_signals,
(can_ignore_conflicts and not must_send_signals),
)
def _add_items(
self, source_field_name, target_field_name, *objs, through_defaults=None
):
# source_field_name: the PK fieldname in join table for the source object
# target_field_name: the PK fieldname in join table for the target object
# *objs - objects to add. Either object instances, or primary keys
# of object instances.
if not objs:
return
through_defaults = dict(resolve_callables(through_defaults or {}))
target_ids = self._get_target_ids(target_field_name, objs)
db = router.db_for_write(self.through, instance=self.instance)
can_ignore_conflicts, must_send_signals, can_fast_add = self._get_add_plan(
db, source_field_name
)
if can_fast_add:
self.through._default_manager.using(db).bulk_create(
[
self.through(
**{
"%s_id" % source_field_name: self.related_val[0],
"%s_id" % target_field_name: target_id,
}
)
for target_id in target_ids
],
ignore_conflicts=True,
)
return
missing_target_ids = self._get_missing_target_ids(
source_field_name, target_field_name, db, target_ids
)
with transaction.atomic(using=db, savepoint=False):
if must_send_signals:
signals.m2m_changed.send(
sender=self.through,
action="pre_add",
instance=self.instance,
reverse=self.reverse,
model=self.model,
pk_set=missing_target_ids,
using=db,
)
# Add the ones that aren't there already.
self.through._default_manager.using(db).bulk_create(
[
self.through(
**through_defaults,
**{
"%s_id" % source_field_name: self.related_val[0],
"%s_id" % target_field_name: target_id,
},
)
for target_id in missing_target_ids
],
ignore_conflicts=can_ignore_conflicts,
)
if must_send_signals:
signals.m2m_changed.send(
sender=self.through,
action="post_add",
instance=self.instance,
reverse=self.reverse,
model=self.model,
pk_set=missing_target_ids,
using=db,
)
def _remove_items(self, source_field_name, target_field_name, *objs):
# source_field_name: the PK colname in join table for the source object
# target_field_name: the PK colname in join table for the target object
# *objs - objects to remove. Either object instances, or primary
# keys of object instances.
if not objs:
return
# Check that all the objects are of the right type
old_ids = set()
for obj in objs:
if isinstance(obj, self.model):
fk_val = self.target_field.get_foreign_related_value(obj)[0]
old_ids.add(fk_val)
else:
old_ids.add(obj)
db = router.db_for_write(self.through, instance=self.instance)
with transaction.atomic(using=db, savepoint=False):
# Send a signal to the other end if need be.
signals.m2m_changed.send(
sender=self.through,
action="pre_remove",
instance=self.instance,
reverse=self.reverse,
model=self.model,
pk_set=old_ids,
using=db,
)
target_model_qs = super().get_queryset()
if target_model_qs._has_filters():
old_vals = target_model_qs.using(db).filter(
**{"%s__in" % self.target_field.target_field.attname: old_ids}
)
else:
old_vals = old_ids
filters = self._build_remove_filters(old_vals)
self.through._default_manager.using(db).filter(filters).delete()
signals.m2m_changed.send(
sender=self.through,
action="post_remove",
instance=self.instance,
reverse=self.reverse,
model=self.model,
pk_set=old_ids,
using=db,
)
return ManyRelatedManager
|
b8b68b71166ad11fb913b4c4c2df2c9cb62bd0ae2f62b3100fb7b8b1e4c707f2 | """
Create SQL statements for QuerySets.
The code in here encapsulates all of the SQL construction so that QuerySets
themselves do not have to (and could be backed by things other than SQL
databases). The abstraction barrier only works one way: this module has to know
all about the internals of models in order to get the information it needs.
"""
import copy
import difflib
import functools
import sys
from collections import Counter, namedtuple
from collections.abc import Iterator, Mapping
from itertools import chain, count, product
from string import ascii_uppercase
from django.core.exceptions import FieldDoesNotExist, FieldError
from django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections
from django.db.models.aggregates import Count
from django.db.models.constants import LOOKUP_SEP
from django.db.models.expressions import (
BaseExpression,
Col,
Exists,
F,
OuterRef,
Ref,
ResolvedOuterRef,
Value,
)
from django.db.models.fields import Field
from django.db.models.fields.related_lookups import MultiColSource
from django.db.models.lookups import Lookup
from django.db.models.query_utils import (
Q,
check_rel_lookup_compatibility,
refs_expression,
)
from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE
from django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin
from django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode
from django.utils.functional import cached_property
from django.utils.regex_helper import _lazy_re_compile
from django.utils.tree import Node
__all__ = ["Query", "RawQuery"]
# Quotation marks ('"`[]), whitespace characters, semicolons, or inline
# SQL comments are forbidden in column aliases.
FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/")
# Inspired from
# https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
EXPLAIN_OPTIONS_PATTERN = _lazy_re_compile(r"[\w\-]+")
def get_field_names_from_opts(opts):
if opts is None:
return set()
return set(
chain.from_iterable(
(f.name, f.attname) if f.concrete else (f.name,) for f in opts.get_fields()
)
)
def get_children_from_q(q):
for child in q.children:
if isinstance(child, Node):
yield from get_children_from_q(child)
else:
yield child
JoinInfo = namedtuple(
"JoinInfo",
("final_field", "targets", "opts", "joins", "path", "transform_function"),
)
class RawQuery:
"""A single raw SQL query."""
def __init__(self, sql, using, params=()):
self.params = params
self.sql = sql
self.using = using
self.cursor = None
# Mirror some properties of a normal query so that
# the compiler can be used to process results.
self.low_mark, self.high_mark = 0, None # Used for offset/limit
self.extra_select = {}
self.annotation_select = {}
def chain(self, using):
return self.clone(using)
def clone(self, using):
return RawQuery(self.sql, using, params=self.params)
def get_columns(self):
if self.cursor is None:
self._execute_query()
converter = connections[self.using].introspection.identifier_converter
return [converter(column_meta[0]) for column_meta in self.cursor.description]
def __iter__(self):
# Always execute a new query for a new iterator.
# This could be optimized with a cache at the expense of RAM.
self._execute_query()
if not connections[self.using].features.can_use_chunked_reads:
# If the database can't use chunked reads we need to make sure we
# evaluate the entire query up front.
result = list(self.cursor)
else:
result = self.cursor
return iter(result)
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self)
@property
def params_type(self):
if self.params is None:
return None
return dict if isinstance(self.params, Mapping) else tuple
def __str__(self):
if self.params_type is None:
return self.sql
return self.sql % self.params_type(self.params)
def _execute_query(self):
connection = connections[self.using]
# Adapt parameters to the database, as much as possible considering
# that the target type isn't known. See #17755.
params_type = self.params_type
adapter = connection.ops.adapt_unknown_value
if params_type is tuple:
params = tuple(adapter(val) for val in self.params)
elif params_type is dict:
params = {key: adapter(val) for key, val in self.params.items()}
elif params_type is None:
params = None
else:
raise RuntimeError("Unexpected params type: %s" % params_type)
self.cursor = connection.cursor()
self.cursor.execute(self.sql, params)
ExplainInfo = namedtuple("ExplainInfo", ("format", "options"))
class Query(BaseExpression):
"""A single SQL query."""
alias_prefix = "T"
empty_result_set_value = None
subq_aliases = frozenset([alias_prefix])
compiler = "SQLCompiler"
base_table_class = BaseTable
join_class = Join
default_cols = True
default_ordering = True
standard_ordering = True
filter_is_sticky = False
subquery = False
# SQL-related attributes.
# Select and related select clauses are expressions to use in the SELECT
# clause of the query. The select is used for cases where we want to set up
# the select clause to contain other than default fields (values(),
# subqueries...). Note that annotations go to annotations dictionary.
select = ()
# The group_by attribute can have one of the following forms:
# - None: no group by at all in the query
# - A tuple of expressions: group by (at least) those expressions.
# String refs are also allowed for now.
# - True: group by all select fields of the model
# See compiler.get_group_by() for details.
group_by = None
order_by = ()
low_mark = 0 # Used for offset/limit.
high_mark = None # Used for offset/limit.
distinct = False
distinct_fields = ()
select_for_update = False
select_for_update_nowait = False
select_for_update_skip_locked = False
select_for_update_of = ()
select_for_no_key_update = False
select_related = False
# Arbitrary limit for select_related to prevents infinite recursion.
max_depth = 5
# Holds the selects defined by a call to values() or values_list()
# excluding annotation_select and extra_select.
values_select = ()
# SQL annotation-related attributes.
annotation_select_mask = None
_annotation_select_cache = None
# Set combination attributes.
combinator = None
combinator_all = False
combined_queries = ()
# These are for extensions. The contents are more or less appended verbatim
# to the appropriate clause.
extra_select_mask = None
_extra_select_cache = None
extra_tables = ()
extra_order_by = ()
# A tuple that is a set of model field names and either True, if these are
# the fields to defer, or False if these are the only fields to load.
deferred_loading = (frozenset(), True)
explain_info = None
def __init__(self, model, alias_cols=True):
self.model = model
self.alias_refcount = {}
# alias_map is the most important data structure regarding joins.
# It's used for recording which joins exist in the query and what
# types they are. The key is the alias of the joined table (possibly
# the table name) and the value is a Join-like object (see
# sql.datastructures.Join for more information).
self.alias_map = {}
# Whether to provide alias to columns during reference resolving.
self.alias_cols = alias_cols
# Sometimes the query contains references to aliases in outer queries (as
# a result of split_exclude). Correct alias quoting needs to know these
# aliases too.
# Map external tables to whether they are aliased.
self.external_aliases = {}
self.table_map = {} # Maps table names to list of aliases.
self.used_aliases = set()
self.where = WhereNode()
# Maps alias -> Annotation Expression.
self.annotations = {}
# These are for extensions. The contents are more or less appended
# verbatim to the appropriate clause.
self.extra = {} # Maps col_alias -> (col_sql, params).
self._filtered_relations = {}
@property
def output_field(self):
if len(self.select) == 1:
select = self.select[0]
return getattr(select, "target", None) or select.field
elif len(self.annotation_select) == 1:
return next(iter(self.annotation_select.values())).output_field
@property
def has_select_fields(self):
return bool(
self.select or self.annotation_select_mask or self.extra_select_mask
)
@cached_property
def base_table(self):
for alias in self.alias_map:
return alias
def __str__(self):
"""
Return the query as a string of SQL with the parameter values
substituted in (use sql_with_params() to see the unsubstituted string).
Parameter values won't necessarily be quoted correctly, since that is
done by the database interface at execution time.
"""
sql, params = self.sql_with_params()
return sql % params
def sql_with_params(self):
"""
Return the query as an SQL string and the parameters that will be
substituted into the query.
"""
return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()
def __deepcopy__(self, memo):
"""Limit the amount of work when a Query is deepcopied."""
result = self.clone()
memo[id(self)] = result
return result
def get_compiler(self, using=None, connection=None, elide_empty=True):
if using is None and connection is None:
raise ValueError("Need either using or connection")
if using:
connection = connections[using]
return connection.ops.compiler(self.compiler)(
self, connection, using, elide_empty
)
def get_meta(self):
"""
Return the Options instance (the model._meta) from which to start
processing. Normally, this is self.model._meta, but it can be changed
by subclasses.
"""
if self.model:
return self.model._meta
def clone(self):
"""
Return a copy of the current Query. A lightweight alternative to
deepcopy().
"""
obj = Empty()
obj.__class__ = self.__class__
# Copy references to everything.
obj.__dict__ = self.__dict__.copy()
# Clone attributes that can't use shallow copy.
obj.alias_refcount = self.alias_refcount.copy()
obj.alias_map = self.alias_map.copy()
obj.external_aliases = self.external_aliases.copy()
obj.table_map = self.table_map.copy()
obj.where = self.where.clone()
obj.annotations = self.annotations.copy()
if self.annotation_select_mask is not None:
obj.annotation_select_mask = self.annotation_select_mask.copy()
if self.combined_queries:
obj.combined_queries = tuple(
[query.clone() for query in self.combined_queries]
)
# _annotation_select_cache cannot be copied, as doing so breaks the
# (necessary) state in which both annotations and
# _annotation_select_cache point to the same underlying objects.
# It will get re-populated in the cloned queryset the next time it's
# used.
obj._annotation_select_cache = None
obj.extra = self.extra.copy()
if self.extra_select_mask is not None:
obj.extra_select_mask = self.extra_select_mask.copy()
if self._extra_select_cache is not None:
obj._extra_select_cache = self._extra_select_cache.copy()
if self.select_related is not False:
# Use deepcopy because select_related stores fields in nested
# dicts.
obj.select_related = copy.deepcopy(obj.select_related)
if "subq_aliases" in self.__dict__:
obj.subq_aliases = self.subq_aliases.copy()
obj.used_aliases = self.used_aliases.copy()
obj._filtered_relations = self._filtered_relations.copy()
# Clear the cached_property, if it exists.
obj.__dict__.pop("base_table", None)
return obj
def chain(self, klass=None):
"""
Return a copy of the current Query that's ready for another operation.
The klass argument changes the type of the Query, e.g. UpdateQuery.
"""
obj = self.clone()
if klass and obj.__class__ != klass:
obj.__class__ = klass
if not obj.filter_is_sticky:
obj.used_aliases = set()
obj.filter_is_sticky = False
if hasattr(obj, "_setup_query"):
obj._setup_query()
return obj
def relabeled_clone(self, change_map):
clone = self.clone()
clone.change_aliases(change_map)
return clone
def _get_col(self, target, field, alias):
if not self.alias_cols:
alias = None
return target.get_col(alias, field)
def rewrite_cols(self, annotation, col_cnt):
# We must make sure the inner query has the referred columns in it.
# If we are aggregating over an annotation, then Django uses Ref()
# instances to note this. However, if we are annotating over a column
# of a related model, then it might be that column isn't part of the
# SELECT clause of the inner query, and we must manually make sure
# the column is selected. An example case is:
# .aggregate(Sum('author__awards'))
# Resolving this expression results in a join to author, but there
# is no guarantee the awards column of author is in the select clause
# of the query. Thus we must manually add the column to the inner
# query.
orig_exprs = annotation.get_source_expressions()
new_exprs = []
for expr in orig_exprs:
# FIXME: These conditions are fairly arbitrary. Identify a better
# method of having expressions decide which code path they should
# take.
if isinstance(expr, Ref):
# Its already a Ref to subquery (see resolve_ref() for
# details)
new_exprs.append(expr)
elif isinstance(expr, (WhereNode, Lookup)):
# Decompose the subexpressions further. The code here is
# copied from the else clause, but this condition must appear
# before the contains_aggregate/is_summary condition below.
new_expr, col_cnt = self.rewrite_cols(expr, col_cnt)
new_exprs.append(new_expr)
else:
# Reuse aliases of expressions already selected in subquery.
for col_alias, selected_annotation in self.annotation_select.items():
if selected_annotation is expr:
new_expr = Ref(col_alias, expr)
break
else:
# An expression that is not selected the subquery.
if isinstance(expr, Col) or (
expr.contains_aggregate and not expr.is_summary
):
# Reference column or another aggregate. Select it
# under a non-conflicting alias.
col_cnt += 1
col_alias = "__col%d" % col_cnt
self.annotations[col_alias] = expr
self.append_annotation_mask([col_alias])
new_expr = Ref(col_alias, expr)
else:
# Some other expression not referencing database values
# directly. Its subexpression might contain Cols.
new_expr, col_cnt = self.rewrite_cols(expr, col_cnt)
new_exprs.append(new_expr)
annotation.set_source_expressions(new_exprs)
return annotation, col_cnt
def get_aggregation(self, using, added_aggregate_names):
"""
Return the dictionary with the values of the existing aggregations.
"""
if not self.annotation_select:
return {}
existing_annotations = [
annotation
for alias, annotation in self.annotations.items()
if alias not in added_aggregate_names
]
# Decide if we need to use a subquery.
#
# Existing annotations would cause incorrect results as get_aggregation()
# must produce just one result and thus must not use GROUP BY. But we
# aren't smart enough to remove the existing annotations from the
# query, so those would force us to use GROUP BY.
#
# If the query has limit or distinct, or uses set operations, then
# those operations must be done in a subquery so that the query
# aggregates on the limit and/or distinct results instead of applying
# the distinct and limit after the aggregation.
if (
isinstance(self.group_by, tuple)
or self.is_sliced
or existing_annotations
or self.distinct
or self.combinator
):
from django.db.models.sql.subqueries import AggregateQuery
inner_query = self.clone()
inner_query.subquery = True
outer_query = AggregateQuery(self.model, inner_query)
inner_query.select_for_update = False
inner_query.select_related = False
inner_query.set_annotation_mask(self.annotation_select)
# Queries with distinct_fields need ordering and when a limit is
# applied we must take the slice from the ordered query. Otherwise
# no need for ordering.
inner_query.clear_ordering(force=False)
if not inner_query.distinct:
# If the inner query uses default select and it has some
# aggregate annotations, then we must make sure the inner
# query is grouped by the main model's primary key. However,
# clearing the select clause can alter results if distinct is
# used.
has_existing_aggregate_annotations = any(
annotation
for annotation in existing_annotations
if getattr(annotation, "contains_aggregate", True)
)
if inner_query.default_cols and has_existing_aggregate_annotations:
inner_query.group_by = (
self.model._meta.pk.get_col(inner_query.get_initial_alias()),
)
inner_query.default_cols = False
relabels = {t: "subquery" for t in inner_query.alias_map}
relabels[None] = "subquery"
# Remove any aggregates marked for reduction from the subquery
# and move them to the outer AggregateQuery.
col_cnt = 0
for alias, expression in list(inner_query.annotation_select.items()):
annotation_select_mask = inner_query.annotation_select_mask
if expression.is_summary:
expression, col_cnt = inner_query.rewrite_cols(expression, col_cnt)
outer_query.annotations[alias] = expression.relabeled_clone(
relabels
)
del inner_query.annotations[alias]
annotation_select_mask.remove(alias)
# Make sure the annotation_select wont use cached results.
inner_query.set_annotation_mask(inner_query.annotation_select_mask)
if (
inner_query.select == ()
and not inner_query.default_cols
and not inner_query.annotation_select_mask
):
# In case of Model.objects[0:3].count(), there would be no
# field selected in the inner query, yet we must use a subquery.
# So, make sure at least one field is selected.
inner_query.select = (
self.model._meta.pk.get_col(inner_query.get_initial_alias()),
)
else:
outer_query = self
self.select = ()
self.default_cols = False
self.extra = {}
empty_set_result = [
expression.empty_result_set_value
for expression in outer_query.annotation_select.values()
]
elide_empty = not any(result is NotImplemented for result in empty_set_result)
outer_query.clear_ordering(force=True)
outer_query.clear_limits()
outer_query.select_for_update = False
outer_query.select_related = False
compiler = outer_query.get_compiler(using, elide_empty=elide_empty)
result = compiler.execute_sql(SINGLE)
if result is None:
result = empty_set_result
converters = compiler.get_converters(outer_query.annotation_select.values())
result = next(compiler.apply_converters((result,), converters))
return dict(zip(outer_query.annotation_select, result))
def get_count(self, using):
"""
Perform a COUNT() query using the current filter constraints.
"""
obj = self.clone()
obj.add_annotation(Count("*"), alias="__count", is_summary=True)
return obj.get_aggregation(using, ["__count"])["__count"]
def has_filters(self):
return self.where
def exists(self, using, limit=True):
q = self.clone()
if not (q.distinct and q.is_sliced):
if q.group_by is True:
q.add_fields(
(f.attname for f in self.model._meta.concrete_fields), False
)
# Disable GROUP BY aliases to avoid orphaning references to the
# SELECT clause which is about to be cleared.
q.set_group_by(allow_aliases=False)
q.clear_select_clause()
if q.combined_queries and q.combinator == "union":
limit_combined = connections[
using
].features.supports_slicing_ordering_in_compound
q.combined_queries = tuple(
combined_query.exists(using, limit=limit_combined)
for combined_query in q.combined_queries
)
q.clear_ordering(force=True)
if limit:
q.set_limits(high=1)
q.add_annotation(Value(1), "a")
return q
def has_results(self, using):
q = self.exists(using)
compiler = q.get_compiler(using=using)
return compiler.has_results()
def explain(self, using, format=None, **options):
q = self.clone()
for option_name in options:
if (
not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name)
or "--" in option_name
):
raise ValueError(f"Invalid option name: {option_name!r}.")
q.explain_info = ExplainInfo(format, options)
compiler = q.get_compiler(using=using)
return "\n".join(compiler.explain_query())
def combine(self, rhs, connector):
"""
Merge the 'rhs' query into the current one (with any 'rhs' effects
being applied *after* (that is, "to the right of") anything in the
current query. 'rhs' is not modified during a call to this function.
The 'connector' parameter describes how to connect filters from the
'rhs' query.
"""
if self.model != rhs.model:
raise TypeError("Cannot combine queries on two different base models.")
if self.is_sliced:
raise TypeError("Cannot combine queries once a slice has been taken.")
if self.distinct != rhs.distinct:
raise TypeError("Cannot combine a unique query with a non-unique query.")
if self.distinct_fields != rhs.distinct_fields:
raise TypeError("Cannot combine queries with different distinct fields.")
# If lhs and rhs shares the same alias prefix, it is possible to have
# conflicting alias changes like T4 -> T5, T5 -> T6, which might end up
# as T4 -> T6 while combining two querysets. To prevent this, change an
# alias prefix of the rhs and update current aliases accordingly,
# except if the alias is the base table since it must be present in the
# query on both sides.
initial_alias = self.get_initial_alias()
rhs.bump_prefix(self, exclude={initial_alias})
# Work out how to relabel the rhs aliases, if necessary.
change_map = {}
conjunction = connector == AND
# Determine which existing joins can be reused. When combining the
# query with AND we must recreate all joins for m2m filters. When
# combining with OR we can reuse joins. The reason is that in AND
# case a single row can't fulfill a condition like:
# revrel__col=1 & revrel__col=2
# But, there might be two different related rows matching this
# condition. In OR case a single True is enough, so single row is
# enough, too.
#
# Note that we will be creating duplicate joins for non-m2m joins in
# the AND case. The results will be correct but this creates too many
# joins. This is something that could be fixed later on.
reuse = set() if conjunction else set(self.alias_map)
joinpromoter = JoinPromoter(connector, 2, False)
joinpromoter.add_votes(
j for j in self.alias_map if self.alias_map[j].join_type == INNER
)
rhs_votes = set()
# Now, add the joins from rhs query into the new query (skipping base
# table).
rhs_tables = list(rhs.alias_map)[1:]
for alias in rhs_tables:
join = rhs.alias_map[alias]
# If the left side of the join was already relabeled, use the
# updated alias.
join = join.relabeled_clone(change_map)
new_alias = self.join(join, reuse=reuse)
if join.join_type == INNER:
rhs_votes.add(new_alias)
# We can't reuse the same join again in the query. If we have two
# distinct joins for the same connection in rhs query, then the
# combined query must have two joins, too.
reuse.discard(new_alias)
if alias != new_alias:
change_map[alias] = new_alias
if not rhs.alias_refcount[alias]:
# The alias was unused in the rhs query. Unref it so that it
# will be unused in the new query, too. We have to add and
# unref the alias so that join promotion has information of
# the join type for the unused alias.
self.unref_alias(new_alias)
joinpromoter.add_votes(rhs_votes)
joinpromoter.update_join_types(self)
# Combine subqueries aliases to ensure aliases relabelling properly
# handle subqueries when combining where and select clauses.
self.subq_aliases |= rhs.subq_aliases
# Now relabel a copy of the rhs where-clause and add it to the current
# one.
w = rhs.where.clone()
w.relabel_aliases(change_map)
self.where.add(w, connector)
# Selection columns and extra extensions are those provided by 'rhs'.
if rhs.select:
self.set_select([col.relabeled_clone(change_map) for col in rhs.select])
else:
self.select = ()
if connector == OR:
# It would be nice to be able to handle this, but the queries don't
# really make sense (or return consistent value sets). Not worth
# the extra complexity when you can write a real query instead.
if self.extra and rhs.extra:
raise ValueError(
"When merging querysets using 'or', you cannot have "
"extra(select=...) on both sides."
)
self.extra.update(rhs.extra)
extra_select_mask = set()
if self.extra_select_mask is not None:
extra_select_mask.update(self.extra_select_mask)
if rhs.extra_select_mask is not None:
extra_select_mask.update(rhs.extra_select_mask)
if extra_select_mask:
self.set_extra_mask(extra_select_mask)
self.extra_tables += rhs.extra_tables
# Ordering uses the 'rhs' ordering, unless it has none, in which case
# the current ordering is used.
self.order_by = rhs.order_by or self.order_by
self.extra_order_by = rhs.extra_order_by or self.extra_order_by
def deferred_to_data(self, target):
"""
Convert the self.deferred_loading data structure to an alternate data
structure, describing the field that *will* be loaded. This is used to
compute the columns to select from the database and also by the
QuerySet class to work out which fields are being initialized on each
model. Models that have all their fields included aren't mentioned in
the result, only those that have field restrictions in place.
The "target" parameter is the instance that is populated (in place).
"""
field_names, defer = self.deferred_loading
if not field_names:
return
orig_opts = self.get_meta()
seen = {}
must_include = {orig_opts.concrete_model: {orig_opts.pk}}
for field_name in field_names:
parts = field_name.split(LOOKUP_SEP)
cur_model = self.model._meta.concrete_model
opts = orig_opts
for name in parts[:-1]:
old_model = cur_model
if name in self._filtered_relations:
name = self._filtered_relations[name].relation_name
source = opts.get_field(name)
if is_reverse_o2o(source):
cur_model = source.related_model
else:
cur_model = source.remote_field.model
cur_model = cur_model._meta.concrete_model
opts = cur_model._meta
# Even if we're "just passing through" this model, we must add
# both the current model's pk and the related reference field
# (if it's not a reverse relation) to the things we select.
if not is_reverse_o2o(source):
must_include[old_model].add(source)
add_to_dict(must_include, cur_model, opts.pk)
field = opts.get_field(parts[-1])
is_reverse_object = field.auto_created and not field.concrete
model = field.related_model if is_reverse_object else field.model
model = model._meta.concrete_model
if model == opts.model:
model = cur_model
if not is_reverse_o2o(field):
add_to_dict(seen, model, field)
if defer:
# We need to load all fields for each model, except those that
# appear in "seen" (for all models that appear in "seen"). The only
# slight complexity here is handling fields that exist on parent
# models.
workset = {}
for model, values in seen.items():
for field in model._meta.local_fields:
if field not in values:
m = field.model._meta.concrete_model
add_to_dict(workset, m, field)
for model, values in must_include.items():
# If we haven't included a model in workset, we don't add the
# corresponding must_include fields for that model, since an
# empty set means "include all fields". That's why there's no
# "else" branch here.
if model in workset:
workset[model].update(values)
for model, fields in workset.items():
target[model] = {f.attname for f in fields}
else:
for model, values in must_include.items():
if model in seen:
seen[model].update(values)
else:
# As we've passed through this model, but not explicitly
# included any fields, we have to make sure it's mentioned
# so that only the "must include" fields are pulled in.
seen[model] = values
# Now ensure that every model in the inheritance chain is mentioned
# in the parent list. Again, it must be mentioned to ensure that
# only "must include" fields are pulled in.
for model in orig_opts.get_parent_list():
seen.setdefault(model, set())
for model, fields in seen.items():
target[model] = {f.attname for f in fields}
def table_alias(self, table_name, create=False, filtered_relation=None):
"""
Return a table alias for the given table_name and whether this is a
new alias or not.
If 'create' is true, a new alias is always created. Otherwise, the
most recently created alias for the table (if one exists) is reused.
"""
alias_list = self.table_map.get(table_name)
if not create and alias_list:
alias = alias_list[0]
self.alias_refcount[alias] += 1
return alias, False
# Create a new alias for this table.
if alias_list:
alias = "%s%d" % (self.alias_prefix, len(self.alias_map) + 1)
alias_list.append(alias)
else:
# The first occurrence of a table uses the table name directly.
alias = (
filtered_relation.alias if filtered_relation is not None else table_name
)
self.table_map[table_name] = [alias]
self.alias_refcount[alias] = 1
return alias, True
def ref_alias(self, alias):
"""Increases the reference count for this alias."""
self.alias_refcount[alias] += 1
def unref_alias(self, alias, amount=1):
"""Decreases the reference count for this alias."""
self.alias_refcount[alias] -= amount
def promote_joins(self, aliases):
"""
Promote recursively the join type of given aliases and its children to
an outer join. If 'unconditional' is False, only promote the join if
it is nullable or the parent join is an outer join.
The children promotion is done to avoid join chains that contain a LOUTER
b INNER c. So, if we have currently a INNER b INNER c and a->b is promoted,
then we must also promote b->c automatically, or otherwise the promotion
of a->b doesn't actually change anything in the query results.
"""
aliases = list(aliases)
while aliases:
alias = aliases.pop(0)
if self.alias_map[alias].join_type is None:
# This is the base table (first FROM entry) - this table
# isn't really joined at all in the query, so we should not
# alter its join type.
continue
# Only the first alias (skipped above) should have None join_type
assert self.alias_map[alias].join_type is not None
parent_alias = self.alias_map[alias].parent_alias
parent_louter = (
parent_alias and self.alias_map[parent_alias].join_type == LOUTER
)
already_louter = self.alias_map[alias].join_type == LOUTER
if (self.alias_map[alias].nullable or parent_louter) and not already_louter:
self.alias_map[alias] = self.alias_map[alias].promote()
# Join type of 'alias' changed, so re-examine all aliases that
# refer to this one.
aliases.extend(
join
for join in self.alias_map
if self.alias_map[join].parent_alias == alias
and join not in aliases
)
def demote_joins(self, aliases):
"""
Change join type from LOUTER to INNER for all joins in aliases.
Similarly to promote_joins(), this method must ensure no join chains
containing first an outer, then an inner join are generated. If we
are demoting b->c join in chain a LOUTER b LOUTER c then we must
demote a->b automatically, or otherwise the demotion of b->c doesn't
actually change anything in the query results. .
"""
aliases = list(aliases)
while aliases:
alias = aliases.pop(0)
if self.alias_map[alias].join_type == LOUTER:
self.alias_map[alias] = self.alias_map[alias].demote()
parent_alias = self.alias_map[alias].parent_alias
if self.alias_map[parent_alias].join_type == INNER:
aliases.append(parent_alias)
def reset_refcounts(self, to_counts):
"""
Reset reference counts for aliases so that they match the value passed
in `to_counts`.
"""
for alias, cur_refcount in self.alias_refcount.copy().items():
unref_amount = cur_refcount - to_counts.get(alias, 0)
self.unref_alias(alias, unref_amount)
def change_aliases(self, change_map):
"""
Change the aliases in change_map (which maps old-alias -> new-alias),
relabelling any references to them in select columns and the where
clause.
"""
# If keys and values of change_map were to intersect, an alias might be
# updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending
# on their order in change_map.
assert set(change_map).isdisjoint(change_map.values())
# 1. Update references in "select" (normal columns plus aliases),
# "group by" and "where".
self.where.relabel_aliases(change_map)
if isinstance(self.group_by, tuple):
self.group_by = tuple(
[col.relabeled_clone(change_map) for col in self.group_by]
)
self.select = tuple([col.relabeled_clone(change_map) for col in self.select])
self.annotations = self.annotations and {
key: col.relabeled_clone(change_map)
for key, col in self.annotations.items()
}
# 2. Rename the alias in the internal table/alias datastructures.
for old_alias, new_alias in change_map.items():
if old_alias not in self.alias_map:
continue
alias_data = self.alias_map[old_alias].relabeled_clone(change_map)
self.alias_map[new_alias] = alias_data
self.alias_refcount[new_alias] = self.alias_refcount[old_alias]
del self.alias_refcount[old_alias]
del self.alias_map[old_alias]
table_aliases = self.table_map[alias_data.table_name]
for pos, alias in enumerate(table_aliases):
if alias == old_alias:
table_aliases[pos] = new_alias
break
self.external_aliases = {
# Table is aliased or it's being changed and thus is aliased.
change_map.get(alias, alias): (aliased or alias in change_map)
for alias, aliased in self.external_aliases.items()
}
def bump_prefix(self, other_query, exclude=None):
"""
Change the alias prefix to the next letter in the alphabet in a way
that the other query's aliases and this query's aliases will not
conflict. Even tables that previously had no alias will get an alias
after this call. To prevent changing aliases use the exclude parameter.
"""
def prefix_gen():
"""
Generate a sequence of characters in alphabetical order:
-> 'A', 'B', 'C', ...
When the alphabet is finished, the sequence will continue with the
Cartesian product:
-> 'AA', 'AB', 'AC', ...
"""
alphabet = ascii_uppercase
prefix = chr(ord(self.alias_prefix) + 1)
yield prefix
for n in count(1):
seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet
for s in product(seq, repeat=n):
yield "".join(s)
prefix = None
if self.alias_prefix != other_query.alias_prefix:
# No clashes between self and outer query should be possible.
return
# Explicitly avoid infinite loop. The constant divider is based on how
# much depth recursive subquery references add to the stack. This value
# might need to be adjusted when adding or removing function calls from
# the code path in charge of performing these operations.
local_recursion_limit = sys.getrecursionlimit() // 16
for pos, prefix in enumerate(prefix_gen()):
if prefix not in self.subq_aliases:
self.alias_prefix = prefix
break
if pos > local_recursion_limit:
raise RecursionError(
"Maximum recursion depth exceeded: too many subqueries."
)
self.subq_aliases = self.subq_aliases.union([self.alias_prefix])
other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases)
if exclude is None:
exclude = {}
self.change_aliases(
{
alias: "%s%d" % (self.alias_prefix, pos)
for pos, alias in enumerate(self.alias_map)
if alias not in exclude
}
)
def get_initial_alias(self):
"""
Return the first alias for this query, after increasing its reference
count.
"""
if self.alias_map:
alias = self.base_table
self.ref_alias(alias)
elif self.model:
alias = self.join(self.base_table_class(self.get_meta().db_table, None))
else:
alias = None
return alias
def count_active_tables(self):
"""
Return the number of tables in this query with a non-zero reference
count. After execution, the reference counts are zeroed, so tables
added in compiler will not be seen by this method.
"""
return len([1 for count in self.alias_refcount.values() if count])
def join(self, join, reuse=None, reuse_with_filtered_relation=False):
"""
Return an alias for the 'join', either reusing an existing alias for
that join or creating a new one. 'join' is either a base_table_class or
join_class.
The 'reuse' parameter can be either None which means all joins are
reusable, or it can be a set containing the aliases that can be reused.
The 'reuse_with_filtered_relation' parameter is used when computing
FilteredRelation instances.
A join is always created as LOUTER if the lhs alias is LOUTER to make
sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new
joins are created as LOUTER if the join is nullable.
"""
if reuse_with_filtered_relation and reuse:
reuse_aliases = [
a for a, j in self.alias_map.items() if a in reuse and j.equals(join)
]
else:
reuse_aliases = [
a
for a, j in self.alias_map.items()
if (reuse is None or a in reuse) and j == join
]
if reuse_aliases:
if join.table_alias in reuse_aliases:
reuse_alias = join.table_alias
else:
# Reuse the most recent alias of the joined table
# (a many-to-many relation may be joined multiple times).
reuse_alias = reuse_aliases[-1]
self.ref_alias(reuse_alias)
return reuse_alias
# No reuse is possible, so we need a new alias.
alias, _ = self.table_alias(
join.table_name, create=True, filtered_relation=join.filtered_relation
)
if join.join_type:
if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:
join_type = LOUTER
else:
join_type = INNER
join.join_type = join_type
join.table_alias = alias
self.alias_map[alias] = join
return alias
def join_parent_model(self, opts, model, alias, seen):
"""
Make sure the given 'model' is joined in the query. If 'model' isn't
a parent of 'opts' or if it is None this method is a no-op.
The 'alias' is the root alias for starting the join, 'seen' is a dict
of model -> alias of existing joins. It must also contain a mapping
of None -> some alias. This will be returned in the no-op case.
"""
if model in seen:
return seen[model]
chain = opts.get_base_chain(model)
if not chain:
return alias
curr_opts = opts
for int_model in chain:
if int_model in seen:
curr_opts = int_model._meta
alias = seen[int_model]
continue
# Proxy model have elements in base chain
# with no parents, assign the new options
# object and skip to the next base in that
# case
if not curr_opts.parents[int_model]:
curr_opts = int_model._meta
continue
link_field = curr_opts.get_ancestor_link(int_model)
join_info = self.setup_joins([link_field.name], curr_opts, alias)
curr_opts = int_model._meta
alias = seen[int_model] = join_info.joins[-1]
return alias or seen[None]
def check_alias(self, alias):
if FORBIDDEN_ALIAS_PATTERN.search(alias):
raise ValueError(
"Column aliases cannot contain whitespace characters, quotation marks, "
"semicolons, or SQL comments."
)
def add_annotation(self, annotation, alias, is_summary=False, select=True):
"""Add a single annotation expression to the Query."""
self.check_alias(alias)
annotation = annotation.resolve_expression(
self, allow_joins=True, reuse=None, summarize=is_summary
)
if select:
self.append_annotation_mask([alias])
else:
self.set_annotation_mask(set(self.annotation_select).difference({alias}))
self.annotations[alias] = annotation
def resolve_expression(self, query, *args, **kwargs):
clone = self.clone()
# Subqueries need to use a different set of aliases than the outer query.
clone.bump_prefix(query)
clone.subquery = True
clone.where.resolve_expression(query, *args, **kwargs)
# Resolve combined queries.
if clone.combinator:
clone.combined_queries = tuple(
[
combined_query.resolve_expression(query, *args, **kwargs)
for combined_query in clone.combined_queries
]
)
for key, value in clone.annotations.items():
resolved = value.resolve_expression(query, *args, **kwargs)
if hasattr(resolved, "external_aliases"):
resolved.external_aliases.update(clone.external_aliases)
clone.annotations[key] = resolved
# Outer query's aliases are considered external.
for alias, table in query.alias_map.items():
clone.external_aliases[alias] = (
isinstance(table, Join)
and table.join_field.related_model._meta.db_table != alias
) or (
isinstance(table, BaseTable) and table.table_name != table.table_alias
)
return clone
def get_external_cols(self):
exprs = chain(self.annotations.values(), self.where.children)
return [
col
for col in self._gen_cols(exprs, include_external=True)
if col.alias in self.external_aliases
]
def get_group_by_cols(self, alias=None):
if alias:
return [Ref(alias, self)]
external_cols = self.get_external_cols()
if any(col.possibly_multivalued for col in external_cols):
return [self]
return external_cols
def as_sql(self, compiler, connection):
# Some backends (e.g. Oracle) raise an error when a subquery contains
# unnecessary ORDER BY clause.
if (
self.subquery
and not connection.features.ignores_unnecessary_order_by_in_subqueries
):
self.clear_ordering(force=False)
for query in self.combined_queries:
query.clear_ordering(force=False)
sql, params = self.get_compiler(connection=connection).as_sql()
if self.subquery:
sql = "(%s)" % sql
return sql, params
def resolve_lookup_value(self, value, can_reuse, allow_joins):
if hasattr(value, "resolve_expression"):
value = value.resolve_expression(
self,
reuse=can_reuse,
allow_joins=allow_joins,
)
elif isinstance(value, (list, tuple)):
# The items of the iterable may be expressions and therefore need
# to be resolved independently.
values = (
self.resolve_lookup_value(sub_value, can_reuse, allow_joins)
for sub_value in value
)
type_ = type(value)
if hasattr(type_, "_make"): # namedtuple
return type_(*values)
return type_(values)
return value
def solve_lookup_type(self, lookup):
"""
Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').
"""
lookup_splitted = lookup.split(LOOKUP_SEP)
if self.annotations:
expression, expression_lookups = refs_expression(
lookup_splitted, self.annotations
)
if expression:
return expression_lookups, (), expression
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)]
if len(lookup_parts) > 1 and not field_parts:
raise FieldError(
'Invalid lookup "%s" for model %s".'
% (lookup, self.get_meta().model.__name__)
)
return lookup_parts, field_parts, False
def check_query_object_type(self, value, opts, field):
"""
Check whether the object passed while querying is of the correct type.
If not, raise a ValueError specifying the wrong object.
"""
if hasattr(value, "_meta"):
if not check_rel_lookup_compatibility(value._meta.model, opts, field):
raise ValueError(
'Cannot query "%s": Must be "%s" instance.'
% (value, opts.object_name)
)
def check_related_objects(self, field, value, opts):
"""Check the type of object passed to query relations."""
if field.is_relation:
# Check that the field and the queryset use the same model in a
# query like .filter(author=Author.objects.all()). For example, the
# opts would be Author's (from the author field) and value.model
# would be Author.objects.all() queryset's .model (Author also).
# The field is the related field on the lhs side.
if (
isinstance(value, Query)
and not value.has_select_fields
and not check_rel_lookup_compatibility(value.model, opts, field)
):
raise ValueError(
'Cannot use QuerySet for "%s": Use a QuerySet for "%s".'
% (value.model._meta.object_name, opts.object_name)
)
elif hasattr(value, "_meta"):
self.check_query_object_type(value, opts, field)
elif hasattr(value, "__iter__"):
for v in value:
self.check_query_object_type(v, opts, field)
def check_filterable(self, expression):
"""Raise an error if expression cannot be used in a WHERE clause."""
if hasattr(expression, "resolve_expression") and not getattr(
expression, "filterable", True
):
raise NotSupportedError(
expression.__class__.__name__ + " is disallowed in the filter "
"clause."
)
if hasattr(expression, "get_source_expressions"):
for expr in expression.get_source_expressions():
self.check_filterable(expr)
def build_lookup(self, lookups, lhs, rhs):
"""
Try to extract transforms and lookup from given lhs.
The lhs value is something that works like SQLExpression.
The rhs value is what the lookup is going to compare against.
The lookups is a list of names to extract using get_lookup()
and get_transform().
"""
# __exact is the default lookup if one isn't given.
*transforms, lookup_name = lookups or ["exact"]
for name in transforms:
lhs = self.try_transform(lhs, name)
# First try get_lookup() so that the lookup takes precedence if the lhs
# supports both transform and lookup for the name.
lookup_class = lhs.get_lookup(lookup_name)
if not lookup_class:
if lhs.field.is_relation:
raise FieldError(
"Related Field got invalid lookup: {}".format(lookup_name)
)
# A lookup wasn't found. Try to interpret the name as a transform
# and do an Exact lookup against it.
lhs = self.try_transform(lhs, lookup_name)
lookup_name = "exact"
lookup_class = lhs.get_lookup(lookup_name)
if not lookup_class:
return
lookup = lookup_class(lhs, rhs)
# Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all
# uses of None as a query value unless the lookup supports it.
if lookup.rhs is None and not lookup.can_use_none_as_rhs:
if lookup_name not in ("exact", "iexact"):
raise ValueError("Cannot use None as a query value")
return lhs.get_lookup("isnull")(lhs, True)
# For Oracle '' is equivalent to null. The check must be done at this
# stage because join promotion can't be done in the compiler. Using
# DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.
# A similar thing is done in is_nullable(), too.
if (
lookup_name == "exact"
and lookup.rhs == ""
and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls
):
return lhs.get_lookup("isnull")(lhs, True)
return lookup
def try_transform(self, lhs, name):
"""
Helper method for build_lookup(). Try to fetch and initialize
a transform for name parameter from lhs.
"""
transform_class = lhs.get_transform(name)
if transform_class:
return transform_class(lhs)
else:
output_field = lhs.output_field.__class__
suggested_lookups = difflib.get_close_matches(
name, output_field.get_lookups()
)
if suggested_lookups:
suggestion = ", perhaps you meant %s?" % " or ".join(suggested_lookups)
else:
suggestion = "."
raise FieldError(
"Unsupported lookup '%s' for %s or join on the field not "
"permitted%s" % (name, output_field.__name__, suggestion)
)
def build_filter(
self,
filter_expr,
branch_negated=False,
current_negated=False,
can_reuse=None,
allow_joins=True,
split_subq=True,
reuse_with_filtered_relation=False,
check_filterable=True,
):
"""
Build a WhereNode for a single filter clause but don't add it
to this Query. Query.add_q() will then add this filter to the where
Node.
The 'branch_negated' tells us if the current branch contains any
negations. This will be used to determine if subqueries are needed.
The 'current_negated' is used to determine if the current filter is
negated or not and this will be used to determine if IS NULL filtering
is needed.
The difference between current_negated and branch_negated is that
branch_negated is set on first negation, but current_negated is
flipped for each negation.
Note that add_filter will not do any negating itself, that is done
upper in the code by add_q().
The 'can_reuse' is a set of reusable joins for multijoins.
If 'reuse_with_filtered_relation' is True, then only joins in can_reuse
will be reused.
The method will create a filter clause that can be added to the current
query. However, if the filter isn't added to the query then the caller
is responsible for unreffing the joins used.
"""
if isinstance(filter_expr, dict):
raise FieldError("Cannot parse keyword query as dict")
if isinstance(filter_expr, Q):
return self._add_q(
filter_expr,
branch_negated=branch_negated,
current_negated=current_negated,
used_aliases=can_reuse,
allow_joins=allow_joins,
split_subq=split_subq,
check_filterable=check_filterable,
)
if hasattr(filter_expr, "resolve_expression"):
if not getattr(filter_expr, "conditional", False):
raise TypeError("Cannot filter against a non-conditional expression.")
condition = filter_expr.resolve_expression(self, allow_joins=allow_joins)
if not isinstance(condition, Lookup):
condition = self.build_lookup(["exact"], condition, True)
return WhereNode([condition], connector=AND), []
arg, value = filter_expr
if not arg:
raise FieldError("Cannot parse keyword query %r" % arg)
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
if check_filterable:
self.check_filterable(reffed_expression)
if not allow_joins and len(parts) > 1:
raise FieldError("Joined field references are not permitted in this query")
pre_joins = self.alias_refcount.copy()
value = self.resolve_lookup_value(value, can_reuse, allow_joins)
used_joins = {
k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)
}
if check_filterable:
self.check_filterable(value)
if reffed_expression:
condition = self.build_lookup(lookups, reffed_expression, value)
return WhereNode([condition], connector=AND), []
opts = self.get_meta()
alias = self.get_initial_alias()
allow_many = not branch_negated or not split_subq
try:
join_info = self.setup_joins(
parts,
opts,
alias,
can_reuse=can_reuse,
allow_many=allow_many,
reuse_with_filtered_relation=reuse_with_filtered_relation,
)
# Prevent iterator from being consumed by check_related_objects()
if isinstance(value, Iterator):
value = list(value)
self.check_related_objects(join_info.final_field, value, join_info.opts)
# split_exclude() needs to know which joins were generated for the
# lookup parts
self._lookup_joins = join_info.joins
except MultiJoin as e:
return self.split_exclude(filter_expr, can_reuse, e.names_with_path)
# Update used_joins before trimming since they are reused to determine
# which joins could be later promoted to INNER.
used_joins.update(join_info.joins)
targets, alias, join_list = self.trim_joins(
join_info.targets, join_info.joins, join_info.path
)
if can_reuse is not None:
can_reuse.update(join_list)
if join_info.final_field.is_relation:
# No support for transforms for relational fields
num_lookups = len(lookups)
if num_lookups > 1:
raise FieldError(
"Related Field got invalid lookup: {}".format(lookups[0])
)
if len(targets) == 1:
col = self._get_col(targets[0], join_info.final_field, alias)
else:
col = MultiColSource(
alias, targets, join_info.targets, join_info.final_field
)
else:
col = self._get_col(targets[0], join_info.final_field, alias)
condition = self.build_lookup(lookups, col, value)
lookup_type = condition.lookup_name
clause = WhereNode([condition], connector=AND)
require_outer = (
lookup_type == "isnull" and condition.rhs is True and not current_negated
)
if (
current_negated
and (lookup_type != "isnull" or condition.rhs is False)
and condition.rhs is not None
):
require_outer = True
if lookup_type != "isnull":
# The condition added here will be SQL like this:
# NOT (col IS NOT NULL), where the first NOT is added in
# upper layers of code. The reason for addition is that if col
# is null, then col != someval will result in SQL "unknown"
# which isn't the same as in Python. The Python None handling
# is wanted, and it can be gotten by
# (col IS NULL OR col != someval)
# <=>
# NOT (col IS NOT NULL AND col = someval).
if (
self.is_nullable(targets[0])
or self.alias_map[join_list[-1]].join_type == LOUTER
):
lookup_class = targets[0].get_lookup("isnull")
col = self._get_col(targets[0], join_info.targets[0], alias)
clause.add(lookup_class(col, False), AND)
# If someval is a nullable column, someval IS NOT NULL is
# added.
if isinstance(value, Col) and self.is_nullable(value.target):
lookup_class = value.target.get_lookup("isnull")
clause.add(lookup_class(value, False), AND)
return clause, used_joins if not require_outer else ()
def add_filter(self, filter_lhs, filter_rhs):
self.add_q(Q((filter_lhs, filter_rhs)))
def add_q(self, q_object):
"""
A preprocessor for the internal _add_q(). Responsible for doing final
join promotion.
"""
# For join promotion this case is doing an AND for the added q_object
# and existing conditions. So, any existing inner join forces the join
# type to remain inner. Existing outer joins can however be demoted.
# (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if
# rel_a doesn't produce any rows, then the whole condition must fail.
# So, demotion is OK.
existing_inner = {
a for a in self.alias_map if self.alias_map[a].join_type == INNER
}
clause, _ = self._add_q(q_object, self.used_aliases)
if clause:
self.where.add(clause, AND)
self.demote_joins(existing_inner)
def build_where(self, filter_expr):
return self.build_filter(filter_expr, allow_joins=False)[0]
def clear_where(self):
self.where = WhereNode()
def _add_q(
self,
q_object,
used_aliases,
branch_negated=False,
current_negated=False,
allow_joins=True,
split_subq=True,
check_filterable=True,
):
"""Add a Q-object to the current filter."""
connector = q_object.connector
current_negated = current_negated ^ q_object.negated
branch_negated = branch_negated or q_object.negated
target_clause = WhereNode(connector=connector, negated=q_object.negated)
joinpromoter = JoinPromoter(
q_object.connector, len(q_object.children), current_negated
)
for child in q_object.children:
child_clause, needed_inner = self.build_filter(
child,
can_reuse=used_aliases,
branch_negated=branch_negated,
current_negated=current_negated,
allow_joins=allow_joins,
split_subq=split_subq,
check_filterable=check_filterable,
)
joinpromoter.add_votes(needed_inner)
if child_clause:
target_clause.add(child_clause, connector)
needed_inner = joinpromoter.update_join_types(self)
return target_clause, needed_inner
def build_filtered_relation_q(
self, q_object, reuse, branch_negated=False, current_negated=False
):
"""Add a FilteredRelation object to the current filter."""
connector = q_object.connector
current_negated ^= q_object.negated
branch_negated = branch_negated or q_object.negated
target_clause = WhereNode(connector=connector, negated=q_object.negated)
for child in q_object.children:
if isinstance(child, Node):
child_clause = self.build_filtered_relation_q(
child,
reuse=reuse,
branch_negated=branch_negated,
current_negated=current_negated,
)
else:
child_clause, _ = self.build_filter(
child,
can_reuse=reuse,
branch_negated=branch_negated,
current_negated=current_negated,
allow_joins=True,
split_subq=False,
reuse_with_filtered_relation=True,
)
target_clause.add(child_clause, connector)
return target_clause
def add_filtered_relation(self, filtered_relation, alias):
filtered_relation.alias = alias
lookups = dict(get_children_from_q(filtered_relation.condition))
relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type(
filtered_relation.relation_name
)
if relation_lookup_parts:
raise ValueError(
"FilteredRelation's relation_name cannot contain lookups "
"(got %r)." % filtered_relation.relation_name
)
for lookup in chain(lookups):
lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup)
shift = 2 if not lookup_parts else 1
lookup_field_path = lookup_field_parts[:-shift]
for idx, lookup_field_part in enumerate(lookup_field_path):
if len(relation_field_parts) > idx:
if relation_field_parts[idx] != lookup_field_part:
raise ValueError(
"FilteredRelation's condition doesn't support "
"relations outside the %r (got %r)."
% (filtered_relation.relation_name, lookup)
)
else:
raise ValueError(
"FilteredRelation's condition doesn't support nested "
"relations deeper than the relation_name (got %r for "
"%r)." % (lookup, filtered_relation.relation_name)
)
self._filtered_relations[filtered_relation.alias] = filtered_relation
def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):
"""
Walk the list of names and turns them into PathInfo tuples. A single
name in 'names' can generate multiple PathInfos (m2m, for example).
'names' is the path of names to travel, 'opts' is the model Options we
start the name resolving from, 'allow_many' is as for setup_joins().
If fail_on_missing is set to True, then a name that can't be resolved
will generate a FieldError.
Return a list of PathInfo tuples. In addition return the final field
(the last used join field) and target (which is a field guaranteed to
contain the same value as the final field). Finally, return those names
that weren't found (which are likely transforms and the final lookup).
"""
path, names_with_path = [], []
for pos, name in enumerate(names):
cur_names_with_path = (name, [])
if name == "pk":
name = opts.pk.name
field = None
filtered_relation = None
try:
if opts is None:
raise FieldDoesNotExist
field = opts.get_field(name)
except FieldDoesNotExist:
if name in self.annotation_select:
field = self.annotation_select[name].output_field
elif name in self._filtered_relations and pos == 0:
filtered_relation = self._filtered_relations[name]
if LOOKUP_SEP in filtered_relation.relation_name:
parts = filtered_relation.relation_name.split(LOOKUP_SEP)
filtered_relation_path, field, _, _ = self.names_to_path(
parts,
opts,
allow_many,
fail_on_missing,
)
path.extend(filtered_relation_path[:-1])
else:
field = opts.get_field(filtered_relation.relation_name)
if field is not None:
# Fields that contain one-to-many relations with a generic
# model (like a GenericForeignKey) cannot generate reverse
# relations and therefore cannot be used for reverse querying.
if field.is_relation and not field.related_model:
raise FieldError(
"Field %r does not generate an automatic reverse "
"relation and therefore cannot be used for reverse "
"querying. If it is a GenericForeignKey, consider "
"adding a GenericRelation." % name
)
try:
model = field.model._meta.concrete_model
except AttributeError:
# QuerySet.annotate() may introduce fields that aren't
# attached to a model.
model = None
else:
# We didn't find the current field, so move position back
# one step.
pos -= 1
if pos == -1 or fail_on_missing:
available = sorted(
[
*get_field_names_from_opts(opts),
*self.annotation_select,
*self._filtered_relations,
]
)
raise FieldError(
"Cannot resolve keyword '%s' into field. "
"Choices are: %s" % (name, ", ".join(available))
)
break
# Check if we need any joins for concrete inheritance cases (the
# field lives in parent, but we are currently in one of its
# children)
if opts is not None and model is not opts.model:
path_to_parent = opts.get_path_to_parent(model)
if path_to_parent:
path.extend(path_to_parent)
cur_names_with_path[1].extend(path_to_parent)
opts = path_to_parent[-1].to_opts
if hasattr(field, "path_infos"):
if filtered_relation:
pathinfos = field.get_path_info(filtered_relation)
else:
pathinfos = field.path_infos
if not allow_many:
for inner_pos, p in enumerate(pathinfos):
if p.m2m:
cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1])
names_with_path.append(cur_names_with_path)
raise MultiJoin(pos + 1, names_with_path)
last = pathinfos[-1]
path.extend(pathinfos)
final_field = last.join_field
opts = last.to_opts
targets = last.target_fields
cur_names_with_path[1].extend(pathinfos)
names_with_path.append(cur_names_with_path)
else:
# Local non-relational field.
final_field = field
targets = (field,)
if fail_on_missing and pos + 1 != len(names):
raise FieldError(
"Cannot resolve keyword %r into field. Join on '%s'"
" not permitted." % (names[pos + 1], name)
)
break
return path, final_field, targets, names[pos + 1 :]
def setup_joins(
self,
names,
opts,
alias,
can_reuse=None,
allow_many=True,
reuse_with_filtered_relation=False,
):
"""
Compute the necessary table joins for the passage through the fields
given in 'names'. 'opts' is the Options class for the current model
(which gives the table we are starting from), 'alias' is the alias for
the table to start the joining from.
The 'can_reuse' defines the reverse foreign key joins we can reuse. It
can be None in which case all joins are reusable or a set of aliases
that can be reused. Note that non-reverse foreign keys are always
reusable when using setup_joins().
The 'reuse_with_filtered_relation' can be used to force 'can_reuse'
parameter and force the relation on the given connections.
If 'allow_many' is False, then any reverse foreign key seen will
generate a MultiJoin exception.
Return the final field involved in the joins, the target field (used
for any 'where' constraint), the final 'opts' value, the joins, the
field path traveled to generate the joins, and a transform function
that takes a field and alias and is equivalent to `field.get_col(alias)`
in the simple case but wraps field transforms if they were included in
names.
The target field is the field containing the concrete value. Final
field can be something different, for example foreign key pointing to
that value. Final field is needed for example in some value
conversions (convert 'obj' in fk__id=obj to pk val using the foreign
key field for example).
"""
joins = [alias]
# The transform can't be applied yet, as joins must be trimmed later.
# To avoid making every caller of this method look up transforms
# directly, compute transforms here and create a partial that converts
# fields to the appropriate wrapped version.
def final_transformer(field, alias):
if not self.alias_cols:
alias = None
return field.get_col(alias)
# Try resolving all the names as fields first. If there's an error,
# treat trailing names as lookups until a field can be resolved.
last_field_exception = None
for pivot in range(len(names), 0, -1):
try:
path, final_field, targets, rest = self.names_to_path(
names[:pivot],
opts,
allow_many,
fail_on_missing=True,
)
except FieldError as exc:
if pivot == 1:
# The first item cannot be a lookup, so it's safe
# to raise the field error here.
raise
else:
last_field_exception = exc
else:
# The transforms are the remaining items that couldn't be
# resolved into fields.
transforms = names[pivot:]
break
for name in transforms:
def transform(field, alias, *, name, previous):
try:
wrapped = previous(field, alias)
return self.try_transform(wrapped, name)
except FieldError:
# FieldError is raised if the transform doesn't exist.
if isinstance(final_field, Field) and last_field_exception:
raise last_field_exception
else:
raise
final_transformer = functools.partial(
transform, name=name, previous=final_transformer
)
# Then, add the path to the query's joins. Note that we can't trim
# joins at this stage - we will need the information about join type
# of the trimmed joins.
for join in path:
if join.filtered_relation:
filtered_relation = join.filtered_relation.clone()
table_alias = filtered_relation.alias
else:
filtered_relation = None
table_alias = None
opts = join.to_opts
if join.direct:
nullable = self.is_nullable(join.join_field)
else:
nullable = True
connection = self.join_class(
opts.db_table,
alias,
table_alias,
INNER,
join.join_field,
nullable,
filtered_relation=filtered_relation,
)
reuse = can_reuse if join.m2m or reuse_with_filtered_relation else None
alias = self.join(
connection,
reuse=reuse,
reuse_with_filtered_relation=reuse_with_filtered_relation,
)
joins.append(alias)
if filtered_relation:
filtered_relation.path = joins[:]
return JoinInfo(final_field, targets, opts, joins, path, final_transformer)
def trim_joins(self, targets, joins, path):
"""
The 'target' parameter is the final field being joined to, 'joins'
is the full list of join aliases. The 'path' contain the PathInfos
used to create the joins.
Return the final target field and table alias and the new active
joins.
Always trim any direct join if the target column is already in the
previous table. Can't trim reverse joins as it's unknown if there's
anything on the other side of the join.
"""
joins = joins[:]
for pos, info in enumerate(reversed(path)):
if len(joins) == 1 or not info.direct:
break
if info.filtered_relation:
break
join_targets = {t.column for t in info.join_field.foreign_related_fields}
cur_targets = {t.column for t in targets}
if not cur_targets.issubset(join_targets):
break
targets_dict = {
r[1].column: r[0]
for r in info.join_field.related_fields
if r[1].column in cur_targets
}
targets = tuple(targets_dict[t.column] for t in targets)
self.unref_alias(joins.pop())
return targets, joins[-1], joins
@classmethod
def _gen_cols(cls, exprs, include_external=False):
for expr in exprs:
if isinstance(expr, Col):
yield expr
elif include_external and callable(
getattr(expr, "get_external_cols", None)
):
yield from expr.get_external_cols()
elif hasattr(expr, "get_source_expressions"):
yield from cls._gen_cols(
expr.get_source_expressions(),
include_external=include_external,
)
@classmethod
def _gen_col_aliases(cls, exprs):
yield from (expr.alias for expr in cls._gen_cols(exprs))
def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False):
annotation = self.annotations.get(name)
if annotation is not None:
if not allow_joins:
for alias in self._gen_col_aliases([annotation]):
if isinstance(self.alias_map[alias], Join):
raise FieldError(
"Joined field references are not permitted in this query"
)
if summarize:
# Summarize currently means we are doing an aggregate() query
# which is executed as a wrapped subquery if any of the
# aggregate() elements reference an existing annotation. In
# that case we need to return a Ref to the subquery's annotation.
if name not in self.annotation_select:
raise FieldError(
"Cannot aggregate over the '%s' alias. Use annotate() "
"to promote it." % name
)
return Ref(name, self.annotation_select[name])
else:
return annotation
else:
field_list = name.split(LOOKUP_SEP)
annotation = self.annotations.get(field_list[0])
if annotation is not None:
for transform in field_list[1:]:
annotation = self.try_transform(annotation, transform)
return annotation
join_info = self.setup_joins(
field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse
)
targets, final_alias, join_list = self.trim_joins(
join_info.targets, join_info.joins, join_info.path
)
if not allow_joins and len(join_list) > 1:
raise FieldError(
"Joined field references are not permitted in this query"
)
if len(targets) > 1:
raise FieldError(
"Referencing multicolumn fields with F() objects isn't supported"
)
# Verify that the last lookup in name is a field or a transform:
# transform_function() raises FieldError if not.
transform = join_info.transform_function(targets[0], final_alias)
if reuse is not None:
reuse.update(join_list)
return transform
def split_exclude(self, filter_expr, can_reuse, names_with_path):
"""
When doing an exclude against any kind of N-to-many relation, we need
to use a subquery. This method constructs the nested query, given the
original exclude filter (filter_expr) and the portion up to the first
N-to-many relation field.
For example, if the origin filter is ~Q(child__name='foo'), filter_expr
is ('child__name', 'foo') and can_reuse is a set of joins usable for
filters in the original query.
We will turn this into equivalent of:
WHERE NOT EXISTS(
SELECT 1
FROM child
WHERE name = 'foo' AND child.parent_id = parent.id
LIMIT 1
)
"""
# Generate the inner query.
query = self.__class__(self.model)
query._filtered_relations = self._filtered_relations
filter_lhs, filter_rhs = filter_expr
if isinstance(filter_rhs, OuterRef):
filter_rhs = OuterRef(filter_rhs)
elif isinstance(filter_rhs, F):
filter_rhs = OuterRef(filter_rhs.name)
query.add_filter(filter_lhs, filter_rhs)
query.clear_ordering(force=True)
# Try to have as simple as possible subquery -> trim leading joins from
# the subquery.
trimmed_prefix, contains_louter = query.trim_start(names_with_path)
col = query.select[0]
select_field = col.target
alias = col.alias
if alias in can_reuse:
pk = select_field.model._meta.pk
# Need to add a restriction so that outer query's filters are in effect for
# the subquery, too.
query.bump_prefix(self)
lookup_class = select_field.get_lookup("exact")
# Note that the query.select[0].alias is different from alias
# due to bump_prefix above.
lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias))
query.where.add(lookup, AND)
query.external_aliases[alias] = True
lookup_class = select_field.get_lookup("exact")
lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix))
query.where.add(lookup, AND)
condition, needed_inner = self.build_filter(Exists(query))
if contains_louter:
or_null_condition, _ = self.build_filter(
("%s__isnull" % trimmed_prefix, True),
current_negated=True,
branch_negated=True,
can_reuse=can_reuse,
)
condition.add(or_null_condition, OR)
# Note that the end result will be:
# (outercol NOT IN innerq AND outercol IS NOT NULL) OR outercol IS NULL.
# This might look crazy but due to how IN works, this seems to be
# correct. If the IS NOT NULL check is removed then outercol NOT
# IN will return UNKNOWN. If the IS NULL check is removed, then if
# outercol IS NULL we will not match the row.
return condition, needed_inner
def set_empty(self):
self.where.add(NothingNode(), AND)
for query in self.combined_queries:
query.set_empty()
def is_empty(self):
return any(isinstance(c, NothingNode) for c in self.where.children)
def set_limits(self, low=None, high=None):
"""
Adjust the limits on the rows retrieved. Use low/high to set these,
as it makes it more Pythonic to read and write. When the SQL query is
created, convert them to the appropriate offset and limit values.
Apply any limits passed in here to the existing constraints. Add low
to the current low value and clamp both to any existing high value.
"""
if high is not None:
if self.high_mark is not None:
self.high_mark = min(self.high_mark, self.low_mark + high)
else:
self.high_mark = self.low_mark + high
if low is not None:
if self.high_mark is not None:
self.low_mark = min(self.high_mark, self.low_mark + low)
else:
self.low_mark = self.low_mark + low
if self.low_mark == self.high_mark:
self.set_empty()
def clear_limits(self):
"""Clear any existing limits."""
self.low_mark, self.high_mark = 0, None
@property
def is_sliced(self):
return self.low_mark != 0 or self.high_mark is not None
def has_limit_one(self):
return self.high_mark is not None and (self.high_mark - self.low_mark) == 1
def can_filter(self):
"""
Return True if adding filters to this instance is still possible.
Typically, this means no limits or offsets have been put on the results.
"""
return not self.is_sliced
def clear_select_clause(self):
"""Remove all fields from SELECT clause."""
self.select = ()
self.default_cols = False
self.select_related = False
self.set_extra_mask(())
self.set_annotation_mask(())
def clear_select_fields(self):
"""
Clear the list of fields to select (but not extra_select columns).
Some queryset types completely replace any existing list of select
columns.
"""
self.select = ()
self.values_select = ()
def add_select_col(self, col, name):
self.select += (col,)
self.values_select += (name,)
def set_select(self, cols):
self.default_cols = False
self.select = tuple(cols)
def add_distinct_fields(self, *field_names):
"""
Add and resolve the given fields to the query's "distinct on" clause.
"""
self.distinct_fields = field_names
self.distinct = True
def add_fields(self, field_names, allow_m2m=True):
"""
Add the given (model) fields to the select set. Add the field names in
the order specified.
"""
alias = self.get_initial_alias()
opts = self.get_meta()
try:
cols = []
for name in field_names:
# Join promotion note - we must not remove any rows here, so
# if there is no existing joins, use outer join.
join_info = self.setup_joins(
name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m
)
targets, final_alias, joins = self.trim_joins(
join_info.targets,
join_info.joins,
join_info.path,
)
for target in targets:
cols.append(join_info.transform_function(target, final_alias))
if cols:
self.set_select(cols)
except MultiJoin:
raise FieldError("Invalid field name: '%s'" % name)
except FieldError:
if LOOKUP_SEP in name:
# For lookups spanning over relationships, show the error
# from the model on which the lookup failed.
raise
elif name in self.annotations:
raise FieldError(
"Cannot select the '%s' alias. Use annotate() to promote "
"it." % name
)
else:
names = sorted(
[
*get_field_names_from_opts(opts),
*self.extra,
*self.annotation_select,
*self._filtered_relations,
]
)
raise FieldError(
"Cannot resolve keyword %r into field. "
"Choices are: %s" % (name, ", ".join(names))
)
def add_ordering(self, *ordering):
"""
Add items from the 'ordering' sequence to the query's "order by"
clause. These items are either field names (not column names) --
possibly with a direction prefix ('-' or '?') -- or OrderBy
expressions.
If 'ordering' is empty, clear all ordering from the query.
"""
errors = []
for item in ordering:
if isinstance(item, str):
if item == "?":
continue
if item.startswith("-"):
item = item[1:]
if item in self.annotations:
continue
if self.extra and item in self.extra:
continue
# names_to_path() validates the lookup. A descriptive
# FieldError will be raise if it's not.
self.names_to_path(item.split(LOOKUP_SEP), self.model._meta)
elif not hasattr(item, "resolve_expression"):
errors.append(item)
if getattr(item, "contains_aggregate", False):
raise FieldError(
"Using an aggregate in order_by() without also including "
"it in annotate() is not allowed: %s" % item
)
if errors:
raise FieldError("Invalid order_by arguments: %s" % errors)
if ordering:
self.order_by += ordering
else:
self.default_ordering = False
def clear_ordering(self, force=False, clear_default=True):
"""
Remove any ordering settings if the current query allows it without
side effects, set 'force' to True to clear the ordering regardless.
If 'clear_default' is True, there will be no ordering in the resulting
query (not even the model's default).
"""
if not force and (
self.is_sliced or self.distinct_fields or self.select_for_update
):
return
self.order_by = ()
self.extra_order_by = ()
if clear_default:
self.default_ordering = False
def set_group_by(self, allow_aliases=True):
"""
Expand the GROUP BY clause required by the query.
This will usually be the set of all non-aggregate fields in the
return data. If the database backend supports grouping by the
primary key, and the query would be equivalent, the optimization
will be made automatically.
"""
# Column names from JOINs to check collisions with aliases.
if allow_aliases:
column_names = set()
seen_models = set()
for join in list(self.alias_map.values())[1:]: # Skip base table.
model = join.join_field.related_model
if model not in seen_models:
column_names.update(
{field.column for field in model._meta.local_concrete_fields}
)
seen_models.add(model)
group_by = list(self.select)
if self.annotation_select:
for alias, annotation in self.annotation_select.items():
if not allow_aliases or alias in column_names:
alias = None
group_by_cols = annotation.get_group_by_cols(alias=alias)
group_by.extend(group_by_cols)
self.group_by = tuple(group_by)
def add_select_related(self, fields):
"""
Set up the select_related data structure so that we only select
certain related models (as opposed to all models, when
self.select_related=True).
"""
if isinstance(self.select_related, bool):
field_dict = {}
else:
field_dict = self.select_related
for field in fields:
d = field_dict
for part in field.split(LOOKUP_SEP):
d = d.setdefault(part, {})
self.select_related = field_dict
def add_extra(self, select, select_params, where, params, tables, order_by):
"""
Add data to the various extra_* attributes for user-created additions
to the query.
"""
if select:
# We need to pair any placeholder markers in the 'select'
# dictionary with their parameters in 'select_params' so that
# subsequent updates to the select dictionary also adjust the
# parameters appropriately.
select_pairs = {}
if select_params:
param_iter = iter(select_params)
else:
param_iter = iter([])
for name, entry in select.items():
self.check_alias(name)
entry = str(entry)
entry_params = []
pos = entry.find("%s")
while pos != -1:
if pos == 0 or entry[pos - 1] != "%":
entry_params.append(next(param_iter))
pos = entry.find("%s", pos + 2)
select_pairs[name] = (entry, entry_params)
self.extra.update(select_pairs)
if where or params:
self.where.add(ExtraWhere(where, params), AND)
if tables:
self.extra_tables += tuple(tables)
if order_by:
self.extra_order_by = order_by
def clear_deferred_loading(self):
"""Remove any fields from the deferred loading set."""
self.deferred_loading = (frozenset(), True)
def add_deferred_loading(self, field_names):
"""
Add the given list of model field names to the set of fields to
exclude from loading from the database when automatic column selection
is done. Add the new field names to any existing field names that
are deferred (or removed from any existing field names that are marked
as the only ones for immediate loading).
"""
# Fields on related models are stored in the literal double-underscore
# format, so that we can use a set datastructure. We do the foo__bar
# splitting and handling when computing the SQL column names (as part of
# get_columns()).
existing, defer = self.deferred_loading
if defer:
# Add to existing deferred names.
self.deferred_loading = existing.union(field_names), True
else:
# Remove names from the set of any existing "immediate load" names.
if new_existing := existing.difference(field_names):
self.deferred_loading = new_existing, False
else:
self.clear_deferred_loading()
if new_only := set(field_names).difference(existing):
self.deferred_loading = new_only, True
def add_immediate_loading(self, field_names):
"""
Add the given list of model field names to the set of fields to
retrieve when the SQL is executed ("immediate loading" fields). The
field names replace any existing immediate loading field names. If
there are field names already specified for deferred loading, remove
those names from the new field_names before storing the new names
for immediate loading. (That is, immediate loading overrides any
existing immediate values, but respects existing deferrals.)
"""
existing, defer = self.deferred_loading
field_names = set(field_names)
if "pk" in field_names:
field_names.remove("pk")
field_names.add(self.get_meta().pk.name)
if defer:
# Remove any existing deferred names from the current set before
# setting the new names.
self.deferred_loading = field_names.difference(existing), False
else:
# Replace any existing "immediate load" field names.
self.deferred_loading = frozenset(field_names), False
def set_annotation_mask(self, names):
"""Set the mask of annotations that will be returned by the SELECT."""
if names is None:
self.annotation_select_mask = None
else:
self.annotation_select_mask = set(names)
self._annotation_select_cache = None
def append_annotation_mask(self, names):
if self.annotation_select_mask is not None:
self.set_annotation_mask(self.annotation_select_mask.union(names))
def set_extra_mask(self, names):
"""
Set the mask of extra select items that will be returned by SELECT.
Don't remove them from the Query since they might be used later.
"""
if names is None:
self.extra_select_mask = None
else:
self.extra_select_mask = set(names)
self._extra_select_cache = None
def set_values(self, fields):
self.select_related = False
self.clear_deferred_loading()
self.clear_select_fields()
if fields:
field_names = []
extra_names = []
annotation_names = []
if not self.extra and not self.annotations:
# Shortcut - if there are no extra or annotations, then
# the values() clause must be just field names.
field_names = list(fields)
else:
self.default_cols = False
for f in fields:
if f in self.extra_select:
extra_names.append(f)
elif f in self.annotation_select:
annotation_names.append(f)
else:
field_names.append(f)
self.set_extra_mask(extra_names)
self.set_annotation_mask(annotation_names)
selected = frozenset(field_names + extra_names + annotation_names)
else:
field_names = [f.attname for f in self.model._meta.concrete_fields]
selected = frozenset(field_names)
# Selected annotations must be known before setting the GROUP BY
# clause.
if self.group_by is True:
self.add_fields(
(f.attname for f in self.model._meta.concrete_fields), False
)
# Disable GROUP BY aliases to avoid orphaning references to the
# SELECT clause which is about to be cleared.
self.set_group_by(allow_aliases=False)
self.clear_select_fields()
elif self.group_by:
# Resolve GROUP BY annotation references if they are not part of
# the selected fields anymore.
group_by = []
for expr in self.group_by:
if isinstance(expr, Ref) and expr.refs not in selected:
expr = self.annotations[expr.refs]
group_by.append(expr)
self.group_by = tuple(group_by)
self.values_select = tuple(field_names)
self.add_fields(field_names, True)
@property
def annotation_select(self):
"""
Return the dictionary of aggregate columns that are not masked and
should be used in the SELECT clause. Cache this result for performance.
"""
if self._annotation_select_cache is not None:
return self._annotation_select_cache
elif not self.annotations:
return {}
elif self.annotation_select_mask is not None:
self._annotation_select_cache = {
k: v
for k, v in self.annotations.items()
if k in self.annotation_select_mask
}
return self._annotation_select_cache
else:
return self.annotations
@property
def extra_select(self):
if self._extra_select_cache is not None:
return self._extra_select_cache
if not self.extra:
return {}
elif self.extra_select_mask is not None:
self._extra_select_cache = {
k: v for k, v in self.extra.items() if k in self.extra_select_mask
}
return self._extra_select_cache
else:
return self.extra
def trim_start(self, names_with_path):
"""
Trim joins from the start of the join path. The candidates for trim
are the PathInfos in names_with_path structure that are m2m joins.
Also set the select column so the start matches the join.
This method is meant to be used for generating the subquery joins &
cols in split_exclude().
Return a lookup usable for doing outerq.filter(lookup=self) and a
boolean indicating if the joins in the prefix contain a LEFT OUTER join.
_"""
all_paths = []
for _, paths in names_with_path:
all_paths.extend(paths)
contains_louter = False
# Trim and operate only on tables that were generated for
# the lookup part of the query. That is, avoid trimming
# joins generated for F() expressions.
lookup_tables = [
t for t in self.alias_map if t in self._lookup_joins or t == self.base_table
]
for trimmed_paths, path in enumerate(all_paths):
if path.m2m:
break
if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER:
contains_louter = True
alias = lookup_tables[trimmed_paths]
self.unref_alias(alias)
# The path.join_field is a Rel, lets get the other side's field
join_field = path.join_field.field
# Build the filter prefix.
paths_in_prefix = trimmed_paths
trimmed_prefix = []
for name, path in names_with_path:
if paths_in_prefix - len(path) < 0:
break
trimmed_prefix.append(name)
paths_in_prefix -= len(path)
trimmed_prefix.append(join_field.foreign_related_fields[0].name)
trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)
# Lets still see if we can trim the first join from the inner query
# (that is, self). We can't do this for:
# - LEFT JOINs because we would miss those rows that have nothing on
# the outer side,
# - INNER JOINs from filtered relations because we would miss their
# filters.
first_join = self.alias_map[lookup_tables[trimmed_paths + 1]]
if first_join.join_type != LOUTER and not first_join.filtered_relation:
select_fields = [r[0] for r in join_field.related_fields]
select_alias = lookup_tables[trimmed_paths + 1]
self.unref_alias(lookup_tables[trimmed_paths])
extra_restriction = join_field.get_extra_restriction(
None, lookup_tables[trimmed_paths + 1]
)
if extra_restriction:
self.where.add(extra_restriction, AND)
else:
# TODO: It might be possible to trim more joins from the start of the
# inner query if it happens to have a longer join chain containing the
# values in select_fields. Lets punt this one for now.
select_fields = [r[1] for r in join_field.related_fields]
select_alias = lookup_tables[trimmed_paths]
# The found starting point is likely a join_class instead of a
# base_table_class reference. But the first entry in the query's FROM
# clause must not be a JOIN.
for table in self.alias_map:
if self.alias_refcount[table] > 0:
self.alias_map[table] = self.base_table_class(
self.alias_map[table].table_name,
table,
)
break
self.set_select([f.get_col(select_alias) for f in select_fields])
return trimmed_prefix, contains_louter
def is_nullable(self, field):
"""
Check if the given field should be treated as nullable.
Some backends treat '' as null and Django treats such fields as
nullable for those backends. In such situations field.null can be
False even if we should treat the field as nullable.
"""
# We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have
# (nor should it have) knowledge of which connection is going to be
# used. The proper fix would be to defer all decisions where
# is_nullable() is needed to the compiler stage, but that is not easy
# to do currently.
return field.null or (
field.empty_strings_allowed
and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls
)
def get_order_dir(field, default="ASC"):
"""
Return the field name and direction for an order specification. For
example, '-foo' is returned as ('foo', 'DESC').
The 'default' param is used to indicate which way no prefix (or a '+'
prefix) should sort. The '-' prefix always sorts the opposite way.
"""
dirn = ORDER_DIR[default]
if field[0] == "-":
return field[1:], dirn[1]
return field, dirn[0]
def add_to_dict(data, key, value):
"""
Add "value" to the set of values for "key", whether or not "key" already
exists.
"""
if key in data:
data[key].add(value)
else:
data[key] = {value}
def is_reverse_o2o(field):
"""
Check if the given field is reverse-o2o. The field is expected to be some
sort of relation field or related object.
"""
return field.is_relation and field.one_to_one and not field.concrete
class JoinPromoter:
"""
A class to abstract away join promotion problems for complex filter
conditions.
"""
def __init__(self, connector, num_children, negated):
self.connector = connector
self.negated = negated
if self.negated:
if connector == AND:
self.effective_connector = OR
else:
self.effective_connector = AND
else:
self.effective_connector = self.connector
self.num_children = num_children
# Maps of table alias to how many times it is seen as required for
# inner and/or outer joins.
self.votes = Counter()
def __repr__(self):
return (
f"{self.__class__.__qualname__}(connector={self.connector!r}, "
f"num_children={self.num_children!r}, negated={self.negated!r})"
)
def add_votes(self, votes):
"""
Add single vote per item to self.votes. Parameter can be any
iterable.
"""
self.votes.update(votes)
def update_join_types(self, query):
"""
Change join types so that the generated query is as efficient as
possible, but still correct. So, change as many joins as possible
to INNER, but don't make OUTER joins INNER if that could remove
results from the query.
"""
to_promote = set()
to_demote = set()
# The effective_connector is used so that NOT (a AND b) is treated
# similarly to (a OR b) for join promotion.
for table, votes in self.votes.items():
# We must use outer joins in OR case when the join isn't contained
# in all of the joins. Otherwise the INNER JOIN itself could remove
# valid results. Consider the case where a model with rel_a and
# rel_b relations is queried with rel_a__col=1 | rel_b__col=2. Now,
# if rel_a join doesn't produce any results is null (for example
# reverse foreign key or null value in direct foreign key), and
# there is a matching row in rel_b with col=2, then an INNER join
# to rel_a would remove a valid match from the query. So, we need
# to promote any existing INNER to LOUTER (it is possible this
# promotion in turn will be demoted later on).
if self.effective_connector == OR and votes < self.num_children:
to_promote.add(table)
# If connector is AND and there is a filter that can match only
# when there is a joinable row, then use INNER. For example, in
# rel_a__col=1 & rel_b__col=2, if either of the rels produce NULL
# as join output, then the col=1 or col=2 can't match (as
# NULL=anything is always false).
# For the OR case, if all children voted for a join to be inner,
# then we can use INNER for the join. For example:
# (rel_a__col__icontains=Alex | rel_a__col__icontains=Russell)
# then if rel_a doesn't produce any rows, the whole condition
# can't match. Hence we can safely use INNER join.
if self.effective_connector == AND or (
self.effective_connector == OR and votes == self.num_children
):
to_demote.add(table)
# Finally, what happens in cases where we have:
# (rel_a__col=1|rel_b__col=2) & rel_a__col__gte=0
# Now, we first generate the OR clause, and promote joins for it
# in the first if branch above. Both rel_a and rel_b are promoted
# to LOUTER joins. After that we do the AND case. The OR case
# voted no inner joins but the rel_a__col__gte=0 votes inner join
# for rel_a. We demote it back to INNER join (in AND case a single
# vote is enough). The demotion is OK, if rel_a doesn't produce
# rows, then the rel_a__col__gte=0 clause can't be true, and thus
# the whole clause must be false. So, it is safe to use INNER
# join.
# Note that in this example we could just as well have the __gte
# clause and the OR clause swapped. Or we could replace the __gte
# clause with an OR clause containing rel_a__col=1|rel_a__col=2,
# and again we could safely demote to INNER.
query.promote_joins(to_promote)
query.demote_joins(to_demote)
return to_demote
|
2a98b1b9a56cd1b98f738b8395c235071205b434c95da039d1075aaa254aa9f6 | import collections
import json
import re
from functools import partial
from itertools import chain
from django.core.exceptions import EmptyResultSet, FieldError
from django.db import DatabaseError, NotSupportedError
from django.db.models.constants import LOOKUP_SEP
from django.db.models.expressions import F, OrderBy, RawSQL, Ref, Value
from django.db.models.functions import Cast, Random
from django.db.models.query_utils import select_related_descend
from django.db.models.sql.constants import (
CURSOR,
GET_ITERATOR_CHUNK_SIZE,
MULTI,
NO_RESULTS,
ORDER_DIR,
SINGLE,
)
from django.db.models.sql.query import Query, get_order_dir
from django.db.models.sql.where import AND
from django.db.transaction import TransactionManagementError
from django.utils.functional import cached_property
from django.utils.hashable import make_hashable
from django.utils.regex_helper import _lazy_re_compile
class SQLCompiler:
# Multiline ordering SQL clause may appear from RawSQL.
ordering_parts = _lazy_re_compile(
r"^(.*)\s(?:ASC|DESC).*",
re.MULTILINE | re.DOTALL,
)
def __init__(self, query, connection, using, elide_empty=True):
self.query = query
self.connection = connection
self.using = using
# Some queries, e.g. coalesced aggregation, need to be executed even if
# they would return an empty result set.
self.elide_empty = elide_empty
self.quote_cache = {"*": "*"}
# The select, klass_info, and annotations are needed by QuerySet.iterator()
# these are set as a side-effect of executing the query. Note that we calculate
# separately a list of extra select columns needed for grammatical correctness
# of the query, but these columns are not included in self.select.
self.select = None
self.annotation_col_map = None
self.klass_info = None
self._meta_ordering = None
def __repr__(self):
return (
f"<{self.__class__.__qualname__} "
f"model={self.query.model.__qualname__} "
f"connection={self.connection!r} using={self.using!r}>"
)
def setup_query(self):
if all(self.query.alias_refcount[a] == 0 for a in self.query.alias_map):
self.query.get_initial_alias()
self.select, self.klass_info, self.annotation_col_map = self.get_select()
self.col_count = len(self.select)
def pre_sql_setup(self):
"""
Do any necessary class setup immediately prior to producing SQL. This
is for things that can't necessarily be done in __init__ because we
might not have all the pieces in place at that time.
"""
self.setup_query()
order_by = self.get_order_by()
self.where, self.having = self.query.where.split_having()
extra_select = self.get_extra_select(order_by, self.select)
self.has_extra_select = bool(extra_select)
group_by = self.get_group_by(self.select + extra_select, order_by)
return extra_select, order_by, group_by
def get_group_by(self, select, order_by):
"""
Return a list of 2-tuples of form (sql, params).
The logic of what exactly the GROUP BY clause contains is hard
to describe in other words than "if it passes the test suite,
then it is correct".
"""
# Some examples:
# SomeModel.objects.annotate(Count('somecol'))
# GROUP BY: all fields of the model
#
# SomeModel.objects.values('name').annotate(Count('somecol'))
# GROUP BY: name
#
# SomeModel.objects.annotate(Count('somecol')).values('name')
# GROUP BY: all cols of the model
#
# SomeModel.objects.values('name', 'pk')
# .annotate(Count('somecol')).values('pk')
# GROUP BY: name, pk
#
# SomeModel.objects.values('name').annotate(Count('somecol')).values('pk')
# GROUP BY: name, pk
#
# In fact, the self.query.group_by is the minimal set to GROUP BY. It
# can't be ever restricted to a smaller set, but additional columns in
# HAVING, ORDER BY, and SELECT clauses are added to it. Unfortunately
# the end result is that it is impossible to force the query to have
# a chosen GROUP BY clause - you can almost do this by using the form:
# .values(*wanted_cols).annotate(AnAggregate())
# but any later annotations, extra selects, values calls that
# refer some column outside of the wanted_cols, order_by, or even
# filter calls can alter the GROUP BY clause.
# The query.group_by is either None (no GROUP BY at all), True
# (group by select fields), or a list of expressions to be added
# to the group by.
if self.query.group_by is None:
return []
expressions = []
if self.query.group_by is not True:
# If the group by is set to a list (by .values() call most likely),
# then we need to add everything in it to the GROUP BY clause.
# Backwards compatibility hack for setting query.group_by. Remove
# when we have public API way of forcing the GROUP BY clause.
# Converts string references to expressions.
for expr in self.query.group_by:
if not hasattr(expr, "as_sql"):
expressions.append(self.query.resolve_ref(expr))
else:
expressions.append(expr)
# Note that even if the group_by is set, it is only the minimal
# set to group by. So, we need to add cols in select, order_by, and
# having into the select in any case.
ref_sources = {expr.source for expr in expressions if isinstance(expr, Ref)}
for expr, _, _ in select:
# Skip members of the select clause that are already included
# by reference.
if expr in ref_sources:
continue
cols = expr.get_group_by_cols()
for col in cols:
expressions.append(col)
if not self._meta_ordering:
for expr, (sql, params, is_ref) in order_by:
# Skip references to the SELECT clause, as all expressions in
# the SELECT clause are already part of the GROUP BY.
if not is_ref:
expressions.extend(expr.get_group_by_cols())
having_group_by = self.having.get_group_by_cols() if self.having else ()
for expr in having_group_by:
expressions.append(expr)
result = []
seen = set()
expressions = self.collapse_group_by(expressions, having_group_by)
for expr in expressions:
sql, params = self.compile(expr)
sql, params = expr.select_format(self, sql, params)
params_hash = make_hashable(params)
if (sql, params_hash) not in seen:
result.append((sql, params))
seen.add((sql, params_hash))
return result
def collapse_group_by(self, expressions, having):
# If the DB can group by primary key, then group by the primary key of
# query's main model. Note that for PostgreSQL the GROUP BY clause must
# include the primary key of every table, but for MySQL it is enough to
# have the main table's primary key.
if self.connection.features.allows_group_by_pk:
# Determine if the main model's primary key is in the query.
pk = None
for expr in expressions:
# Is this a reference to query's base table primary key? If the
# expression isn't a Col-like, then skip the expression.
if (
getattr(expr, "target", None) == self.query.model._meta.pk
and getattr(expr, "alias", None) == self.query.base_table
):
pk = expr
break
# If the main model's primary key is in the query, group by that
# field, HAVING expressions, and expressions associated with tables
# that don't have a primary key included in the grouped columns.
if pk:
pk_aliases = {
expr.alias
for expr in expressions
if hasattr(expr, "target") and expr.target.primary_key
}
expressions = [pk] + [
expr
for expr in expressions
if expr in having
or (
getattr(expr, "alias", None) is not None
and expr.alias not in pk_aliases
)
]
elif self.connection.features.allows_group_by_selected_pks:
# Filter out all expressions associated with a table's primary key
# present in the grouped columns. This is done by identifying all
# tables that have their primary key included in the grouped
# columns and removing non-primary key columns referring to them.
# Unmanaged models are excluded because they could be representing
# database views on which the optimization might not be allowed.
pks = {
expr
for expr in expressions
if (
hasattr(expr, "target")
and expr.target.primary_key
and self.connection.features.allows_group_by_selected_pks_on_model(
expr.target.model
)
)
}
aliases = {expr.alias for expr in pks}
expressions = [
expr
for expr in expressions
if expr in pks or getattr(expr, "alias", None) not in aliases
]
return expressions
def get_select(self):
"""
Return three values:
- a list of 3-tuples of (expression, (sql, params), alias)
- a klass_info structure,
- a dictionary of annotations
The (sql, params) is what the expression will produce, and alias is the
"AS alias" for the column (possibly None).
The klass_info structure contains the following information:
- The base model of the query.
- Which columns for that model are present in the query (by
position of the select clause).
- related_klass_infos: [f, klass_info] to descent into
The annotations is a dictionary of {'attname': column position} values.
"""
select = []
klass_info = None
annotations = {}
select_idx = 0
for alias, (sql, params) in self.query.extra_select.items():
annotations[alias] = select_idx
select.append((RawSQL(sql, params), alias))
select_idx += 1
assert not (self.query.select and self.query.default_cols)
if self.query.default_cols:
cols = self.get_default_columns()
else:
# self.query.select is a special case. These columns never go to
# any model.
cols = self.query.select
if cols:
select_list = []
for col in cols:
select_list.append(select_idx)
select.append((col, None))
select_idx += 1
klass_info = {
"model": self.query.model,
"select_fields": select_list,
}
for alias, annotation in self.query.annotation_select.items():
annotations[alias] = select_idx
select.append((annotation, alias))
select_idx += 1
if self.query.select_related:
related_klass_infos = self.get_related_selections(select)
klass_info["related_klass_infos"] = related_klass_infos
def get_select_from_parent(klass_info):
for ki in klass_info["related_klass_infos"]:
if ki["from_parent"]:
ki["select_fields"] = (
klass_info["select_fields"] + ki["select_fields"]
)
get_select_from_parent(ki)
get_select_from_parent(klass_info)
ret = []
for col, alias in select:
try:
sql, params = self.compile(col)
except EmptyResultSet:
empty_result_set_value = getattr(
col, "empty_result_set_value", NotImplemented
)
if empty_result_set_value is NotImplemented:
# Select a predicate that's always False.
sql, params = "0", ()
else:
sql, params = self.compile(Value(empty_result_set_value))
else:
sql, params = col.select_format(self, sql, params)
ret.append((col, (sql, params), alias))
return ret, klass_info, annotations
def _order_by_pairs(self):
if self.query.extra_order_by:
ordering = self.query.extra_order_by
elif not self.query.default_ordering:
ordering = self.query.order_by
elif self.query.order_by:
ordering = self.query.order_by
elif (meta := self.query.get_meta()) and meta.ordering:
ordering = meta.ordering
self._meta_ordering = ordering
else:
ordering = []
if self.query.standard_ordering:
default_order, _ = ORDER_DIR["ASC"]
else:
default_order, _ = ORDER_DIR["DESC"]
for field in ordering:
if hasattr(field, "resolve_expression"):
if isinstance(field, Value):
# output_field must be resolved for constants.
field = Cast(field, field.output_field)
if not isinstance(field, OrderBy):
field = field.asc()
if not self.query.standard_ordering:
field = field.copy()
field.reverse_ordering()
yield field, False
continue
if field == "?": # random
yield OrderBy(Random()), False
continue
col, order = get_order_dir(field, default_order)
descending = order == "DESC"
if col in self.query.annotation_select:
# Reference to expression in SELECT clause
yield (
OrderBy(
Ref(col, self.query.annotation_select[col]),
descending=descending,
),
True,
)
continue
if col in self.query.annotations:
# References to an expression which is masked out of the SELECT
# clause.
if self.query.combinator and self.select:
# Don't use the resolved annotation because other
# combinated queries might define it differently.
expr = F(col)
else:
expr = self.query.annotations[col]
if isinstance(expr, Value):
# output_field must be resolved for constants.
expr = Cast(expr, expr.output_field)
yield OrderBy(expr, descending=descending), False
continue
if "." in field:
# This came in through an extra(order_by=...) addition. Pass it
# on verbatim.
table, col = col.split(".", 1)
yield (
OrderBy(
RawSQL(
"%s.%s" % (self.quote_name_unless_alias(table), col), []
),
descending=descending,
),
False,
)
continue
if self.query.extra and col in self.query.extra:
if col in self.query.extra_select:
yield (
OrderBy(
Ref(col, RawSQL(*self.query.extra[col])),
descending=descending,
),
True,
)
else:
yield (
OrderBy(RawSQL(*self.query.extra[col]), descending=descending),
False,
)
else:
if self.query.combinator and self.select:
# Don't use the first model's field because other
# combinated queries might define it differently.
yield OrderBy(F(col), descending=descending), False
else:
# 'col' is of the form 'field' or 'field1__field2' or
# '-field1__field2__field', etc.
yield from self.find_ordering_name(
field,
self.query.get_meta(),
default_order=default_order,
)
def get_order_by(self):
"""
Return a list of 2-tuples of the form (expr, (sql, params, is_ref)) for
the ORDER BY clause.
The order_by clause can alter the select clause (for example it can add
aliases to clauses that do not yet have one, or it can add totally new
select clauses).
"""
result = []
seen = set()
for expr, is_ref in self._order_by_pairs():
resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None)
if self.query.combinator and self.select:
src = resolved.get_source_expressions()[0]
expr_src = expr.get_source_expressions()[0]
# Relabel order by columns to raw numbers if this is a combined
# query; necessary since the columns can't be referenced by the
# fully qualified name and the simple column names may collide.
for idx, (sel_expr, _, col_alias) in enumerate(self.select):
if is_ref and col_alias == src.refs:
src = src.source
elif col_alias and not (
isinstance(expr_src, F) and col_alias == expr_src.name
):
continue
if src == sel_expr:
resolved.set_source_expressions([RawSQL("%d" % (idx + 1), ())])
break
else:
if col_alias:
raise DatabaseError(
"ORDER BY term does not match any column in the result set."
)
# Add column used in ORDER BY clause to the selected
# columns and to each combined query.
order_by_idx = len(self.query.select) + 1
col_name = f"__orderbycol{order_by_idx}"
for q in self.query.combined_queries:
q.add_annotation(expr_src, col_name)
self.query.add_select_col(resolved, col_name)
resolved.set_source_expressions([RawSQL(f"{order_by_idx}", ())])
sql, params = self.compile(resolved)
# Don't add the same column twice, but the order direction is
# not taken into account so we strip it. When this entire method
# is refactored into expressions, then we can check each part as we
# generate it.
without_ordering = self.ordering_parts.search(sql)[1]
params_hash = make_hashable(params)
if (without_ordering, params_hash) in seen:
continue
seen.add((without_ordering, params_hash))
result.append((resolved, (sql, params, is_ref)))
return result
def get_extra_select(self, order_by, select):
extra_select = []
if self.query.distinct and not self.query.distinct_fields:
select_sql = [t[1] for t in select]
for expr, (sql, params, is_ref) in order_by:
without_ordering = self.ordering_parts.search(sql)[1]
if not is_ref and (without_ordering, params) not in select_sql:
extra_select.append((expr, (without_ordering, params), None))
return extra_select
def quote_name_unless_alias(self, name):
"""
A wrapper around connection.ops.quote_name that doesn't quote aliases
for table names. This avoids problems with some SQL dialects that treat
quoted strings specially (e.g. PostgreSQL).
"""
if name in self.quote_cache:
return self.quote_cache[name]
if (
(name in self.query.alias_map and name not in self.query.table_map)
or name in self.query.extra_select
or (
self.query.external_aliases.get(name)
and name not in self.query.table_map
)
):
self.quote_cache[name] = name
return name
r = self.connection.ops.quote_name(name)
self.quote_cache[name] = r
return r
def compile(self, node):
vendor_impl = getattr(node, "as_" + self.connection.vendor, None)
if vendor_impl:
sql, params = vendor_impl(self, self.connection)
else:
sql, params = node.as_sql(self, self.connection)
return sql, params
def get_combinator_sql(self, combinator, all):
features = self.connection.features
compilers = [
query.get_compiler(self.using, self.connection, self.elide_empty)
for query in self.query.combined_queries
if not query.is_empty()
]
if not features.supports_slicing_ordering_in_compound:
for query, compiler in zip(self.query.combined_queries, compilers):
if query.low_mark or query.high_mark:
raise DatabaseError(
"LIMIT/OFFSET not allowed in subqueries of compound statements."
)
if compiler.get_order_by():
raise DatabaseError(
"ORDER BY not allowed in subqueries of compound statements."
)
parts = ()
for compiler in compilers:
try:
# If the columns list is limited, then all combined queries
# must have the same columns list. Set the selects defined on
# the query on all combined queries, if not already set.
if not compiler.query.values_select and self.query.values_select:
compiler.query = compiler.query.clone()
compiler.query.set_values(
(
*self.query.extra_select,
*self.query.values_select,
*self.query.annotation_select,
)
)
part_sql, part_args = compiler.as_sql()
if compiler.query.combinator:
# Wrap in a subquery if wrapping in parentheses isn't
# supported.
if not features.supports_parentheses_in_compound:
part_sql = "SELECT * FROM ({})".format(part_sql)
# Add parentheses when combining with compound query if not
# already added for all compound queries.
elif (
self.query.subquery
or not features.supports_slicing_ordering_in_compound
):
part_sql = "({})".format(part_sql)
elif (
self.query.subquery
and features.supports_slicing_ordering_in_compound
):
part_sql = "({})".format(part_sql)
parts += ((part_sql, part_args),)
except EmptyResultSet:
# Omit the empty queryset with UNION and with DIFFERENCE if the
# first queryset is nonempty.
if combinator == "union" or (combinator == "difference" and parts):
continue
raise
if not parts:
raise EmptyResultSet
combinator_sql = self.connection.ops.set_operators[combinator]
if all and combinator == "union":
combinator_sql += " ALL"
braces = "{}"
if not self.query.subquery and features.supports_slicing_ordering_in_compound:
braces = "({})"
sql_parts, args_parts = zip(
*((braces.format(sql), args) for sql, args in parts)
)
result = [" {} ".format(combinator_sql).join(sql_parts)]
params = []
for part in args_parts:
params.extend(part)
return result, params
def as_sql(self, with_limits=True, with_col_aliases=False):
"""
Create the SQL for this query. Return the SQL string and list of
parameters.
If 'with_limits' is False, any limit/offset information is not included
in the query.
"""
refcounts_before = self.query.alias_refcount.copy()
try:
extra_select, order_by, group_by = self.pre_sql_setup()
for_update_part = None
# Is a LIMIT/OFFSET clause needed?
with_limit_offset = with_limits and (
self.query.high_mark is not None or self.query.low_mark
)
combinator = self.query.combinator
features = self.connection.features
if combinator:
if not getattr(features, "supports_select_{}".format(combinator)):
raise NotSupportedError(
"{} is not supported on this database backend.".format(
combinator
)
)
result, params = self.get_combinator_sql(
combinator, self.query.combinator_all
)
else:
distinct_fields, distinct_params = self.get_distinct()
# This must come after 'select', 'ordering', and 'distinct'
# (see docstring of get_from_clause() for details).
from_, f_params = self.get_from_clause()
try:
where, w_params = (
self.compile(self.where) if self.where is not None else ("", [])
)
except EmptyResultSet:
if self.elide_empty:
raise
# Use a predicate that's always False.
where, w_params = "0 = 1", []
having, h_params = (
self.compile(self.having) if self.having is not None else ("", [])
)
result = ["SELECT"]
params = []
if self.query.distinct:
distinct_result, distinct_params = self.connection.ops.distinct_sql(
distinct_fields,
distinct_params,
)
result += distinct_result
params += distinct_params
out_cols = []
col_idx = 1
for _, (s_sql, s_params), alias in self.select + extra_select:
if alias:
s_sql = "%s AS %s" % (
s_sql,
self.connection.ops.quote_name(alias),
)
elif with_col_aliases:
s_sql = "%s AS %s" % (
s_sql,
self.connection.ops.quote_name("col%d" % col_idx),
)
col_idx += 1
params.extend(s_params)
out_cols.append(s_sql)
result += [", ".join(out_cols)]
if from_:
result += ["FROM", *from_]
elif self.connection.features.bare_select_suffix:
result += [self.connection.features.bare_select_suffix]
params.extend(f_params)
if self.query.select_for_update and features.has_select_for_update:
if (
self.connection.get_autocommit()
# Don't raise an exception when database doesn't
# support transactions, as it's a noop.
and features.supports_transactions
):
raise TransactionManagementError(
"select_for_update cannot be used outside of a transaction."
)
if (
with_limit_offset
and not features.supports_select_for_update_with_limit
):
raise NotSupportedError(
"LIMIT/OFFSET is not supported with "
"select_for_update on this database backend."
)
nowait = self.query.select_for_update_nowait
skip_locked = self.query.select_for_update_skip_locked
of = self.query.select_for_update_of
no_key = self.query.select_for_no_key_update
# If it's a NOWAIT/SKIP LOCKED/OF/NO KEY query but the
# backend doesn't support it, raise NotSupportedError to
# prevent a possible deadlock.
if nowait and not features.has_select_for_update_nowait:
raise NotSupportedError(
"NOWAIT is not supported on this database backend."
)
elif skip_locked and not features.has_select_for_update_skip_locked:
raise NotSupportedError(
"SKIP LOCKED is not supported on this database backend."
)
elif of and not features.has_select_for_update_of:
raise NotSupportedError(
"FOR UPDATE OF is not supported on this database backend."
)
elif no_key and not features.has_select_for_no_key_update:
raise NotSupportedError(
"FOR NO KEY UPDATE is not supported on this "
"database backend."
)
for_update_part = self.connection.ops.for_update_sql(
nowait=nowait,
skip_locked=skip_locked,
of=self.get_select_for_update_of_arguments(),
no_key=no_key,
)
if for_update_part and features.for_update_after_from:
result.append(for_update_part)
if where:
result.append("WHERE %s" % where)
params.extend(w_params)
grouping = []
for g_sql, g_params in group_by:
grouping.append(g_sql)
params.extend(g_params)
if grouping:
if distinct_fields:
raise NotImplementedError(
"annotate() + distinct(fields) is not implemented."
)
order_by = order_by or self.connection.ops.force_no_ordering()
result.append("GROUP BY %s" % ", ".join(grouping))
if self._meta_ordering:
order_by = None
if having:
result.append("HAVING %s" % having)
params.extend(h_params)
if self.query.explain_info:
result.insert(
0,
self.connection.ops.explain_query_prefix(
self.query.explain_info.format,
**self.query.explain_info.options,
),
)
if order_by:
ordering = []
for _, (o_sql, o_params, _) in order_by:
ordering.append(o_sql)
params.extend(o_params)
result.append("ORDER BY %s" % ", ".join(ordering))
if with_limit_offset:
result.append(
self.connection.ops.limit_offset_sql(
self.query.low_mark, self.query.high_mark
)
)
if for_update_part and not features.for_update_after_from:
result.append(for_update_part)
if self.query.subquery and extra_select:
# If the query is used as a subquery, the extra selects would
# result in more columns than the left-hand side expression is
# expecting. This can happen when a subquery uses a combination
# of order_by() and distinct(), forcing the ordering expressions
# to be selected as well. Wrap the query in another subquery
# to exclude extraneous selects.
sub_selects = []
sub_params = []
for index, (select, _, alias) in enumerate(self.select, start=1):
if not alias and with_col_aliases:
alias = "col%d" % index
if alias:
sub_selects.append(
"%s.%s"
% (
self.connection.ops.quote_name("subquery"),
self.connection.ops.quote_name(alias),
)
)
else:
select_clone = select.relabeled_clone(
{select.alias: "subquery"}
)
subselect, subparams = select_clone.as_sql(
self, self.connection
)
sub_selects.append(subselect)
sub_params.extend(subparams)
return "SELECT %s FROM (%s) subquery" % (
", ".join(sub_selects),
" ".join(result),
), tuple(sub_params + params)
return " ".join(result), tuple(params)
finally:
# Finally do cleanup - get rid of the joins we created above.
self.query.reset_refcounts(refcounts_before)
def get_default_columns(self, start_alias=None, opts=None, from_parent=None):
"""
Compute the default columns for selecting every field in the base
model. Will sometimes be called to pull in related models (e.g. via
select_related), in which case "opts" and "start_alias" will be given
to provide a starting point for the traversal.
Return a list of strings, quoted appropriately for use in SQL
directly, as well as a set of aliases used in the select statement (if
'as_pairs' is True, return a list of (alias, col_name) pairs instead
of strings as the first component and None as the second component).
"""
result = []
if opts is None:
if (opts := self.query.get_meta()) is None:
return result
only_load = self.deferred_to_columns()
start_alias = start_alias or self.query.get_initial_alias()
# The 'seen_models' is used to optimize checking the needed parent
# alias for a given field. This also includes None -> start_alias to
# be used by local fields.
seen_models = {None: start_alias}
for field in opts.concrete_fields:
model = field.model._meta.concrete_model
# A proxy model will have a different model and concrete_model. We
# will assign None if the field belongs to this model.
if model == opts.model:
model = None
if (
from_parent
and model is not None
and issubclass(
from_parent._meta.concrete_model, model._meta.concrete_model
)
):
# Avoid loading data for already loaded parents.
# We end up here in the case select_related() resolution
# proceeds from parent model to child model. In that case the
# parent model data is already present in the SELECT clause,
# and we want to avoid reloading the same data again.
continue
if field.model in only_load and field.attname not in only_load[field.model]:
continue
alias = self.query.join_parent_model(opts, model, start_alias, seen_models)
column = field.get_col(alias)
result.append(column)
return result
def get_distinct(self):
"""
Return a quoted list of fields to use in DISTINCT ON part of the query.
This method can alter the tables in the query, and thus it must be
called before get_from_clause().
"""
result = []
params = []
opts = self.query.get_meta()
for name in self.query.distinct_fields:
parts = name.split(LOOKUP_SEP)
_, targets, alias, joins, path, _, transform_function = self._setup_joins(
parts, opts, None
)
targets, alias, _ = self.query.trim_joins(targets, joins, path)
for target in targets:
if name in self.query.annotation_select:
result.append(self.connection.ops.quote_name(name))
else:
r, p = self.compile(transform_function(target, alias))
result.append(r)
params.append(p)
return result, params
def find_ordering_name(
self, name, opts, alias=None, default_order="ASC", already_seen=None
):
"""
Return the table alias (the name might be ambiguous, the alias will
not be) and column name for ordering by the given 'name' parameter.
The 'name' is of the form 'field1__field2__...__fieldN'.
"""
name, order = get_order_dir(name, default_order)
descending = order == "DESC"
pieces = name.split(LOOKUP_SEP)
(
field,
targets,
alias,
joins,
path,
opts,
transform_function,
) = self._setup_joins(pieces, opts, alias)
# If we get to this point and the field is a relation to another model,
# append the default ordering for that model unless it is the pk
# shortcut or the attribute name of the field that is specified.
if (
field.is_relation
and opts.ordering
and getattr(field, "attname", None) != pieces[-1]
and name != "pk"
):
# Firstly, avoid infinite loops.
already_seen = already_seen or set()
join_tuple = tuple(
getattr(self.query.alias_map[j], "join_cols", None) for j in joins
)
if join_tuple in already_seen:
raise FieldError("Infinite loop caused by ordering.")
already_seen.add(join_tuple)
results = []
for item in opts.ordering:
if hasattr(item, "resolve_expression") and not isinstance(
item, OrderBy
):
item = item.desc() if descending else item.asc()
if isinstance(item, OrderBy):
results.append(
(item.prefix_references(f"{name}{LOOKUP_SEP}"), False)
)
continue
results.extend(
(expr.prefix_references(f"{name}{LOOKUP_SEP}"), is_ref)
for expr, is_ref in self.find_ordering_name(
item, opts, alias, order, already_seen
)
)
return results
targets, alias, _ = self.query.trim_joins(targets, joins, path)
return [
(OrderBy(transform_function(t, alias), descending=descending), False)
for t in targets
]
def _setup_joins(self, pieces, opts, alias):
"""
Helper method for get_order_by() and get_distinct().
get_ordering() and get_distinct() must produce same target columns on
same input, as the prefixes of get_ordering() and get_distinct() must
match. Executing SQL where this is not true is an error.
"""
alias = alias or self.query.get_initial_alias()
field, targets, opts, joins, path, transform_function = self.query.setup_joins(
pieces, opts, alias
)
alias = joins[-1]
return field, targets, alias, joins, path, opts, transform_function
def get_from_clause(self):
"""
Return a list of strings that are joined together to go after the
"FROM" part of the query, as well as a list any extra parameters that
need to be included. Subclasses, can override this to create a
from-clause via a "select".
This should only be called after any SQL construction methods that
might change the tables that are needed. This means the select columns,
ordering, and distinct must be done first.
"""
result = []
params = []
for alias in tuple(self.query.alias_map):
if not self.query.alias_refcount[alias]:
continue
try:
from_clause = self.query.alias_map[alias]
except KeyError:
# Extra tables can end up in self.tables, but not in the
# alias_map if they aren't in a join. That's OK. We skip them.
continue
clause_sql, clause_params = self.compile(from_clause)
result.append(clause_sql)
params.extend(clause_params)
for t in self.query.extra_tables:
alias, _ = self.query.table_alias(t)
# Only add the alias if it's not already present (the table_alias()
# call increments the refcount, so an alias refcount of one means
# this is the only reference).
if (
alias not in self.query.alias_map
or self.query.alias_refcount[alias] == 1
):
result.append(", %s" % self.quote_name_unless_alias(alias))
return result, params
def get_related_selections(
self,
select,
opts=None,
root_alias=None,
cur_depth=1,
requested=None,
restricted=None,
):
"""
Fill in the information needed for a select_related query. The current
depth is measured as the number of connections away from the root model
(for example, cur_depth=1 means we are looking at models with direct
connections to the root model).
"""
def _get_field_choices():
direct_choices = (f.name for f in opts.fields if f.is_relation)
reverse_choices = (
f.field.related_query_name()
for f in opts.related_objects
if f.field.unique
)
return chain(
direct_choices, reverse_choices, self.query._filtered_relations
)
related_klass_infos = []
if not restricted and cur_depth > self.query.max_depth:
# We've recursed far enough; bail out.
return related_klass_infos
if not opts:
opts = self.query.get_meta()
root_alias = self.query.get_initial_alias()
only_load = self.deferred_to_columns()
# Setup for the case when only particular related fields should be
# included in the related selection.
fields_found = set()
if requested is None:
restricted = isinstance(self.query.select_related, dict)
if restricted:
requested = self.query.select_related
def get_related_klass_infos(klass_info, related_klass_infos):
klass_info["related_klass_infos"] = related_klass_infos
for f in opts.fields:
field_model = f.model._meta.concrete_model
fields_found.add(f.name)
if restricted:
next = requested.get(f.name, {})
if not f.is_relation:
# If a non-related field is used like a relation,
# or if a single non-relational field is given.
if next or f.name in requested:
raise FieldError(
"Non-relational field given in select_related: '%s'. "
"Choices are: %s"
% (
f.name,
", ".join(_get_field_choices()) or "(none)",
)
)
else:
next = False
if not select_related_descend(
f, restricted, requested, only_load.get(field_model)
):
continue
klass_info = {
"model": f.remote_field.model,
"field": f,
"reverse": False,
"local_setter": f.set_cached_value,
"remote_setter": f.remote_field.set_cached_value
if f.unique
else lambda x, y: None,
"from_parent": False,
}
related_klass_infos.append(klass_info)
select_fields = []
_, _, _, joins, _, _ = self.query.setup_joins([f.name], opts, root_alias)
alias = joins[-1]
columns = self.get_default_columns(
start_alias=alias, opts=f.remote_field.model._meta
)
for col in columns:
select_fields.append(len(select))
select.append((col, None))
klass_info["select_fields"] = select_fields
next_klass_infos = self.get_related_selections(
select,
f.remote_field.model._meta,
alias,
cur_depth + 1,
next,
restricted,
)
get_related_klass_infos(klass_info, next_klass_infos)
if restricted:
related_fields = [
(o.field, o.related_model)
for o in opts.related_objects
if o.field.unique and not o.many_to_many
]
for f, model in related_fields:
if not select_related_descend(
f, restricted, requested, only_load.get(model), reverse=True
):
continue
related_field_name = f.related_query_name()
fields_found.add(related_field_name)
join_info = self.query.setup_joins(
[related_field_name], opts, root_alias
)
alias = join_info.joins[-1]
from_parent = issubclass(model, opts.model) and model is not opts.model
klass_info = {
"model": model,
"field": f,
"reverse": True,
"local_setter": f.remote_field.set_cached_value,
"remote_setter": f.set_cached_value,
"from_parent": from_parent,
}
related_klass_infos.append(klass_info)
select_fields = []
columns = self.get_default_columns(
start_alias=alias, opts=model._meta, from_parent=opts.model
)
for col in columns:
select_fields.append(len(select))
select.append((col, None))
klass_info["select_fields"] = select_fields
next = requested.get(f.related_query_name(), {})
next_klass_infos = self.get_related_selections(
select, model._meta, alias, cur_depth + 1, next, restricted
)
get_related_klass_infos(klass_info, next_klass_infos)
def local_setter(obj, from_obj):
# Set a reverse fk object when relation is non-empty.
if from_obj:
f.remote_field.set_cached_value(from_obj, obj)
def remote_setter(name, obj, from_obj):
setattr(from_obj, name, obj)
for name in list(requested):
# Filtered relations work only on the topmost level.
if cur_depth > 1:
break
if name in self.query._filtered_relations:
fields_found.add(name)
f, _, join_opts, joins, _, _ = self.query.setup_joins(
[name], opts, root_alias
)
model = join_opts.model
alias = joins[-1]
from_parent = (
issubclass(model, opts.model) and model is not opts.model
)
klass_info = {
"model": model,
"field": f,
"reverse": True,
"local_setter": local_setter,
"remote_setter": partial(remote_setter, name),
"from_parent": from_parent,
}
related_klass_infos.append(klass_info)
select_fields = []
columns = self.get_default_columns(
start_alias=alias,
opts=model._meta,
from_parent=opts.model,
)
for col in columns:
select_fields.append(len(select))
select.append((col, None))
klass_info["select_fields"] = select_fields
next_requested = requested.get(name, {})
next_klass_infos = self.get_related_selections(
select,
opts=model._meta,
root_alias=alias,
cur_depth=cur_depth + 1,
requested=next_requested,
restricted=restricted,
)
get_related_klass_infos(klass_info, next_klass_infos)
fields_not_found = set(requested).difference(fields_found)
if fields_not_found:
invalid_fields = ("'%s'" % s for s in fields_not_found)
raise FieldError(
"Invalid field name(s) given in select_related: %s. "
"Choices are: %s"
% (
", ".join(invalid_fields),
", ".join(_get_field_choices()) or "(none)",
)
)
return related_klass_infos
def get_select_for_update_of_arguments(self):
"""
Return a quoted list of arguments for the SELECT FOR UPDATE OF part of
the query.
"""
def _get_parent_klass_info(klass_info):
concrete_model = klass_info["model"]._meta.concrete_model
for parent_model, parent_link in concrete_model._meta.parents.items():
parent_list = parent_model._meta.get_parent_list()
yield {
"model": parent_model,
"field": parent_link,
"reverse": False,
"select_fields": [
select_index
for select_index in klass_info["select_fields"]
# Selected columns from a model or its parents.
if (
self.select[select_index][0].target.model == parent_model
or self.select[select_index][0].target.model in parent_list
)
],
}
def _get_first_selected_col_from_model(klass_info):
"""
Find the first selected column from a model. If it doesn't exist,
don't lock a model.
select_fields is filled recursively, so it also contains fields
from the parent models.
"""
concrete_model = klass_info["model"]._meta.concrete_model
for select_index in klass_info["select_fields"]:
if self.select[select_index][0].target.model == concrete_model:
return self.select[select_index][0]
def _get_field_choices():
"""Yield all allowed field paths in breadth-first search order."""
queue = collections.deque([(None, self.klass_info)])
while queue:
parent_path, klass_info = queue.popleft()
if parent_path is None:
path = []
yield "self"
else:
field = klass_info["field"]
if klass_info["reverse"]:
field = field.remote_field
path = parent_path + [field.name]
yield LOOKUP_SEP.join(path)
queue.extend(
(path, klass_info)
for klass_info in _get_parent_klass_info(klass_info)
)
queue.extend(
(path, klass_info)
for klass_info in klass_info.get("related_klass_infos", [])
)
if not self.klass_info:
return []
result = []
invalid_names = []
for name in self.query.select_for_update_of:
klass_info = self.klass_info
if name == "self":
col = _get_first_selected_col_from_model(klass_info)
else:
for part in name.split(LOOKUP_SEP):
klass_infos = (
*klass_info.get("related_klass_infos", []),
*_get_parent_klass_info(klass_info),
)
for related_klass_info in klass_infos:
field = related_klass_info["field"]
if related_klass_info["reverse"]:
field = field.remote_field
if field.name == part:
klass_info = related_klass_info
break
else:
klass_info = None
break
if klass_info is None:
invalid_names.append(name)
continue
col = _get_first_selected_col_from_model(klass_info)
if col is not None:
if self.connection.features.select_for_update_of_column:
result.append(self.compile(col)[0])
else:
result.append(self.quote_name_unless_alias(col.alias))
if invalid_names:
raise FieldError(
"Invalid field name(s) given in select_for_update(of=(...)): %s. "
"Only relational fields followed in the query are allowed. "
"Choices are: %s."
% (
", ".join(invalid_names),
", ".join(_get_field_choices()),
)
)
return result
def deferred_to_columns(self):
"""
Convert the self.deferred_loading data structure to mapping of table
names to sets of column names which are to be loaded. Return the
dictionary.
"""
columns = {}
self.query.deferred_to_data(columns)
return columns
def get_converters(self, expressions):
converters = {}
for i, expression in enumerate(expressions):
if expression:
backend_converters = self.connection.ops.get_db_converters(expression)
field_converters = expression.get_db_converters(self.connection)
if backend_converters or field_converters:
converters[i] = (backend_converters + field_converters, expression)
return converters
def apply_converters(self, rows, converters):
connection = self.connection
converters = list(converters.items())
for row in map(list, rows):
for pos, (convs, expression) in converters:
value = row[pos]
for converter in convs:
value = converter(value, expression, connection)
row[pos] = value
yield row
def results_iter(
self,
results=None,
tuple_expected=False,
chunked_fetch=False,
chunk_size=GET_ITERATOR_CHUNK_SIZE,
):
"""Return an iterator over the results from executing this query."""
if results is None:
results = self.execute_sql(
MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size
)
fields = [s[0] for s in self.select[0 : self.col_count]]
converters = self.get_converters(fields)
rows = chain.from_iterable(results)
if converters:
rows = self.apply_converters(rows, converters)
if tuple_expected:
rows = map(tuple, rows)
return rows
def has_results(self):
"""
Backends (e.g. NoSQL) can override this in order to use optimized
versions of "query has any results."
"""
return bool(self.execute_sql(SINGLE))
def execute_sql(
self, result_type=MULTI, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE
):
"""
Run the query against the database and return the result(s). The
return value is a single data item if result_type is SINGLE, or an
iterator over the results if the result_type is MULTI.
result_type is either MULTI (use fetchmany() to retrieve all rows),
SINGLE (only retrieve a single row), or None. In this last case, the
cursor is returned if any query is executed, since it's used by
subclasses such as InsertQuery). It's possible, however, that no query
is needed, as the filters describe an empty set. In that case, None is
returned, to avoid any unnecessary database interaction.
"""
result_type = result_type or NO_RESULTS
try:
sql, params = self.as_sql()
if not sql:
raise EmptyResultSet
except EmptyResultSet:
if result_type == MULTI:
return iter([])
else:
return
if chunked_fetch:
cursor = self.connection.chunked_cursor()
else:
cursor = self.connection.cursor()
try:
cursor.execute(sql, params)
except Exception:
# Might fail for server-side cursors (e.g. connection closed)
cursor.close()
raise
if result_type == CURSOR:
# Give the caller the cursor to process and close.
return cursor
if result_type == SINGLE:
try:
val = cursor.fetchone()
if val:
return val[0 : self.col_count]
return val
finally:
# done with the cursor
cursor.close()
if result_type == NO_RESULTS:
cursor.close()
return
result = cursor_iter(
cursor,
self.connection.features.empty_fetchmany_value,
self.col_count if self.has_extra_select else None,
chunk_size,
)
if not chunked_fetch or not self.connection.features.can_use_chunked_reads:
# If we are using non-chunked reads, we return the same data
# structure as normally, but ensure it is all read into memory
# before going any further. Use chunked_fetch if requested,
# unless the database doesn't support it.
return list(result)
return result
def as_subquery_condition(self, alias, columns, compiler):
qn = compiler.quote_name_unless_alias
qn2 = self.connection.ops.quote_name
for index, select_col in enumerate(self.query.select):
lhs_sql, lhs_params = self.compile(select_col)
rhs = "%s.%s" % (qn(alias), qn2(columns[index]))
self.query.where.add(RawSQL("%s = %s" % (lhs_sql, rhs), lhs_params), AND)
sql, params = self.as_sql()
return "EXISTS (%s)" % sql, params
def explain_query(self):
result = list(self.execute_sql())
# Some backends return 1 item tuples with strings, and others return
# tuples with integers and strings. Flatten them out into strings.
format_ = self.query.explain_info.format
output_formatter = json.dumps if format_ and format_.lower() == "json" else str
for row in result[0]:
if not isinstance(row, str):
yield " ".join(output_formatter(c) for c in row)
else:
yield row
class SQLInsertCompiler(SQLCompiler):
returning_fields = None
returning_params = ()
def field_as_sql(self, field, val):
"""
Take a field and a value intended to be saved on that field, and
return placeholder SQL and accompanying params. Check for raw values,
expressions, and fields with get_placeholder() defined in that order.
When field is None, consider the value raw and use it as the
placeholder, with no corresponding parameters returned.
"""
if field is None:
# A field value of None means the value is raw.
sql, params = val, []
elif hasattr(val, "as_sql"):
# This is an expression, let's compile it.
sql, params = self.compile(val)
elif hasattr(field, "get_placeholder"):
# Some fields (e.g. geo fields) need special munging before
# they can be inserted.
sql, params = field.get_placeholder(val, self, self.connection), [val]
else:
# Return the common case for the placeholder
sql, params = "%s", [val]
# The following hook is only used by Oracle Spatial, which sometimes
# needs to yield 'NULL' and [] as its placeholder and params instead
# of '%s' and [None]. The 'NULL' placeholder is produced earlier by
# OracleOperations.get_geom_placeholder(). The following line removes
# the corresponding None parameter. See ticket #10888.
params = self.connection.ops.modify_insert_params(sql, params)
return sql, params
def prepare_value(self, field, value):
"""
Prepare a value to be used in a query by resolving it if it is an
expression and otherwise calling the field's get_db_prep_save().
"""
if hasattr(value, "resolve_expression"):
value = value.resolve_expression(
self.query, allow_joins=False, for_save=True
)
# Don't allow values containing Col expressions. They refer to
# existing columns on a row, but in the case of insert the row
# doesn't exist yet.
if value.contains_column_references:
raise ValueError(
'Failed to insert expression "%s" on %s. F() expressions '
"can only be used to update, not to insert." % (value, field)
)
if value.contains_aggregate:
raise FieldError(
"Aggregate functions are not allowed in this query "
"(%s=%r)." % (field.name, value)
)
if value.contains_over_clause:
raise FieldError(
"Window expressions are not allowed in this query (%s=%r)."
% (field.name, value)
)
else:
value = field.get_db_prep_save(value, connection=self.connection)
return value
def pre_save_val(self, field, obj):
"""
Get the given field's value off the given obj. pre_save() is used for
things like auto_now on DateTimeField. Skip it if this is a raw query.
"""
if self.query.raw:
return getattr(obj, field.attname)
return field.pre_save(obj, add=True)
def assemble_as_sql(self, fields, value_rows):
"""
Take a sequence of N fields and a sequence of M rows of values, and
generate placeholder SQL and parameters for each field and value.
Return a pair containing:
* a sequence of M rows of N SQL placeholder strings, and
* a sequence of M rows of corresponding parameter values.
Each placeholder string may contain any number of '%s' interpolation
strings, and each parameter row will contain exactly as many params
as the total number of '%s's in the corresponding placeholder row.
"""
if not value_rows:
return [], []
# list of (sql, [params]) tuples for each object to be saved
# Shape: [n_objs][n_fields][2]
rows_of_fields_as_sql = (
(self.field_as_sql(field, v) for field, v in zip(fields, row))
for row in value_rows
)
# tuple like ([sqls], [[params]s]) for each object to be saved
# Shape: [n_objs][2][n_fields]
sql_and_param_pair_rows = (zip(*row) for row in rows_of_fields_as_sql)
# Extract separate lists for placeholders and params.
# Each of these has shape [n_objs][n_fields]
placeholder_rows, param_rows = zip(*sql_and_param_pair_rows)
# Params for each field are still lists, and need to be flattened.
param_rows = [[p for ps in row for p in ps] for row in param_rows]
return placeholder_rows, param_rows
def as_sql(self):
# We don't need quote_name_unless_alias() here, since these are all
# going to be column names (so we can avoid the extra overhead).
qn = self.connection.ops.quote_name
opts = self.query.get_meta()
insert_statement = self.connection.ops.insert_statement(
on_conflict=self.query.on_conflict,
)
result = ["%s %s" % (insert_statement, qn(opts.db_table))]
fields = self.query.fields or [opts.pk]
result.append("(%s)" % ", ".join(qn(f.column) for f in fields))
if self.query.fields:
value_rows = [
[
self.prepare_value(field, self.pre_save_val(field, obj))
for field in fields
]
for obj in self.query.objs
]
else:
# An empty object.
value_rows = [
[self.connection.ops.pk_default_value()] for _ in self.query.objs
]
fields = [None]
# Currently the backends just accept values when generating bulk
# queries and generate their own placeholders. Doing that isn't
# necessary and it should be possible to use placeholders and
# expressions in bulk inserts too.
can_bulk = (
not self.returning_fields and self.connection.features.has_bulk_insert
)
placeholder_rows, param_rows = self.assemble_as_sql(fields, value_rows)
on_conflict_suffix_sql = self.connection.ops.on_conflict_suffix_sql(
fields,
self.query.on_conflict,
self.query.update_fields,
self.query.unique_fields,
)
if (
self.returning_fields
and self.connection.features.can_return_columns_from_insert
):
if self.connection.features.can_return_rows_from_bulk_insert:
result.append(
self.connection.ops.bulk_insert_sql(fields, placeholder_rows)
)
params = param_rows
else:
result.append("VALUES (%s)" % ", ".join(placeholder_rows[0]))
params = [param_rows[0]]
if on_conflict_suffix_sql:
result.append(on_conflict_suffix_sql)
# Skip empty r_sql to allow subclasses to customize behavior for
# 3rd party backends. Refs #19096.
r_sql, self.returning_params = self.connection.ops.return_insert_columns(
self.returning_fields
)
if r_sql:
result.append(r_sql)
params += [self.returning_params]
return [(" ".join(result), tuple(chain.from_iterable(params)))]
if can_bulk:
result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows))
if on_conflict_suffix_sql:
result.append(on_conflict_suffix_sql)
return [(" ".join(result), tuple(p for ps in param_rows for p in ps))]
else:
if on_conflict_suffix_sql:
result.append(on_conflict_suffix_sql)
return [
(" ".join(result + ["VALUES (%s)" % ", ".join(p)]), vals)
for p, vals in zip(placeholder_rows, param_rows)
]
def execute_sql(self, returning_fields=None):
assert not (
returning_fields
and len(self.query.objs) != 1
and not self.connection.features.can_return_rows_from_bulk_insert
)
opts = self.query.get_meta()
self.returning_fields = returning_fields
with self.connection.cursor() as cursor:
for sql, params in self.as_sql():
cursor.execute(sql, params)
if not self.returning_fields:
return []
if (
self.connection.features.can_return_rows_from_bulk_insert
and len(self.query.objs) > 1
):
rows = self.connection.ops.fetch_returned_insert_rows(cursor)
elif self.connection.features.can_return_columns_from_insert:
assert len(self.query.objs) == 1
rows = [
self.connection.ops.fetch_returned_insert_columns(
cursor,
self.returning_params,
)
]
else:
rows = [
(
self.connection.ops.last_insert_id(
cursor,
opts.db_table,
opts.pk.column,
),
)
]
cols = [field.get_col(opts.db_table) for field in self.returning_fields]
converters = self.get_converters(cols)
if converters:
rows = list(self.apply_converters(rows, converters))
return rows
class SQLDeleteCompiler(SQLCompiler):
@cached_property
def single_alias(self):
# Ensure base table is in aliases.
self.query.get_initial_alias()
return sum(self.query.alias_refcount[t] > 0 for t in self.query.alias_map) == 1
@classmethod
def _expr_refs_base_model(cls, expr, base_model):
if isinstance(expr, Query):
return expr.model == base_model
if not hasattr(expr, "get_source_expressions"):
return False
return any(
cls._expr_refs_base_model(source_expr, base_model)
for source_expr in expr.get_source_expressions()
)
@cached_property
def contains_self_reference_subquery(self):
return any(
self._expr_refs_base_model(expr, self.query.model)
for expr in chain(
self.query.annotations.values(), self.query.where.children
)
)
def _as_sql(self, query):
result = ["DELETE FROM %s" % self.quote_name_unless_alias(query.base_table)]
where, params = self.compile(query.where)
if where:
result.append("WHERE %s" % where)
return " ".join(result), tuple(params)
def as_sql(self):
"""
Create the SQL for this query. Return the SQL string and list of
parameters.
"""
if self.single_alias and not self.contains_self_reference_subquery:
return self._as_sql(self.query)
innerq = self.query.clone()
innerq.__class__ = Query
innerq.clear_select_clause()
pk = self.query.model._meta.pk
innerq.select = [pk.get_col(self.query.get_initial_alias())]
outerq = Query(self.query.model)
if not self.connection.features.update_can_self_select:
# Force the materialization of the inner query to allow reference
# to the target table on MySQL.
sql, params = innerq.get_compiler(connection=self.connection).as_sql()
innerq = RawSQL("SELECT * FROM (%s) subquery" % sql, params)
outerq.add_filter("pk__in", innerq)
return self._as_sql(outerq)
class SQLUpdateCompiler(SQLCompiler):
def as_sql(self):
"""
Create the SQL for this query. Return the SQL string and list of
parameters.
"""
self.pre_sql_setup()
if not self.query.values:
return "", ()
qn = self.quote_name_unless_alias
values, update_params = [], []
for field, model, val in self.query.values:
if hasattr(val, "resolve_expression"):
val = val.resolve_expression(
self.query, allow_joins=False, for_save=True
)
if val.contains_aggregate:
raise FieldError(
"Aggregate functions are not allowed in this query "
"(%s=%r)." % (field.name, val)
)
if val.contains_over_clause:
raise FieldError(
"Window expressions are not allowed in this query "
"(%s=%r)." % (field.name, val)
)
elif hasattr(val, "prepare_database_save"):
if field.remote_field:
val = field.get_db_prep_save(
val.prepare_database_save(field),
connection=self.connection,
)
else:
raise TypeError(
"Tried to update field %s with a model instance, %r. "
"Use a value compatible with %s."
% (field, val, field.__class__.__name__)
)
else:
val = field.get_db_prep_save(val, connection=self.connection)
# Getting the placeholder for the field.
if hasattr(field, "get_placeholder"):
placeholder = field.get_placeholder(val, self, self.connection)
else:
placeholder = "%s"
name = field.column
if hasattr(val, "as_sql"):
sql, params = self.compile(val)
values.append("%s = %s" % (qn(name), placeholder % sql))
update_params.extend(params)
elif val is not None:
values.append("%s = %s" % (qn(name), placeholder))
update_params.append(val)
else:
values.append("%s = NULL" % qn(name))
table = self.query.base_table
result = [
"UPDATE %s SET" % qn(table),
", ".join(values),
]
where, params = self.compile(self.query.where)
if where:
result.append("WHERE %s" % where)
return " ".join(result), tuple(update_params + params)
def execute_sql(self, result_type):
"""
Execute the specified update. Return the number of rows affected by
the primary update query. The "primary update query" is the first
non-empty query that is executed. Row counts for any subsequent,
related queries are not available.
"""
cursor = super().execute_sql(result_type)
try:
rows = cursor.rowcount if cursor else 0
is_empty = cursor is None
finally:
if cursor:
cursor.close()
for query in self.query.get_related_updates():
aux_rows = query.get_compiler(self.using).execute_sql(result_type)
if is_empty and aux_rows:
rows = aux_rows
is_empty = False
return rows
def pre_sql_setup(self):
"""
If the update depends on results from other tables, munge the "where"
conditions to match the format required for (portable) SQL updates.
If multiple updates are required, pull out the id values to update at
this point so that they don't change as a result of the progressive
updates.
"""
refcounts_before = self.query.alias_refcount.copy()
# Ensure base table is in the query
self.query.get_initial_alias()
count = self.query.count_active_tables()
if not self.query.related_updates and count == 1:
return
query = self.query.chain(klass=Query)
query.select_related = False
query.clear_ordering(force=True)
query.extra = {}
query.select = []
meta = query.get_meta()
fields = [meta.pk.name]
related_ids_index = []
for related in self.query.related_updates:
if all(
path.join_field.primary_key for path in meta.get_path_to_parent(related)
):
# If a primary key chain exists to the targeted related update,
# then the meta.pk value can be used for it.
related_ids_index.append((related, 0))
else:
# This branch will only be reached when updating a field of an
# ancestor that is not part of the primary key chain of a MTI
# tree.
related_ids_index.append((related, len(fields)))
fields.append(related._meta.pk.name)
query.add_fields(fields)
super().pre_sql_setup()
must_pre_select = (
count > 1 and not self.connection.features.update_can_self_select
)
# Now we adjust the current query: reset the where clause and get rid
# of all the tables we don't need (since they're in the sub-select).
self.query.clear_where()
if self.query.related_updates or must_pre_select:
# Either we're using the idents in multiple update queries (so
# don't want them to change), or the db backend doesn't support
# selecting from the updating table (e.g. MySQL).
idents = []
related_ids = collections.defaultdict(list)
for rows in query.get_compiler(self.using).execute_sql(MULTI):
idents.extend(r[0] for r in rows)
for parent, index in related_ids_index:
related_ids[parent].extend(r[index] for r in rows)
self.query.add_filter("pk__in", idents)
self.query.related_ids = related_ids
else:
# The fast path. Filters and updates in one query.
self.query.add_filter("pk__in", query)
self.query.reset_refcounts(refcounts_before)
class SQLAggregateCompiler(SQLCompiler):
def as_sql(self):
"""
Create the SQL for this query. Return the SQL string and list of
parameters.
"""
sql, params = [], []
for annotation in self.query.annotation_select.values():
ann_sql, ann_params = self.compile(annotation)
ann_sql, ann_params = annotation.select_format(self, ann_sql, ann_params)
sql.append(ann_sql)
params.extend(ann_params)
self.col_count = len(self.query.annotation_select)
sql = ", ".join(sql)
params = tuple(params)
inner_query_sql, inner_query_params = self.query.inner_query.get_compiler(
self.using,
elide_empty=self.elide_empty,
).as_sql(with_col_aliases=True)
sql = "SELECT %s FROM (%s) subquery" % (sql, inner_query_sql)
params = params + inner_query_params
return sql, params
def cursor_iter(cursor, sentinel, col_count, itersize):
"""
Yield blocks of rows from a cursor and ensure the cursor is closed when
done.
"""
try:
for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel):
yield rows if col_count is None else [r[:col_count] for r in rows]
finally:
cursor.close()
|
c81b245c45098e12912926e073a151a84e797531b1104f4edb114ee018dee389 | """
Code to manage the creation and SQL rendering of 'where' constraints.
"""
import operator
from functools import reduce
from django.core.exceptions import EmptyResultSet
from django.db.models.expressions import Case, When
from django.db.models.lookups import Exact
from django.utils import tree
from django.utils.functional import cached_property
# Connection types
AND = "AND"
OR = "OR"
XOR = "XOR"
class WhereNode(tree.Node):
"""
An SQL WHERE clause.
The class is tied to the Query class that created it (in order to create
the correct SQL).
A child is usually an expression producing boolean values. Most likely the
expression is a Lookup instance.
However, a child could also be any class with as_sql() and either
relabeled_clone() method or relabel_aliases() and clone() methods and
contains_aggregate attribute.
"""
default = AND
resolved = False
conditional = True
def split_having(self, negated=False):
"""
Return two possibly None nodes: one for those parts of self that
should be included in the WHERE clause and one for those parts of
self that must be included in the HAVING clause.
"""
if not self.contains_aggregate:
return self, None
in_negated = negated ^ self.negated
# If the effective connector is OR or XOR and this node contains an
# aggregate, then we need to push the whole branch to HAVING clause.
may_need_split = (
(in_negated and self.connector == AND)
or (not in_negated and self.connector == OR)
or self.connector == XOR
)
if may_need_split and self.contains_aggregate:
return None, self
where_parts = []
having_parts = []
for c in self.children:
if hasattr(c, "split_having"):
where_part, having_part = c.split_having(in_negated)
if where_part is not None:
where_parts.append(where_part)
if having_part is not None:
having_parts.append(having_part)
elif c.contains_aggregate:
having_parts.append(c)
else:
where_parts.append(c)
having_node = (
self.create(having_parts, self.connector, self.negated)
if having_parts
else None
)
where_node = (
self.create(where_parts, self.connector, self.negated)
if where_parts
else None
)
return where_node, having_node
def as_sql(self, compiler, connection):
"""
Return the SQL version of the where clause and the value to be
substituted in. Return '', [] if this node matches everything,
None, [] if this node is empty, and raise EmptyResultSet if this
node can't match anything.
"""
result = []
result_params = []
if self.connector == AND:
full_needed, empty_needed = len(self.children), 1
else:
full_needed, empty_needed = 1, len(self.children)
if self.connector == XOR and not connection.features.supports_logical_xor:
# Convert if the database doesn't support XOR:
# a XOR b XOR c XOR ...
# to:
# (a OR b OR c OR ...) AND (a + b + c + ...) == 1
lhs = self.__class__(self.children, OR)
rhs_sum = reduce(
operator.add,
(Case(When(c, then=1), default=0) for c in self.children),
)
rhs = Exact(1, rhs_sum)
return self.__class__([lhs, rhs], AND, self.negated).as_sql(
compiler, connection
)
for child in self.children:
try:
sql, params = compiler.compile(child)
except EmptyResultSet:
empty_needed -= 1
else:
if sql:
result.append(sql)
result_params.extend(params)
else:
full_needed -= 1
# Check if this node matches nothing or everything.
# First check the amount of full nodes and empty nodes
# to make this node empty/full.
# Now, check if this node is full/empty using the
# counts.
if empty_needed == 0:
if self.negated:
return "", []
else:
raise EmptyResultSet
if full_needed == 0:
if self.negated:
raise EmptyResultSet
else:
return "", []
conn = " %s " % self.connector
sql_string = conn.join(result)
if sql_string:
if self.negated:
# Some backends (Oracle at least) need parentheses
# around the inner SQL in the negated case, even if the
# inner SQL contains just a single expression.
sql_string = "NOT (%s)" % sql_string
elif len(result) > 1 or self.resolved:
sql_string = "(%s)" % sql_string
return sql_string, result_params
def get_group_by_cols(self, alias=None):
cols = []
for child in self.children:
cols.extend(child.get_group_by_cols())
return cols
def get_source_expressions(self):
return self.children[:]
def set_source_expressions(self, children):
assert len(children) == len(self.children)
self.children = children
def relabel_aliases(self, change_map):
"""
Relabel the alias values of any children. 'change_map' is a dictionary
mapping old (current) alias values to the new values.
"""
for pos, child in enumerate(self.children):
if hasattr(child, "relabel_aliases"):
# For example another WhereNode
child.relabel_aliases(change_map)
elif hasattr(child, "relabeled_clone"):
self.children[pos] = child.relabeled_clone(change_map)
def clone(self):
clone = self.create(connector=self.connector, negated=self.negated)
for child in self.children:
if hasattr(child, "clone"):
child = child.clone()
clone.children.append(child)
return clone
def relabeled_clone(self, change_map):
clone = self.clone()
clone.relabel_aliases(change_map)
return clone
@classmethod
def _contains_aggregate(cls, obj):
if isinstance(obj, tree.Node):
return any(cls._contains_aggregate(c) for c in obj.children)
return obj.contains_aggregate
@cached_property
def contains_aggregate(self):
return self._contains_aggregate(self)
@classmethod
def _contains_over_clause(cls, obj):
if isinstance(obj, tree.Node):
return any(cls._contains_over_clause(c) for c in obj.children)
return obj.contains_over_clause
@cached_property
def contains_over_clause(self):
return self._contains_over_clause(self)
@staticmethod
def _resolve_leaf(expr, query, *args, **kwargs):
if hasattr(expr, "resolve_expression"):
expr = expr.resolve_expression(query, *args, **kwargs)
return expr
@classmethod
def _resolve_node(cls, node, query, *args, **kwargs):
if hasattr(node, "children"):
for child in node.children:
cls._resolve_node(child, query, *args, **kwargs)
if hasattr(node, "lhs"):
node.lhs = cls._resolve_leaf(node.lhs, query, *args, **kwargs)
if hasattr(node, "rhs"):
node.rhs = cls._resolve_leaf(node.rhs, query, *args, **kwargs)
def resolve_expression(self, *args, **kwargs):
clone = self.clone()
clone._resolve_node(clone, *args, **kwargs)
clone.resolved = True
return clone
@cached_property
def output_field(self):
from django.db.models import BooleanField
return BooleanField()
def select_format(self, compiler, sql, params):
# Wrap filters with a CASE WHEN expression if a database backend
# (e.g. Oracle) doesn't support boolean expression in SELECT or GROUP
# BY list.
if not compiler.connection.features.supports_boolean_expr_in_select_clause:
sql = f"CASE WHEN {sql} THEN 1 ELSE 0 END"
return sql, params
def get_db_converters(self, connection):
return self.output_field.get_db_converters(connection)
def get_lookup(self, lookup):
return self.output_field.get_lookup(lookup)
class NothingNode:
"""A node that matches nothing."""
contains_aggregate = False
def as_sql(self, compiler=None, connection=None):
raise EmptyResultSet
class ExtraWhere:
# The contents are a black box - assume no aggregates are used.
contains_aggregate = False
def __init__(self, sqls, params):
self.sqls = sqls
self.params = params
def as_sql(self, compiler=None, connection=None):
sqls = ["(%s)" % sql for sql in self.sqls]
return " AND ".join(sqls), list(self.params or ())
class SubqueryConstraint:
# Even if aggregates would be used in a subquery, the outer query isn't
# interested about those.
contains_aggregate = False
def __init__(self, alias, columns, targets, query_object):
self.alias = alias
self.columns = columns
self.targets = targets
query_object.clear_ordering(clear_default=True)
self.query_object = query_object
def as_sql(self, compiler, connection):
query = self.query_object
query.set_values(self.targets)
query_compiler = query.get_compiler(connection=connection)
return query_compiler.as_subquery_condition(self.alias, self.columns, compiler)
|
cadeb5f1c150e46b29d5f5ff2303ae3dfa530f9f6c1c591c5fc7656bdd2fca0e | import logging
import operator
from datetime import datetime
from django.conf import settings
from django.db.backends.ddl_references import (
Columns,
Expressions,
ForeignKeyName,
IndexName,
Statement,
Table,
)
from django.db.backends.utils import names_digest, split_identifier
from django.db.models import Deferrable, Index
from django.db.models.sql import Query
from django.db.transaction import TransactionManagementError, atomic
from django.utils import timezone
logger = logging.getLogger("django.db.backends.schema")
def _is_relevant_relation(relation, altered_field):
"""
When altering the given field, must constraints on its model from the given
relation be temporarily dropped?
"""
field = relation.field
if field.many_to_many:
# M2M reverse field
return False
if altered_field.primary_key and field.to_fields == [None]:
# Foreign key constraint on the primary key, which is being altered.
return True
# Is the constraint targeting the field being altered?
return altered_field.name in field.to_fields
def _all_related_fields(model):
# Related fields must be returned in a deterministic order.
return sorted(
model._meta._get_fields(
forward=False,
reverse=True,
include_hidden=True,
include_parents=False,
),
key=operator.attrgetter("name"),
)
def _related_non_m2m_objects(old_field, new_field):
# Filter out m2m objects from reverse relations.
# Return (old_relation, new_relation) tuples.
related_fields = zip(
(
obj
for obj in _all_related_fields(old_field.model)
if _is_relevant_relation(obj, old_field)
),
(
obj
for obj in _all_related_fields(new_field.model)
if _is_relevant_relation(obj, new_field)
),
)
for old_rel, new_rel in related_fields:
yield old_rel, new_rel
yield from _related_non_m2m_objects(
old_rel.remote_field,
new_rel.remote_field,
)
class BaseDatabaseSchemaEditor:
"""
This class and its subclasses are responsible for emitting schema-changing
statements to the databases - model creation/removal/alteration, field
renaming, index fiddling, and so on.
"""
# Overrideable SQL templates
sql_create_table = "CREATE TABLE %(table)s (%(definition)s)"
sql_rename_table = "ALTER TABLE %(old_table)s RENAME TO %(new_table)s"
sql_retablespace_table = "ALTER TABLE %(table)s SET TABLESPACE %(new_tablespace)s"
sql_delete_table = "DROP TABLE %(table)s CASCADE"
sql_create_column = "ALTER TABLE %(table)s ADD COLUMN %(column)s %(definition)s"
sql_alter_column = "ALTER TABLE %(table)s %(changes)s"
sql_alter_column_type = "ALTER COLUMN %(column)s TYPE %(type)s"
sql_alter_column_null = "ALTER COLUMN %(column)s DROP NOT NULL"
sql_alter_column_not_null = "ALTER COLUMN %(column)s SET NOT NULL"
sql_alter_column_default = "ALTER COLUMN %(column)s SET DEFAULT %(default)s"
sql_alter_column_no_default = "ALTER COLUMN %(column)s DROP DEFAULT"
sql_alter_column_no_default_null = sql_alter_column_no_default
sql_alter_column_collate = "ALTER COLUMN %(column)s TYPE %(type)s%(collation)s"
sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s CASCADE"
sql_rename_column = (
"ALTER TABLE %(table)s RENAME COLUMN %(old_column)s TO %(new_column)s"
)
sql_update_with_default = (
"UPDATE %(table)s SET %(column)s = %(default)s WHERE %(column)s IS NULL"
)
sql_unique_constraint = "UNIQUE (%(columns)s)%(deferrable)s"
sql_check_constraint = "CHECK (%(check)s)"
sql_delete_constraint = "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
sql_constraint = "CONSTRAINT %(name)s %(constraint)s"
sql_create_check = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s CHECK (%(check)s)"
sql_delete_check = sql_delete_constraint
sql_create_unique = (
"ALTER TABLE %(table)s ADD CONSTRAINT %(name)s "
"UNIQUE (%(columns)s)%(deferrable)s"
)
sql_delete_unique = sql_delete_constraint
sql_create_fk = (
"ALTER TABLE %(table)s ADD CONSTRAINT %(name)s FOREIGN KEY (%(column)s) "
"REFERENCES %(to_table)s (%(to_column)s)%(deferrable)s"
)
sql_create_inline_fk = None
sql_create_column_inline_fk = None
sql_delete_fk = sql_delete_constraint
sql_create_index = (
"CREATE INDEX %(name)s ON %(table)s "
"(%(columns)s)%(include)s%(extra)s%(condition)s"
)
sql_create_unique_index = (
"CREATE UNIQUE INDEX %(name)s ON %(table)s "
"(%(columns)s)%(include)s%(condition)s"
)
sql_rename_index = "ALTER INDEX %(old_name)s RENAME TO %(new_name)s"
sql_delete_index = "DROP INDEX %(name)s"
sql_create_pk = (
"ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%(columns)s)"
)
sql_delete_pk = sql_delete_constraint
sql_delete_procedure = "DROP PROCEDURE %(procedure)s"
def __init__(self, connection, collect_sql=False, atomic=True):
self.connection = connection
self.collect_sql = collect_sql
if self.collect_sql:
self.collected_sql = []
self.atomic_migration = self.connection.features.can_rollback_ddl and atomic
# State-managing methods
def __enter__(self):
self.deferred_sql = []
if self.atomic_migration:
self.atomic = atomic(self.connection.alias)
self.atomic.__enter__()
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is None:
for sql in self.deferred_sql:
self.execute(sql)
if self.atomic_migration:
self.atomic.__exit__(exc_type, exc_value, traceback)
# Core utility functions
def execute(self, sql, params=()):
"""Execute the given SQL statement, with optional parameters."""
# Don't perform the transactional DDL check if SQL is being collected
# as it's not going to be executed anyway.
if (
not self.collect_sql
and self.connection.in_atomic_block
and not self.connection.features.can_rollback_ddl
):
raise TransactionManagementError(
"Executing DDL statements while in a transaction on databases "
"that can't perform a rollback is prohibited."
)
# Account for non-string statement objects.
sql = str(sql)
# Log the command we're running, then run it
logger.debug(
"%s; (params %r)", sql, params, extra={"params": params, "sql": sql}
)
if self.collect_sql:
ending = "" if sql.rstrip().endswith(";") else ";"
if params is not None:
self.collected_sql.append(
(sql % tuple(map(self.quote_value, params))) + ending
)
else:
self.collected_sql.append(sql + ending)
else:
with self.connection.cursor() as cursor:
cursor.execute(sql, params)
def quote_name(self, name):
return self.connection.ops.quote_name(name)
def table_sql(self, model):
"""Take a model and return its table definition."""
# Add any unique_togethers (always deferred, as some fields might be
# created afterward, like geometry fields with some backends).
for field_names in model._meta.unique_together:
fields = [model._meta.get_field(field) for field in field_names]
self.deferred_sql.append(self._create_unique_sql(model, fields))
# Create column SQL, add FK deferreds if needed.
column_sqls = []
params = []
for field in model._meta.local_fields:
# SQL.
definition, extra_params = self.column_sql(model, field)
if definition is None:
continue
# Check constraints can go on the column SQL here.
db_params = field.db_parameters(connection=self.connection)
if db_params["check"]:
definition += " " + self.sql_check_constraint % db_params
# Autoincrement SQL (for backends with inline variant).
col_type_suffix = field.db_type_suffix(connection=self.connection)
if col_type_suffix:
definition += " %s" % col_type_suffix
params.extend(extra_params)
# FK.
if field.remote_field and field.db_constraint:
to_table = field.remote_field.model._meta.db_table
to_column = field.remote_field.model._meta.get_field(
field.remote_field.field_name
).column
if self.sql_create_inline_fk:
definition += " " + self.sql_create_inline_fk % {
"to_table": self.quote_name(to_table),
"to_column": self.quote_name(to_column),
}
elif self.connection.features.supports_foreign_keys:
self.deferred_sql.append(
self._create_fk_sql(
model, field, "_fk_%(to_table)s_%(to_column)s"
)
)
# Add the SQL to our big list.
column_sqls.append(
"%s %s"
% (
self.quote_name(field.column),
definition,
)
)
# Autoincrement SQL (for backends with post table definition
# variant).
if field.get_internal_type() in (
"AutoField",
"BigAutoField",
"SmallAutoField",
):
autoinc_sql = self.connection.ops.autoinc_sql(
model._meta.db_table, field.column
)
if autoinc_sql:
self.deferred_sql.extend(autoinc_sql)
constraints = [
constraint.constraint_sql(model, self)
for constraint in model._meta.constraints
]
sql = self.sql_create_table % {
"table": self.quote_name(model._meta.db_table),
"definition": ", ".join(
constraint for constraint in (*column_sqls, *constraints) if constraint
),
}
if model._meta.db_tablespace:
tablespace_sql = self.connection.ops.tablespace_sql(
model._meta.db_tablespace
)
if tablespace_sql:
sql += " " + tablespace_sql
return sql, params
# Field <-> database mapping functions
def _iter_column_sql(
self, column_db_type, params, model, field, field_db_params, include_default
):
yield column_db_type
if collation := field_db_params.get("collation"):
yield self._collate_sql(collation)
# Work out nullability.
null = field.null
# Include a default value, if requested.
include_default = (
include_default
and not self.skip_default(field)
and
# Don't include a default value if it's a nullable field and the
# default cannot be dropped in the ALTER COLUMN statement (e.g.
# MySQL longtext and longblob).
not (null and self.skip_default_on_alter(field))
)
if include_default:
default_value = self.effective_default(field)
if default_value is not None:
column_default = "DEFAULT " + self._column_default_sql(field)
if self.connection.features.requires_literal_defaults:
# Some databases can't take defaults as a parameter (Oracle).
# If this is the case, the individual schema backend should
# implement prepare_default().
yield column_default % self.prepare_default(default_value)
else:
yield column_default
params.append(default_value)
# Oracle treats the empty string ('') as null, so coerce the null
# option whenever '' is a possible value.
if (
field.empty_strings_allowed
and not field.primary_key
and self.connection.features.interprets_empty_strings_as_nulls
):
null = True
if not null:
yield "NOT NULL"
elif not self.connection.features.implied_column_null:
yield "NULL"
if field.primary_key:
yield "PRIMARY KEY"
elif field.unique:
yield "UNIQUE"
# Optionally add the tablespace if it's an implicitly indexed column.
tablespace = field.db_tablespace or model._meta.db_tablespace
if (
tablespace
and self.connection.features.supports_tablespaces
and field.unique
):
yield self.connection.ops.tablespace_sql(tablespace, inline=True)
def column_sql(self, model, field, include_default=False):
"""
Return the column definition for a field. The field must already have
had set_attributes_from_name() called.
"""
# Get the column's type and use that as the basis of the SQL.
field_db_params = field.db_parameters(connection=self.connection)
column_db_type = field_db_params["type"]
# Check for fields that aren't actually columns (e.g. M2M).
if column_db_type is None:
return None, None
params = []
return (
" ".join(
# This appends to the params being returned.
self._iter_column_sql(
column_db_type,
params,
model,
field,
field_db_params,
include_default,
)
),
params,
)
def skip_default(self, field):
"""
Some backends don't accept default values for certain columns types
(i.e. MySQL longtext and longblob).
"""
return False
def skip_default_on_alter(self, field):
"""
Some backends don't accept default values for certain columns types
(i.e. MySQL longtext and longblob) in the ALTER COLUMN statement.
"""
return False
def prepare_default(self, value):
"""
Only used for backends which have requires_literal_defaults feature
"""
raise NotImplementedError(
"subclasses of BaseDatabaseSchemaEditor for backends which have "
"requires_literal_defaults must provide a prepare_default() method"
)
def _column_default_sql(self, field):
"""
Return the SQL to use in a DEFAULT clause. The resulting string should
contain a '%s' placeholder for a default value.
"""
return "%s"
@staticmethod
def _effective_default(field):
# This method allows testing its logic without a connection.
if field.has_default():
default = field.get_default()
elif not field.null and field.blank and field.empty_strings_allowed:
if field.get_internal_type() == "BinaryField":
default = b""
else:
default = ""
elif getattr(field, "auto_now", False) or getattr(field, "auto_now_add", False):
internal_type = field.get_internal_type()
if internal_type == "DateTimeField":
default = timezone.now()
else:
default = datetime.now()
if internal_type == "DateField":
default = default.date()
elif internal_type == "TimeField":
default = default.time()
else:
default = None
return default
def effective_default(self, field):
"""Return a field's effective database default value."""
return field.get_db_prep_save(self._effective_default(field), self.connection)
def quote_value(self, value):
"""
Return a quoted version of the value so it's safe to use in an SQL
string. This is not safe against injection from user code; it is
intended only for use in making SQL scripts or preparing default values
for particularly tricky backends (defaults are not user-defined, though,
so this is safe).
"""
raise NotImplementedError()
# Actions
def create_model(self, model):
"""
Create a table and any accompanying indexes or unique constraints for
the given `model`.
"""
sql, params = self.table_sql(model)
# Prevent using [] as params, in the case a literal '%' is used in the
# definition.
self.execute(sql, params or None)
# Add any field index and index_together's (deferred as SQLite
# _remake_table needs it).
self.deferred_sql.extend(self._model_indexes_sql(model))
# Make M2M tables
for field in model._meta.local_many_to_many:
if field.remote_field.through._meta.auto_created:
self.create_model(field.remote_field.through)
def delete_model(self, model):
"""Delete a model from the database."""
# Handle auto-created intermediary models
for field in model._meta.local_many_to_many:
if field.remote_field.through._meta.auto_created:
self.delete_model(field.remote_field.through)
# Delete the table
self.execute(
self.sql_delete_table
% {
"table": self.quote_name(model._meta.db_table),
}
)
# Remove all deferred statements referencing the deleted table.
for sql in list(self.deferred_sql):
if isinstance(sql, Statement) and sql.references_table(
model._meta.db_table
):
self.deferred_sql.remove(sql)
def add_index(self, model, index):
"""Add an index on a model."""
if (
index.contains_expressions
and not self.connection.features.supports_expression_indexes
):
return None
# Index.create_sql returns interpolated SQL which makes params=None a
# necessity to avoid escaping attempts on execution.
self.execute(index.create_sql(model, self), params=None)
def remove_index(self, model, index):
"""Remove an index from a model."""
if (
index.contains_expressions
and not self.connection.features.supports_expression_indexes
):
return None
self.execute(index.remove_sql(model, self))
def rename_index(self, model, old_index, new_index):
if self.connection.features.can_rename_index:
self.execute(
self._rename_index_sql(model, old_index.name, new_index.name),
params=None,
)
else:
self.remove_index(model, old_index)
self.add_index(model, new_index)
def add_constraint(self, model, constraint):
"""Add a constraint to a model."""
sql = constraint.create_sql(model, self)
if sql:
# Constraint.create_sql returns interpolated SQL which makes
# params=None a necessity to avoid escaping attempts on execution.
self.execute(sql, params=None)
def remove_constraint(self, model, constraint):
"""Remove a constraint from a model."""
sql = constraint.remove_sql(model, self)
if sql:
self.execute(sql)
def alter_unique_together(self, model, old_unique_together, new_unique_together):
"""
Deal with a model changing its unique_together. The input
unique_togethers must be doubly-nested, not the single-nested
["foo", "bar"] format.
"""
olds = {tuple(fields) for fields in old_unique_together}
news = {tuple(fields) for fields in new_unique_together}
# Deleted uniques
for fields in olds.difference(news):
self._delete_composed_index(
model,
fields,
{"unique": True, "primary_key": False},
self.sql_delete_unique,
)
# Created uniques
for field_names in news.difference(olds):
fields = [model._meta.get_field(field) for field in field_names]
self.execute(self._create_unique_sql(model, fields))
def alter_index_together(self, model, old_index_together, new_index_together):
"""
Deal with a model changing its index_together. The input
index_togethers must be doubly-nested, not the single-nested
["foo", "bar"] format.
"""
olds = {tuple(fields) for fields in old_index_together}
news = {tuple(fields) for fields in new_index_together}
# Deleted indexes
for fields in olds.difference(news):
self._delete_composed_index(
model,
fields,
{"index": True, "unique": False},
self.sql_delete_index,
)
# Created indexes
for field_names in news.difference(olds):
fields = [model._meta.get_field(field) for field in field_names]
self.execute(self._create_index_sql(model, fields=fields, suffix="_idx"))
def _delete_composed_index(self, model, fields, constraint_kwargs, sql):
meta_constraint_names = {
constraint.name for constraint in model._meta.constraints
}
meta_index_names = {constraint.name for constraint in model._meta.indexes}
columns = [model._meta.get_field(field).column for field in fields]
constraint_names = self._constraint_names(
model,
columns,
exclude=meta_constraint_names | meta_index_names,
**constraint_kwargs,
)
if (
constraint_kwargs.get("unique") is True
and constraint_names
and self.connection.features.allows_multiple_constraints_on_same_fields
):
# Constraint matching the unique_together name.
default_name = str(
self._unique_constraint_name(model._meta.db_table, columns, quote=False)
)
if default_name in constraint_names:
constraint_names = [default_name]
if len(constraint_names) != 1:
raise ValueError(
"Found wrong number (%s) of constraints for %s(%s)"
% (
len(constraint_names),
model._meta.db_table,
", ".join(columns),
)
)
self.execute(self._delete_constraint_sql(sql, model, constraint_names[0]))
def alter_db_table(self, model, old_db_table, new_db_table):
"""Rename the table a model points to."""
if old_db_table == new_db_table or (
self.connection.features.ignores_table_name_case
and old_db_table.lower() == new_db_table.lower()
):
return
self.execute(
self.sql_rename_table
% {
"old_table": self.quote_name(old_db_table),
"new_table": self.quote_name(new_db_table),
}
)
# Rename all references to the old table name.
for sql in self.deferred_sql:
if isinstance(sql, Statement):
sql.rename_table_references(old_db_table, new_db_table)
def alter_db_tablespace(self, model, old_db_tablespace, new_db_tablespace):
"""Move a model's table between tablespaces."""
self.execute(
self.sql_retablespace_table
% {
"table": self.quote_name(model._meta.db_table),
"old_tablespace": self.quote_name(old_db_tablespace),
"new_tablespace": self.quote_name(new_db_tablespace),
}
)
def add_field(self, model, field):
"""
Create a field on a model. Usually involves adding a column, but may
involve adding a table instead (for M2M fields).
"""
# Special-case implicit M2M tables
if field.many_to_many and field.remote_field.through._meta.auto_created:
return self.create_model(field.remote_field.through)
# Get the column's definition
definition, params = self.column_sql(model, field, include_default=True)
# It might not actually have a column behind it
if definition is None:
return
# Check constraints can go on the column SQL here
db_params = field.db_parameters(connection=self.connection)
if db_params["check"]:
definition += " " + self.sql_check_constraint % db_params
if (
field.remote_field
and self.connection.features.supports_foreign_keys
and field.db_constraint
):
constraint_suffix = "_fk_%(to_table)s_%(to_column)s"
# Add FK constraint inline, if supported.
if self.sql_create_column_inline_fk:
to_table = field.remote_field.model._meta.db_table
to_column = field.remote_field.model._meta.get_field(
field.remote_field.field_name
).column
namespace, _ = split_identifier(model._meta.db_table)
definition += " " + self.sql_create_column_inline_fk % {
"name": self._fk_constraint_name(model, field, constraint_suffix),
"namespace": "%s." % self.quote_name(namespace)
if namespace
else "",
"column": self.quote_name(field.column),
"to_table": self.quote_name(to_table),
"to_column": self.quote_name(to_column),
"deferrable": self.connection.ops.deferrable_sql(),
}
# Otherwise, add FK constraints later.
else:
self.deferred_sql.append(
self._create_fk_sql(model, field, constraint_suffix)
)
# Build the SQL and run it
sql = self.sql_create_column % {
"table": self.quote_name(model._meta.db_table),
"column": self.quote_name(field.column),
"definition": definition,
}
self.execute(sql, params)
# Drop the default if we need to
# (Django usually does not use in-database defaults)
if (
not self.skip_default_on_alter(field)
and self.effective_default(field) is not None
):
changes_sql, params = self._alter_column_default_sql(
model, None, field, drop=True
)
sql = self.sql_alter_column % {
"table": self.quote_name(model._meta.db_table),
"changes": changes_sql,
}
self.execute(sql, params)
# Add an index, if required
self.deferred_sql.extend(self._field_indexes_sql(model, field))
# Reset connection if required
if self.connection.features.connection_persists_old_columns:
self.connection.close()
def remove_field(self, model, field):
"""
Remove a field from a model. Usually involves deleting a column,
but for M2Ms may involve deleting a table.
"""
# Special-case implicit M2M tables
if field.many_to_many and field.remote_field.through._meta.auto_created:
return self.delete_model(field.remote_field.through)
# It might not actually have a column behind it
if field.db_parameters(connection=self.connection)["type"] is None:
return
# Drop any FK constraints, MySQL requires explicit deletion
if field.remote_field:
fk_names = self._constraint_names(model, [field.column], foreign_key=True)
for fk_name in fk_names:
self.execute(self._delete_fk_sql(model, fk_name))
# Delete the column
sql = self.sql_delete_column % {
"table": self.quote_name(model._meta.db_table),
"column": self.quote_name(field.column),
}
self.execute(sql)
# Reset connection if required
if self.connection.features.connection_persists_old_columns:
self.connection.close()
# Remove all deferred statements referencing the deleted column.
for sql in list(self.deferred_sql):
if isinstance(sql, Statement) and sql.references_column(
model._meta.db_table, field.column
):
self.deferred_sql.remove(sql)
def alter_field(self, model, old_field, new_field, strict=False):
"""
Allow a field's type, uniqueness, nullability, default, column,
constraints, etc. to be modified.
`old_field` is required to compute the necessary changes.
If `strict` is True, raise errors if the old column does not match
`old_field` precisely.
"""
if not self._field_should_be_altered(old_field, new_field):
return
# Ensure this field is even column-based
old_db_params = old_field.db_parameters(connection=self.connection)
old_type = old_db_params["type"]
new_db_params = new_field.db_parameters(connection=self.connection)
new_type = new_db_params["type"]
if (old_type is None and old_field.remote_field is None) or (
new_type is None and new_field.remote_field is None
):
raise ValueError(
"Cannot alter field %s into %s - they do not properly define "
"db_type (are you using a badly-written custom field?)"
% (old_field, new_field),
)
elif (
old_type is None
and new_type is None
and (
old_field.remote_field.through
and new_field.remote_field.through
and old_field.remote_field.through._meta.auto_created
and new_field.remote_field.through._meta.auto_created
)
):
return self._alter_many_to_many(model, old_field, new_field, strict)
elif (
old_type is None
and new_type is None
and (
old_field.remote_field.through
and new_field.remote_field.through
and not old_field.remote_field.through._meta.auto_created
and not new_field.remote_field.through._meta.auto_created
)
):
# Both sides have through models; this is a no-op.
return
elif old_type is None or new_type is None:
raise ValueError(
"Cannot alter field %s into %s - they are not compatible types "
"(you cannot alter to or from M2M fields, or add or remove "
"through= on M2M fields)" % (old_field, new_field)
)
self._alter_field(
model,
old_field,
new_field,
old_type,
new_type,
old_db_params,
new_db_params,
strict,
)
def _alter_field(
self,
model,
old_field,
new_field,
old_type,
new_type,
old_db_params,
new_db_params,
strict=False,
):
"""Perform a "physical" (non-ManyToMany) field update."""
# Drop any FK constraints, we'll remake them later
fks_dropped = set()
if (
self.connection.features.supports_foreign_keys
and old_field.remote_field
and old_field.db_constraint
):
fk_names = self._constraint_names(
model, [old_field.column], foreign_key=True
)
if strict and len(fk_names) != 1:
raise ValueError(
"Found wrong number (%s) of foreign key constraints for %s.%s"
% (
len(fk_names),
model._meta.db_table,
old_field.column,
)
)
for fk_name in fk_names:
fks_dropped.add((old_field.column,))
self.execute(self._delete_fk_sql(model, fk_name))
# Has unique been removed?
if old_field.unique and (
not new_field.unique or self._field_became_primary_key(old_field, new_field)
):
# Find the unique constraint for this field
meta_constraint_names = {
constraint.name for constraint in model._meta.constraints
}
constraint_names = self._constraint_names(
model,
[old_field.column],
unique=True,
primary_key=False,
exclude=meta_constraint_names,
)
if strict and len(constraint_names) != 1:
raise ValueError(
"Found wrong number (%s) of unique constraints for %s.%s"
% (
len(constraint_names),
model._meta.db_table,
old_field.column,
)
)
for constraint_name in constraint_names:
self.execute(self._delete_unique_sql(model, constraint_name))
# Drop incoming FK constraints if the field is a primary key or unique,
# which might be a to_field target, and things are going to change.
old_collation = old_db_params.get("collation")
new_collation = new_db_params.get("collation")
drop_foreign_keys = (
self.connection.features.supports_foreign_keys
and (
(old_field.primary_key and new_field.primary_key)
or (old_field.unique and new_field.unique)
)
and ((old_type != new_type) or (old_collation != new_collation))
)
if drop_foreign_keys:
# '_meta.related_field' also contains M2M reverse fields, these
# will be filtered out
for _old_rel, new_rel in _related_non_m2m_objects(old_field, new_field):
rel_fk_names = self._constraint_names(
new_rel.related_model, [new_rel.field.column], foreign_key=True
)
for fk_name in rel_fk_names:
self.execute(self._delete_fk_sql(new_rel.related_model, fk_name))
# Removed an index? (no strict check, as multiple indexes are possible)
# Remove indexes if db_index switched to False or a unique constraint
# will now be used in lieu of an index. The following lines from the
# truth table show all True cases; the rest are False:
#
# old_field.db_index | old_field.unique | new_field.db_index | new_field.unique
# ------------------------------------------------------------------------------
# True | False | False | False
# True | False | False | True
# True | False | True | True
if (
old_field.db_index
and not old_field.unique
and (not new_field.db_index or new_field.unique)
):
# Find the index for this field
meta_index_names = {index.name for index in model._meta.indexes}
# Retrieve only BTREE indexes since this is what's created with
# db_index=True.
index_names = self._constraint_names(
model,
[old_field.column],
index=True,
type_=Index.suffix,
exclude=meta_index_names,
)
for index_name in index_names:
# The only way to check if an index was created with
# db_index=True or with Index(['field'], name='foo')
# is to look at its name (refs #28053).
self.execute(self._delete_index_sql(model, index_name))
# Change check constraints?
if old_db_params["check"] != new_db_params["check"] and old_db_params["check"]:
meta_constraint_names = {
constraint.name for constraint in model._meta.constraints
}
constraint_names = self._constraint_names(
model,
[old_field.column],
check=True,
exclude=meta_constraint_names,
)
if strict and len(constraint_names) != 1:
raise ValueError(
"Found wrong number (%s) of check constraints for %s.%s"
% (
len(constraint_names),
model._meta.db_table,
old_field.column,
)
)
for constraint_name in constraint_names:
self.execute(self._delete_check_sql(model, constraint_name))
# Have they renamed the column?
if old_field.column != new_field.column:
self.execute(
self._rename_field_sql(
model._meta.db_table, old_field, new_field, new_type
)
)
# Rename all references to the renamed column.
for sql in self.deferred_sql:
if isinstance(sql, Statement):
sql.rename_column_references(
model._meta.db_table, old_field.column, new_field.column
)
# Next, start accumulating actions to do
actions = []
null_actions = []
post_actions = []
# Type suffix change? (e.g. auto increment).
old_type_suffix = old_field.db_type_suffix(connection=self.connection)
new_type_suffix = new_field.db_type_suffix(connection=self.connection)
# Collation change?
if old_collation != new_collation:
# Collation change handles also a type change.
fragment = self._alter_column_collation_sql(
model, new_field, new_type, new_collation, old_field
)
actions.append(fragment)
# Type change?
elif (old_type, old_type_suffix) != (new_type, new_type_suffix):
fragment, other_actions = self._alter_column_type_sql(
model, old_field, new_field, new_type
)
actions.append(fragment)
post_actions.extend(other_actions)
# When changing a column NULL constraint to NOT NULL with a given
# default value, we need to perform 4 steps:
# 1. Add a default for new incoming writes
# 2. Update existing NULL rows with new default
# 3. Replace NULL constraint with NOT NULL
# 4. Drop the default again.
# Default change?
needs_database_default = False
if old_field.null and not new_field.null:
old_default = self.effective_default(old_field)
new_default = self.effective_default(new_field)
if (
not self.skip_default_on_alter(new_field)
and old_default != new_default
and new_default is not None
):
needs_database_default = True
actions.append(
self._alter_column_default_sql(model, old_field, new_field)
)
# Nullability change?
if old_field.null != new_field.null:
fragment = self._alter_column_null_sql(model, old_field, new_field)
if fragment:
null_actions.append(fragment)
# Only if we have a default and there is a change from NULL to NOT NULL
four_way_default_alteration = new_field.has_default() and (
old_field.null and not new_field.null
)
if actions or null_actions:
if not four_way_default_alteration:
# If we don't have to do a 4-way default alteration we can
# directly run a (NOT) NULL alteration
actions = actions + null_actions
# Combine actions together if we can (e.g. postgres)
if self.connection.features.supports_combined_alters and actions:
sql, params = tuple(zip(*actions))
actions = [(", ".join(sql), sum(params, []))]
# Apply those actions
for sql, params in actions:
self.execute(
self.sql_alter_column
% {
"table": self.quote_name(model._meta.db_table),
"changes": sql,
},
params,
)
if four_way_default_alteration:
# Update existing rows with default value
self.execute(
self.sql_update_with_default
% {
"table": self.quote_name(model._meta.db_table),
"column": self.quote_name(new_field.column),
"default": "%s",
},
[new_default],
)
# Since we didn't run a NOT NULL change before we need to do it
# now
for sql, params in null_actions:
self.execute(
self.sql_alter_column
% {
"table": self.quote_name(model._meta.db_table),
"changes": sql,
},
params,
)
if post_actions:
for sql, params in post_actions:
self.execute(sql, params)
# If primary_key changed to False, delete the primary key constraint.
if old_field.primary_key and not new_field.primary_key:
self._delete_primary_key(model, strict)
# Added a unique?
if self._unique_should_be_added(old_field, new_field):
self.execute(self._create_unique_sql(model, [new_field]))
# Added an index? Add an index if db_index switched to True or a unique
# constraint will no longer be used in lieu of an index. The following
# lines from the truth table show all True cases; the rest are False:
#
# old_field.db_index | old_field.unique | new_field.db_index | new_field.unique
# ------------------------------------------------------------------------------
# False | False | True | False
# False | True | True | False
# True | True | True | False
if (
(not old_field.db_index or old_field.unique)
and new_field.db_index
and not new_field.unique
):
self.execute(self._create_index_sql(model, fields=[new_field]))
# Type alteration on primary key? Then we need to alter the column
# referring to us.
rels_to_update = []
if drop_foreign_keys:
rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
# Changed to become primary key?
if self._field_became_primary_key(old_field, new_field):
# Make the new one
self.execute(self._create_primary_key_sql(model, new_field))
# Update all referencing columns
rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
# Handle our type alters on the other end of rels from the PK stuff above
for old_rel, new_rel in rels_to_update:
rel_db_params = new_rel.field.db_parameters(connection=self.connection)
rel_type = rel_db_params["type"]
rel_collation = rel_db_params.get("collation")
old_rel_db_params = old_rel.field.db_parameters(connection=self.connection)
old_rel_collation = old_rel_db_params.get("collation")
if old_rel_collation != rel_collation:
# Collation change handles also a type change.
fragment = self._alter_column_collation_sql(
new_rel.related_model,
new_rel.field,
rel_type,
rel_collation,
old_rel.field,
)
other_actions = []
else:
fragment, other_actions = self._alter_column_type_sql(
new_rel.related_model, old_rel.field, new_rel.field, rel_type
)
self.execute(
self.sql_alter_column
% {
"table": self.quote_name(new_rel.related_model._meta.db_table),
"changes": fragment[0],
},
fragment[1],
)
for sql, params in other_actions:
self.execute(sql, params)
# Does it have a foreign key?
if (
self.connection.features.supports_foreign_keys
and new_field.remote_field
and (
fks_dropped or not old_field.remote_field or not old_field.db_constraint
)
and new_field.db_constraint
):
self.execute(
self._create_fk_sql(model, new_field, "_fk_%(to_table)s_%(to_column)s")
)
# Rebuild FKs that pointed to us if we previously had to drop them
if drop_foreign_keys:
for _, rel in rels_to_update:
if rel.field.db_constraint:
self.execute(
self._create_fk_sql(rel.related_model, rel.field, "_fk")
)
# Does it have check constraints we need to add?
if old_db_params["check"] != new_db_params["check"] and new_db_params["check"]:
constraint_name = self._create_index_name(
model._meta.db_table, [new_field.column], suffix="_check"
)
self.execute(
self._create_check_sql(model, constraint_name, new_db_params["check"])
)
# Drop the default if we need to
# (Django usually does not use in-database defaults)
if needs_database_default:
changes_sql, params = self._alter_column_default_sql(
model, old_field, new_field, drop=True
)
sql = self.sql_alter_column % {
"table": self.quote_name(model._meta.db_table),
"changes": changes_sql,
}
self.execute(sql, params)
# Reset connection if required
if self.connection.features.connection_persists_old_columns:
self.connection.close()
def _alter_column_null_sql(self, model, old_field, new_field):
"""
Hook to specialize column null alteration.
Return a (sql, params) fragment to set a column to null or non-null
as required by new_field, or None if no changes are required.
"""
if (
self.connection.features.interprets_empty_strings_as_nulls
and new_field.empty_strings_allowed
):
# The field is nullable in the database anyway, leave it alone.
return
else:
new_db_params = new_field.db_parameters(connection=self.connection)
sql = (
self.sql_alter_column_null
if new_field.null
else self.sql_alter_column_not_null
)
return (
sql
% {
"column": self.quote_name(new_field.column),
"type": new_db_params["type"],
},
[],
)
def _alter_column_default_sql(self, model, old_field, new_field, drop=False):
"""
Hook to specialize column default alteration.
Return a (sql, params) fragment to add or drop (depending on the drop
argument) a default to new_field's column.
"""
new_default = self.effective_default(new_field)
default = self._column_default_sql(new_field)
params = [new_default]
if drop:
params = []
elif self.connection.features.requires_literal_defaults:
# Some databases (Oracle) can't take defaults as a parameter
# If this is the case, the SchemaEditor for that database should
# implement prepare_default().
default = self.prepare_default(new_default)
params = []
new_db_params = new_field.db_parameters(connection=self.connection)
if drop:
if new_field.null:
sql = self.sql_alter_column_no_default_null
else:
sql = self.sql_alter_column_no_default
else:
sql = self.sql_alter_column_default
return (
sql
% {
"column": self.quote_name(new_field.column),
"type": new_db_params["type"],
"default": default,
},
params,
)
def _alter_column_type_sql(self, model, old_field, new_field, new_type):
"""
Hook to specialize column type alteration for different backends,
for cases when a creation type is different to an alteration type
(e.g. SERIAL in PostgreSQL, PostGIS fields).
Return a two-tuple of: an SQL fragment of (sql, params) to insert into
an ALTER TABLE statement and a list of extra (sql, params) tuples to
run once the field is altered.
"""
return (
(
self.sql_alter_column_type
% {
"column": self.quote_name(new_field.column),
"type": new_type,
},
[],
),
[],
)
def _alter_column_collation_sql(
self, model, new_field, new_type, new_collation, old_field
):
return (
self.sql_alter_column_collate
% {
"column": self.quote_name(new_field.column),
"type": new_type,
"collation": " " + self._collate_sql(new_collation)
if new_collation
else "",
},
[],
)
def _alter_many_to_many(self, model, old_field, new_field, strict):
"""Alter M2Ms to repoint their to= endpoints."""
# Rename the through table
if (
old_field.remote_field.through._meta.db_table
!= new_field.remote_field.through._meta.db_table
):
self.alter_db_table(
old_field.remote_field.through,
old_field.remote_field.through._meta.db_table,
new_field.remote_field.through._meta.db_table,
)
# Repoint the FK to the other side
self.alter_field(
new_field.remote_field.through,
# The field that points to the target model is needed, so we can
# tell alter_field to change it - this is m2m_reverse_field_name()
# (as opposed to m2m_field_name(), which points to our model).
old_field.remote_field.through._meta.get_field(
old_field.m2m_reverse_field_name()
),
new_field.remote_field.through._meta.get_field(
new_field.m2m_reverse_field_name()
),
)
self.alter_field(
new_field.remote_field.through,
# for self-referential models we need to alter field from the other end too
old_field.remote_field.through._meta.get_field(old_field.m2m_field_name()),
new_field.remote_field.through._meta.get_field(new_field.m2m_field_name()),
)
def _create_index_name(self, table_name, column_names, suffix=""):
"""
Generate a unique name for an index/unique constraint.
The name is divided into 3 parts: the table name, the column names,
and a unique digest and suffix.
"""
_, table_name = split_identifier(table_name)
hash_suffix_part = "%s%s" % (
names_digest(table_name, *column_names, length=8),
suffix,
)
max_length = self.connection.ops.max_name_length() or 200
# If everything fits into max_length, use that name.
index_name = "%s_%s_%s" % (table_name, "_".join(column_names), hash_suffix_part)
if len(index_name) <= max_length:
return index_name
# Shorten a long suffix.
if len(hash_suffix_part) > max_length / 3:
hash_suffix_part = hash_suffix_part[: max_length // 3]
other_length = (max_length - len(hash_suffix_part)) // 2 - 1
index_name = "%s_%s_%s" % (
table_name[:other_length],
"_".join(column_names)[:other_length],
hash_suffix_part,
)
# Prepend D if needed to prevent the name from starting with an
# underscore or a number (not permitted on Oracle).
if index_name[0] == "_" or index_name[0].isdigit():
index_name = "D%s" % index_name[:-1]
return index_name
def _get_index_tablespace_sql(self, model, fields, db_tablespace=None):
if db_tablespace is None:
if len(fields) == 1 and fields[0].db_tablespace:
db_tablespace = fields[0].db_tablespace
elif settings.DEFAULT_INDEX_TABLESPACE:
db_tablespace = settings.DEFAULT_INDEX_TABLESPACE
elif model._meta.db_tablespace:
db_tablespace = model._meta.db_tablespace
if db_tablespace is not None:
return " " + self.connection.ops.tablespace_sql(db_tablespace)
return ""
def _index_condition_sql(self, condition):
if condition:
return " WHERE " + condition
return ""
def _index_include_sql(self, model, columns):
if not columns or not self.connection.features.supports_covering_indexes:
return ""
return Statement(
" INCLUDE (%(columns)s)",
columns=Columns(model._meta.db_table, columns, self.quote_name),
)
def _create_index_sql(
self,
model,
*,
fields=None,
name=None,
suffix="",
using="",
db_tablespace=None,
col_suffixes=(),
sql=None,
opclasses=(),
condition=None,
include=None,
expressions=None,
):
"""
Return the SQL statement to create the index for one or several fields
or expressions. `sql` can be specified if the syntax differs from the
standard (GIS indexes, ...).
"""
fields = fields or []
expressions = expressions or []
compiler = Query(model, alias_cols=False).get_compiler(
connection=self.connection,
)
tablespace_sql = self._get_index_tablespace_sql(
model, fields, db_tablespace=db_tablespace
)
columns = [field.column for field in fields]
sql_create_index = sql or self.sql_create_index
table = model._meta.db_table
def create_index_name(*args, **kwargs):
nonlocal name
if name is None:
name = self._create_index_name(*args, **kwargs)
return self.quote_name(name)
return Statement(
sql_create_index,
table=Table(table, self.quote_name),
name=IndexName(table, columns, suffix, create_index_name),
using=using,
columns=(
self._index_columns(table, columns, col_suffixes, opclasses)
if columns
else Expressions(table, expressions, compiler, self.quote_value)
),
extra=tablespace_sql,
condition=self._index_condition_sql(condition),
include=self._index_include_sql(model, include),
)
def _delete_index_sql(self, model, name, sql=None):
return Statement(
sql or self.sql_delete_index,
table=Table(model._meta.db_table, self.quote_name),
name=self.quote_name(name),
)
def _rename_index_sql(self, model, old_name, new_name):
return Statement(
self.sql_rename_index,
table=Table(model._meta.db_table, self.quote_name),
old_name=self.quote_name(old_name),
new_name=self.quote_name(new_name),
)
def _index_columns(self, table, columns, col_suffixes, opclasses):
return Columns(table, columns, self.quote_name, col_suffixes=col_suffixes)
def _model_indexes_sql(self, model):
"""
Return a list of all index SQL statements (field indexes,
index_together, Meta.indexes) for the specified model.
"""
if not model._meta.managed or model._meta.proxy or model._meta.swapped:
return []
output = []
for field in model._meta.local_fields:
output.extend(self._field_indexes_sql(model, field))
for field_names in model._meta.index_together:
fields = [model._meta.get_field(field) for field in field_names]
output.append(self._create_index_sql(model, fields=fields, suffix="_idx"))
for index in model._meta.indexes:
if (
not index.contains_expressions
or self.connection.features.supports_expression_indexes
):
output.append(index.create_sql(model, self))
return output
def _field_indexes_sql(self, model, field):
"""
Return a list of all index SQL statements for the specified field.
"""
output = []
if self._field_should_be_indexed(model, field):
output.append(self._create_index_sql(model, fields=[field]))
return output
def _field_should_be_altered(self, old_field, new_field):
_, old_path, old_args, old_kwargs = old_field.deconstruct()
_, new_path, new_args, new_kwargs = new_field.deconstruct()
# Don't alter when:
# - changing only a field name
# - changing an attribute that doesn't affect the schema
# - adding only a db_column and the column name is not changed
for attr in old_field.non_db_attrs:
old_kwargs.pop(attr, None)
for attr in new_field.non_db_attrs:
new_kwargs.pop(attr, None)
return self.quote_name(old_field.column) != self.quote_name(
new_field.column
) or (old_path, old_args, old_kwargs) != (new_path, new_args, new_kwargs)
def _field_should_be_indexed(self, model, field):
return field.db_index and not field.unique
def _field_became_primary_key(self, old_field, new_field):
return not old_field.primary_key and new_field.primary_key
def _unique_should_be_added(self, old_field, new_field):
return (
not new_field.primary_key
and new_field.unique
and (not old_field.unique or old_field.primary_key)
)
def _rename_field_sql(self, table, old_field, new_field, new_type):
return self.sql_rename_column % {
"table": self.quote_name(table),
"old_column": self.quote_name(old_field.column),
"new_column": self.quote_name(new_field.column),
"type": new_type,
}
def _create_fk_sql(self, model, field, suffix):
table = Table(model._meta.db_table, self.quote_name)
name = self._fk_constraint_name(model, field, suffix)
column = Columns(model._meta.db_table, [field.column], self.quote_name)
to_table = Table(field.target_field.model._meta.db_table, self.quote_name)
to_column = Columns(
field.target_field.model._meta.db_table,
[field.target_field.column],
self.quote_name,
)
deferrable = self.connection.ops.deferrable_sql()
return Statement(
self.sql_create_fk,
table=table,
name=name,
column=column,
to_table=to_table,
to_column=to_column,
deferrable=deferrable,
)
def _fk_constraint_name(self, model, field, suffix):
def create_fk_name(*args, **kwargs):
return self.quote_name(self._create_index_name(*args, **kwargs))
return ForeignKeyName(
model._meta.db_table,
[field.column],
split_identifier(field.target_field.model._meta.db_table)[1],
[field.target_field.column],
suffix,
create_fk_name,
)
def _delete_fk_sql(self, model, name):
return self._delete_constraint_sql(self.sql_delete_fk, model, name)
def _deferrable_constraint_sql(self, deferrable):
if deferrable is None:
return ""
if deferrable == Deferrable.DEFERRED:
return " DEFERRABLE INITIALLY DEFERRED"
if deferrable == Deferrable.IMMEDIATE:
return " DEFERRABLE INITIALLY IMMEDIATE"
def _unique_sql(
self,
model,
fields,
name,
condition=None,
deferrable=None,
include=None,
opclasses=None,
expressions=None,
):
if (
deferrable
and not self.connection.features.supports_deferrable_unique_constraints
):
return None
if condition or include or opclasses or expressions:
# Databases support conditional, covering, and functional unique
# constraints via a unique index.
sql = self._create_unique_sql(
model,
fields,
name=name,
condition=condition,
include=include,
opclasses=opclasses,
expressions=expressions,
)
if sql:
self.deferred_sql.append(sql)
return None
constraint = self.sql_unique_constraint % {
"columns": ", ".join([self.quote_name(field.column) for field in fields]),
"deferrable": self._deferrable_constraint_sql(deferrable),
}
return self.sql_constraint % {
"name": self.quote_name(name),
"constraint": constraint,
}
def _create_unique_sql(
self,
model,
fields,
name=None,
condition=None,
deferrable=None,
include=None,
opclasses=None,
expressions=None,
):
if (
(
deferrable
and not self.connection.features.supports_deferrable_unique_constraints
)
or (condition and not self.connection.features.supports_partial_indexes)
or (include and not self.connection.features.supports_covering_indexes)
or (
expressions and not self.connection.features.supports_expression_indexes
)
):
return None
compiler = Query(model, alias_cols=False).get_compiler(
connection=self.connection
)
table = model._meta.db_table
columns = [field.column for field in fields]
if name is None:
name = self._unique_constraint_name(table, columns, quote=True)
else:
name = self.quote_name(name)
if condition or include or opclasses or expressions:
sql = self.sql_create_unique_index
else:
sql = self.sql_create_unique
if columns:
columns = self._index_columns(
table, columns, col_suffixes=(), opclasses=opclasses
)
else:
columns = Expressions(table, expressions, compiler, self.quote_value)
return Statement(
sql,
table=Table(table, self.quote_name),
name=name,
columns=columns,
condition=self._index_condition_sql(condition),
deferrable=self._deferrable_constraint_sql(deferrable),
include=self._index_include_sql(model, include),
)
def _unique_constraint_name(self, table, columns, quote=True):
if quote:
def create_unique_name(*args, **kwargs):
return self.quote_name(self._create_index_name(*args, **kwargs))
else:
create_unique_name = self._create_index_name
return IndexName(table, columns, "_uniq", create_unique_name)
def _delete_unique_sql(
self,
model,
name,
condition=None,
deferrable=None,
include=None,
opclasses=None,
expressions=None,
):
if (
(
deferrable
and not self.connection.features.supports_deferrable_unique_constraints
)
or (condition and not self.connection.features.supports_partial_indexes)
or (include and not self.connection.features.supports_covering_indexes)
or (
expressions and not self.connection.features.supports_expression_indexes
)
):
return None
if condition or include or opclasses or expressions:
sql = self.sql_delete_index
else:
sql = self.sql_delete_unique
return self._delete_constraint_sql(sql, model, name)
def _check_sql(self, name, check):
return self.sql_constraint % {
"name": self.quote_name(name),
"constraint": self.sql_check_constraint % {"check": check},
}
def _create_check_sql(self, model, name, check):
return Statement(
self.sql_create_check,
table=Table(model._meta.db_table, self.quote_name),
name=self.quote_name(name),
check=check,
)
def _delete_check_sql(self, model, name):
return self._delete_constraint_sql(self.sql_delete_check, model, name)
def _delete_constraint_sql(self, template, model, name):
return Statement(
template,
table=Table(model._meta.db_table, self.quote_name),
name=self.quote_name(name),
)
def _constraint_names(
self,
model,
column_names=None,
unique=None,
primary_key=None,
index=None,
foreign_key=None,
check=None,
type_=None,
exclude=None,
):
"""Return all constraint names matching the columns and conditions."""
if column_names is not None:
column_names = [
self.connection.introspection.identifier_converter(name)
for name in column_names
]
with self.connection.cursor() as cursor:
constraints = self.connection.introspection.get_constraints(
cursor, model._meta.db_table
)
result = []
for name, infodict in constraints.items():
if column_names is None or column_names == infodict["columns"]:
if unique is not None and infodict["unique"] != unique:
continue
if primary_key is not None and infodict["primary_key"] != primary_key:
continue
if index is not None and infodict["index"] != index:
continue
if check is not None and infodict["check"] != check:
continue
if foreign_key is not None and not infodict["foreign_key"]:
continue
if type_ is not None and infodict["type"] != type_:
continue
if not exclude or name not in exclude:
result.append(name)
return result
def _delete_primary_key(self, model, strict=False):
constraint_names = self._constraint_names(model, primary_key=True)
if strict and len(constraint_names) != 1:
raise ValueError(
"Found wrong number (%s) of PK constraints for %s"
% (
len(constraint_names),
model._meta.db_table,
)
)
for constraint_name in constraint_names:
self.execute(self._delete_primary_key_sql(model, constraint_name))
def _create_primary_key_sql(self, model, field):
return Statement(
self.sql_create_pk,
table=Table(model._meta.db_table, self.quote_name),
name=self.quote_name(
self._create_index_name(
model._meta.db_table, [field.column], suffix="_pk"
)
),
columns=Columns(model._meta.db_table, [field.column], self.quote_name),
)
def _delete_primary_key_sql(self, model, name):
return self._delete_constraint_sql(self.sql_delete_pk, model, name)
def _collate_sql(self, collation):
return "COLLATE " + self.quote_name(collation)
def remove_procedure(self, procedure_name, param_types=()):
sql = self.sql_delete_procedure % {
"procedure": self.quote_name(procedure_name),
"param_types": ",".join(param_types),
}
self.execute(sql)
|
7bc2ac3d58aae782ef07c55c094721acfe5a8eb41c938a6a2fd6f7bd5f19ffdc | import operator
from django.db.backends.base.features import BaseDatabaseFeatures
from django.utils.functional import cached_property
class DatabaseFeatures(BaseDatabaseFeatures):
empty_fetchmany_value = ()
allows_group_by_pk = True
related_fields_match_type = True
# MySQL doesn't support sliced subqueries with IN/ALL/ANY/SOME.
allow_sliced_subqueries_with_in = False
has_select_for_update = True
supports_forward_references = False
supports_regex_backreferencing = False
supports_date_lookup_using_string = False
supports_timezones = False
requires_explicit_null_ordering_when_grouping = True
can_release_savepoints = True
atomic_transactions = False
can_clone_databases = True
supports_temporal_subtraction = True
supports_select_intersection = False
supports_select_difference = False
supports_slicing_ordering_in_compound = True
supports_index_on_text_field = False
supports_update_conflicts = True
create_test_procedure_without_params_sql = """
CREATE PROCEDURE test_procedure ()
BEGIN
DECLARE V_I INTEGER;
SET V_I = 1;
END;
"""
create_test_procedure_with_int_param_sql = """
CREATE PROCEDURE test_procedure (P_I INTEGER)
BEGIN
DECLARE V_I INTEGER;
SET V_I = P_I;
END;
"""
create_test_table_with_composite_primary_key = """
CREATE TABLE test_table_composite_pk (
column_1 INTEGER NOT NULL,
column_2 INTEGER NOT NULL,
PRIMARY KEY(column_1, column_2)
)
"""
# Neither MySQL nor MariaDB support partial indexes.
supports_partial_indexes = False
# COLLATE must be wrapped in parentheses because MySQL treats COLLATE as an
# indexed expression.
collate_as_index_expression = True
supports_order_by_nulls_modifier = False
order_by_nulls_first = True
supports_logical_xor = True
@cached_property
def minimum_database_version(self):
if self.connection.mysql_is_mariadb:
return (10, 4)
else:
return (8,)
@cached_property
def test_collations(self):
charset = "utf8"
if (
self.connection.mysql_is_mariadb
and self.connection.mysql_version >= (10, 6)
) or (
not self.connection.mysql_is_mariadb
and self.connection.mysql_version >= (8, 0, 30)
):
# utf8 is an alias for utf8mb3 in MariaDB 10.6+ and MySQL 8.0.30+.
charset = "utf8mb3"
return {
"ci": f"{charset}_general_ci",
"non_default": f"{charset}_esperanto_ci",
"swedish_ci": f"{charset}_swedish_ci",
}
test_now_utc_template = "UTC_TIMESTAMP"
@cached_property
def django_test_skips(self):
skips = {
"This doesn't work on MySQL.": {
"db_functions.comparison.test_greatest.GreatestTests."
"test_coalesce_workaround",
"db_functions.comparison.test_least.LeastTests."
"test_coalesce_workaround",
},
"Running on MySQL requires utf8mb4 encoding (#18392).": {
"model_fields.test_textfield.TextFieldTests.test_emoji",
"model_fields.test_charfield.TestCharField.test_emoji",
},
"MySQL doesn't support functional indexes on a function that "
"returns JSON": {
"schema.tests.SchemaTests.test_func_index_json_key_transform",
},
"MySQL supports multiplying and dividing DurationFields by a "
"scalar value but it's not implemented (#25287).": {
"expressions.tests.FTimeDeltaTests.test_durationfield_multiply_divide",
},
"UPDATE ... ORDER BY syntax on MySQL/MariaDB does not support ordering by"
"related fields.": {
"update.tests.AdvancedTests."
"test_update_ordered_by_inline_m2m_annotation",
"update.tests.AdvancedTests.test_update_ordered_by_m2m_annotation",
},
}
if "ONLY_FULL_GROUP_BY" in self.connection.sql_mode:
skips.update(
{
"GROUP BY optimization does not work properly when "
"ONLY_FULL_GROUP_BY mode is enabled on MySQL, see #31331.": {
"aggregation.tests.AggregateTestCase."
"test_aggregation_subquery_annotation_multivalued",
"annotations.tests.NonAggregateAnnotationTestCase."
"test_annotation_aggregate_with_m2o",
},
}
)
if self.connection.mysql_is_mariadb and (
10,
4,
3,
) < self.connection.mysql_version < (10, 5, 2):
skips.update(
{
"https://jira.mariadb.org/browse/MDEV-19598": {
"schema.tests.SchemaTests."
"test_alter_not_unique_field_to_primary_key",
},
}
)
if self.connection.mysql_is_mariadb and (
10,
4,
12,
) < self.connection.mysql_version < (10, 5):
skips.update(
{
"https://jira.mariadb.org/browse/MDEV-22775": {
"schema.tests.SchemaTests."
"test_alter_pk_with_self_referential_field",
},
}
)
if not self.supports_explain_analyze:
skips.update(
{
"MariaDB and MySQL >= 8.0.18 specific.": {
"queries.test_explain.ExplainTests.test_mysql_analyze",
},
}
)
return skips
@cached_property
def _mysql_storage_engine(self):
"Internal method used in Django tests. Don't rely on this from your code"
return self.connection.mysql_server_data["default_storage_engine"]
@cached_property
def allows_auto_pk_0(self):
"""
Autoincrement primary key can be set to 0 if it doesn't generate new
autoincrement values.
"""
return "NO_AUTO_VALUE_ON_ZERO" in self.connection.sql_mode
@cached_property
def update_can_self_select(self):
return self.connection.mysql_is_mariadb and self.connection.mysql_version >= (
10,
3,
2,
)
@cached_property
def can_introspect_foreign_keys(self):
"Confirm support for introspected foreign keys"
return self._mysql_storage_engine != "MyISAM"
@cached_property
def introspected_field_types(self):
return {
**super().introspected_field_types,
"BinaryField": "TextField",
"BooleanField": "IntegerField",
"DurationField": "BigIntegerField",
"GenericIPAddressField": "CharField",
}
@cached_property
def can_return_columns_from_insert(self):
return self.connection.mysql_is_mariadb and self.connection.mysql_version >= (
10,
5,
0,
)
can_return_rows_from_bulk_insert = property(
operator.attrgetter("can_return_columns_from_insert")
)
@cached_property
def has_zoneinfo_database(self):
return self.connection.mysql_server_data["has_zoneinfo_database"]
@cached_property
def is_sql_auto_is_null_enabled(self):
return self.connection.mysql_server_data["sql_auto_is_null"]
@cached_property
def supports_over_clause(self):
if self.connection.mysql_is_mariadb:
return True
return self.connection.mysql_version >= (8, 0, 2)
supports_frame_range_fixed_distance = property(
operator.attrgetter("supports_over_clause")
)
@cached_property
def supports_column_check_constraints(self):
if self.connection.mysql_is_mariadb:
return True
return self.connection.mysql_version >= (8, 0, 16)
supports_table_check_constraints = property(
operator.attrgetter("supports_column_check_constraints")
)
@cached_property
def can_introspect_check_constraints(self):
if self.connection.mysql_is_mariadb:
return True
return self.connection.mysql_version >= (8, 0, 16)
@cached_property
def has_select_for_update_skip_locked(self):
if self.connection.mysql_is_mariadb:
return self.connection.mysql_version >= (10, 6)
return self.connection.mysql_version >= (8, 0, 1)
@cached_property
def has_select_for_update_nowait(self):
if self.connection.mysql_is_mariadb:
return True
return self.connection.mysql_version >= (8, 0, 1)
@cached_property
def has_select_for_update_of(self):
return (
not self.connection.mysql_is_mariadb
and self.connection.mysql_version >= (8, 0, 1)
)
@cached_property
def supports_explain_analyze(self):
return self.connection.mysql_is_mariadb or self.connection.mysql_version >= (
8,
0,
18,
)
@cached_property
def supported_explain_formats(self):
# Alias MySQL's TRADITIONAL to TEXT for consistency with other
# backends.
formats = {"JSON", "TEXT", "TRADITIONAL"}
if not self.connection.mysql_is_mariadb and self.connection.mysql_version >= (
8,
0,
16,
):
formats.add("TREE")
return formats
@cached_property
def supports_transactions(self):
"""
All storage engines except MyISAM support transactions.
"""
return self._mysql_storage_engine != "MyISAM"
uses_savepoints = property(operator.attrgetter("supports_transactions"))
can_release_savepoints = property(operator.attrgetter("supports_transactions"))
@cached_property
def ignores_table_name_case(self):
return self.connection.mysql_server_data["lower_case_table_names"]
@cached_property
def supports_default_in_lead_lag(self):
# To be added in https://jira.mariadb.org/browse/MDEV-12981.
return not self.connection.mysql_is_mariadb
@cached_property
def can_introspect_json_field(self):
if self.connection.mysql_is_mariadb:
return self.can_introspect_check_constraints
return True
@cached_property
def supports_index_column_ordering(self):
if self._mysql_storage_engine != "InnoDB":
return False
if self.connection.mysql_is_mariadb:
return self.connection.mysql_version >= (10, 8)
return self.connection.mysql_version >= (8, 0, 1)
@cached_property
def supports_expression_indexes(self):
return (
not self.connection.mysql_is_mariadb
and self._mysql_storage_engine != "MyISAM"
and self.connection.mysql_version >= (8, 0, 13)
)
@cached_property
def can_rename_index(self):
if self.connection.mysql_is_mariadb:
return self.connection.mysql_version >= (10, 5, 2)
return True
|
056f6e2c43460756ee28891980041267b84418332196ae742ac1d426503feec9 | import psycopg2
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.backends.ddl_references import IndexColumns
from django.db.backends.utils import strip_quotes
class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
# Setting all constraints to IMMEDIATE to allow changing data in the same
# transaction.
sql_update_with_default = (
"UPDATE %(table)s SET %(column)s = %(default)s WHERE %(column)s IS NULL"
"; SET CONSTRAINTS ALL IMMEDIATE"
)
sql_delete_sequence = "DROP SEQUENCE IF EXISTS %(sequence)s CASCADE"
sql_create_index = (
"CREATE INDEX %(name)s ON %(table)s%(using)s "
"(%(columns)s)%(include)s%(extra)s%(condition)s"
)
sql_create_index_concurrently = (
"CREATE INDEX CONCURRENTLY %(name)s ON %(table)s%(using)s "
"(%(columns)s)%(include)s%(extra)s%(condition)s"
)
sql_delete_index = "DROP INDEX IF EXISTS %(name)s"
sql_delete_index_concurrently = "DROP INDEX CONCURRENTLY IF EXISTS %(name)s"
# Setting the constraint to IMMEDIATE to allow changing data in the same
# transaction.
sql_create_column_inline_fk = (
"CONSTRAINT %(name)s REFERENCES %(to_table)s(%(to_column)s)%(deferrable)s"
"; SET CONSTRAINTS %(namespace)s%(name)s IMMEDIATE"
)
# Setting the constraint to IMMEDIATE runs any deferred checks to allow
# dropping it in the same transaction.
sql_delete_fk = (
"SET CONSTRAINTS %(name)s IMMEDIATE; "
"ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
)
sql_delete_procedure = "DROP FUNCTION %(procedure)s(%(param_types)s)"
sql_add_identity = (
"ALTER TABLE %(table)s ALTER COLUMN %(column)s ADD "
"GENERATED BY DEFAULT AS IDENTITY"
)
sql_drop_indentity = (
"ALTER TABLE %(table)s ALTER COLUMN %(column)s DROP IDENTITY IF EXISTS"
)
def quote_value(self, value):
if isinstance(value, str):
value = value.replace("%", "%%")
adapted = psycopg2.extensions.adapt(value)
if hasattr(adapted, "encoding"):
adapted.encoding = "utf8"
# getquoted() returns a quoted bytestring of the adapted value.
return adapted.getquoted().decode()
def _field_indexes_sql(self, model, field):
output = super()._field_indexes_sql(model, field)
like_index_statement = self._create_like_index_sql(model, field)
if like_index_statement is not None:
output.append(like_index_statement)
return output
def _field_data_type(self, field):
if field.is_relation:
return field.rel_db_type(self.connection)
return self.connection.data_types.get(
field.get_internal_type(),
field.db_type(self.connection),
)
def _field_base_data_types(self, field):
# Yield base data types for array fields.
if field.base_field.get_internal_type() == "ArrayField":
yield from self._field_base_data_types(field.base_field)
else:
yield self._field_data_type(field.base_field)
def _create_like_index_sql(self, model, field):
"""
Return the statement to create an index with varchar operator pattern
when the column type is 'varchar' or 'text', otherwise return None.
"""
db_type = field.db_type(connection=self.connection)
if db_type is not None and (field.db_index or field.unique):
# Fields with database column types of `varchar` and `text` need
# a second index that specifies their operator class, which is
# needed when performing correct LIKE queries outside the
# C locale. See #12234.
#
# The same doesn't apply to array fields such as varchar[size]
# and text[size], so skip them.
if "[" in db_type:
return None
if db_type.startswith("varchar"):
return self._create_index_sql(
model,
fields=[field],
suffix="_like",
opclasses=["varchar_pattern_ops"],
)
elif db_type.startswith("text"):
return self._create_index_sql(
model,
fields=[field],
suffix="_like",
opclasses=["text_pattern_ops"],
)
return None
def _using_sql(self, new_field, old_field):
using_sql = " USING %(column)s::%(type)s"
new_internal_type = new_field.get_internal_type()
old_internal_type = old_field.get_internal_type()
if new_internal_type == "ArrayField" and new_internal_type == old_internal_type:
# Compare base data types for array fields.
if list(self._field_base_data_types(old_field)) != list(
self._field_base_data_types(new_field)
):
return using_sql
elif self._field_data_type(old_field) != self._field_data_type(new_field):
return using_sql
return ""
def _alter_column_type_sql(self, model, old_field, new_field, new_type):
self.sql_alter_column_type = "ALTER COLUMN %(column)s TYPE %(type)s"
# Cast when data type changed.
if using_sql := self._using_sql(new_field, old_field):
self.sql_alter_column_type += using_sql
new_internal_type = new_field.get_internal_type()
old_internal_type = old_field.get_internal_type()
# Make ALTER TYPE with IDENTITY make sense.
table = strip_quotes(model._meta.db_table)
auto_field_types = {
"AutoField",
"BigAutoField",
"SmallAutoField",
}
old_is_auto = old_internal_type in auto_field_types
new_is_auto = new_internal_type in auto_field_types
if new_is_auto and not old_is_auto:
column = strip_quotes(new_field.column)
return (
(
self.sql_alter_column_type
% {
"column": self.quote_name(column),
"type": new_type,
},
[],
),
[
(
self.sql_add_identity
% {
"table": self.quote_name(table),
"column": self.quote_name(column),
},
[],
),
],
)
elif old_is_auto and not new_is_auto:
# Drop IDENTITY if exists (pre-Django 4.1 serial columns don't have
# it).
self.execute(
self.sql_drop_indentity
% {
"table": self.quote_name(table),
"column": self.quote_name(strip_quotes(old_field.column)),
}
)
column = strip_quotes(new_field.column)
sequence_name = "%s_%s_seq" % (table, column)
fragment, _ = super()._alter_column_type_sql(
model, old_field, new_field, new_type
)
return fragment, [
(
# Drop the sequence if exists (Django 4.1+ identity columns
# don't have it).
self.sql_delete_sequence
% {
"sequence": self.quote_name(sequence_name),
},
[],
),
]
else:
return super()._alter_column_type_sql(model, old_field, new_field, new_type)
def _alter_column_collation_sql(
self, model, new_field, new_type, new_collation, old_field
):
sql = self.sql_alter_column_collate
# Cast when data type changed.
if using_sql := self._using_sql(new_field, old_field):
sql += using_sql
return (
sql
% {
"column": self.quote_name(new_field.column),
"type": new_type,
"collation": " " + self._collate_sql(new_collation)
if new_collation
else "",
},
[],
)
def _alter_field(
self,
model,
old_field,
new_field,
old_type,
new_type,
old_db_params,
new_db_params,
strict=False,
):
# Drop indexes on varchar/text/citext columns that are changing to a
# different type.
if (old_field.db_index or old_field.unique) and (
(old_type.startswith("varchar") and not new_type.startswith("varchar"))
or (old_type.startswith("text") and not new_type.startswith("text"))
or (old_type.startswith("citext") and not new_type.startswith("citext"))
):
index_name = self._create_index_name(
model._meta.db_table, [old_field.column], suffix="_like"
)
self.execute(self._delete_index_sql(model, index_name))
super()._alter_field(
model,
old_field,
new_field,
old_type,
new_type,
old_db_params,
new_db_params,
strict,
)
# Added an index? Create any PostgreSQL-specific indexes.
if (not (old_field.db_index or old_field.unique) and new_field.db_index) or (
not old_field.unique and new_field.unique
):
like_index_statement = self._create_like_index_sql(model, new_field)
if like_index_statement is not None:
self.execute(like_index_statement)
# Removed an index? Drop any PostgreSQL-specific indexes.
if old_field.unique and not (new_field.db_index or new_field.unique):
index_to_remove = self._create_index_name(
model._meta.db_table, [old_field.column], suffix="_like"
)
self.execute(self._delete_index_sql(model, index_to_remove))
def _index_columns(self, table, columns, col_suffixes, opclasses):
if opclasses:
return IndexColumns(
table,
columns,
self.quote_name,
col_suffixes=col_suffixes,
opclasses=opclasses,
)
return super()._index_columns(table, columns, col_suffixes, opclasses)
def add_index(self, model, index, concurrently=False):
self.execute(
index.create_sql(model, self, concurrently=concurrently), params=None
)
def remove_index(self, model, index, concurrently=False):
self.execute(index.remove_sql(model, self, concurrently=concurrently))
def _delete_index_sql(self, model, name, sql=None, concurrently=False):
sql = (
self.sql_delete_index_concurrently
if concurrently
else self.sql_delete_index
)
return super()._delete_index_sql(model, name, sql)
def _create_index_sql(
self,
model,
*,
fields=None,
name=None,
suffix="",
using="",
db_tablespace=None,
col_suffixes=(),
sql=None,
opclasses=(),
condition=None,
concurrently=False,
include=None,
expressions=None,
):
sql = (
self.sql_create_index
if not concurrently
else self.sql_create_index_concurrently
)
return super()._create_index_sql(
model,
fields=fields,
name=name,
suffix=suffix,
using=using,
db_tablespace=db_tablespace,
col_suffixes=col_suffixes,
sql=sql,
opclasses=opclasses,
condition=condition,
include=include,
expressions=expressions,
)
|
3c8749c0a38c481e5bb1e2345a541a535b1a79be480963bd855697d5175c0774 | """
SQLite backend for the sqlite3 module in the standard library.
"""
import datetime
import decimal
import warnings
from itertools import chain
from sqlite3 import dbapi2 as Database
from django.core.exceptions import ImproperlyConfigured
from django.db import IntegrityError
from django.db.backends.base.base import BaseDatabaseWrapper
from django.utils.asyncio import async_unsafe
from django.utils.dateparse import parse_date, parse_datetime, parse_time
from django.utils.regex_helper import _lazy_re_compile
from ._functions import register as register_functions
from .client import DatabaseClient
from .creation import DatabaseCreation
from .features import DatabaseFeatures
from .introspection import DatabaseIntrospection
from .operations import DatabaseOperations
from .schema import DatabaseSchemaEditor
def decoder(conv_func):
"""
Convert bytestrings from Python's sqlite3 interface to a regular string.
"""
return lambda s: conv_func(s.decode())
def adapt_date(val):
return val.isoformat()
def adapt_datetime(val):
return val.isoformat(" ")
Database.register_converter("bool", b"1".__eq__)
Database.register_converter("date", decoder(parse_date))
Database.register_converter("time", decoder(parse_time))
Database.register_converter("datetime", decoder(parse_datetime))
Database.register_converter("timestamp", decoder(parse_datetime))
Database.register_adapter(decimal.Decimal, str)
Database.register_adapter(datetime.date, adapt_date)
Database.register_adapter(datetime.datetime, adapt_datetime)
class DatabaseWrapper(BaseDatabaseWrapper):
vendor = "sqlite"
display_name = "SQLite"
# SQLite doesn't actually support most of these types, but it "does the right
# thing" given more verbose field definitions, so leave them as is so that
# schema inspection is more useful.
data_types = {
"AutoField": "integer",
"BigAutoField": "integer",
"BinaryField": "BLOB",
"BooleanField": "bool",
"CharField": "varchar(%(max_length)s)",
"DateField": "date",
"DateTimeField": "datetime",
"DecimalField": "decimal",
"DurationField": "bigint",
"FileField": "varchar(%(max_length)s)",
"FilePathField": "varchar(%(max_length)s)",
"FloatField": "real",
"IntegerField": "integer",
"BigIntegerField": "bigint",
"IPAddressField": "char(15)",
"GenericIPAddressField": "char(39)",
"JSONField": "text",
"OneToOneField": "integer",
"PositiveBigIntegerField": "bigint unsigned",
"PositiveIntegerField": "integer unsigned",
"PositiveSmallIntegerField": "smallint unsigned",
"SlugField": "varchar(%(max_length)s)",
"SmallAutoField": "integer",
"SmallIntegerField": "smallint",
"TextField": "text",
"TimeField": "time",
"UUIDField": "char(32)",
}
data_type_check_constraints = {
"PositiveBigIntegerField": '"%(column)s" >= 0',
"JSONField": '(JSON_VALID("%(column)s") OR "%(column)s" IS NULL)',
"PositiveIntegerField": '"%(column)s" >= 0',
"PositiveSmallIntegerField": '"%(column)s" >= 0',
}
data_types_suffix = {
"AutoField": "AUTOINCREMENT",
"BigAutoField": "AUTOINCREMENT",
"SmallAutoField": "AUTOINCREMENT",
}
# SQLite requires LIKE statements to include an ESCAPE clause if the value
# being escaped has a percent or underscore in it.
# See https://www.sqlite.org/lang_expr.html for an explanation.
operators = {
"exact": "= %s",
"iexact": "LIKE %s ESCAPE '\\'",
"contains": "LIKE %s ESCAPE '\\'",
"icontains": "LIKE %s ESCAPE '\\'",
"regex": "REGEXP %s",
"iregex": "REGEXP '(?i)' || %s",
"gt": "> %s",
"gte": ">= %s",
"lt": "< %s",
"lte": "<= %s",
"startswith": "LIKE %s ESCAPE '\\'",
"endswith": "LIKE %s ESCAPE '\\'",
"istartswith": "LIKE %s ESCAPE '\\'",
"iendswith": "LIKE %s ESCAPE '\\'",
}
# The patterns below are used to generate SQL pattern lookup clauses when
# the right-hand side of the lookup isn't a raw string (it might be an expression
# or the result of a bilateral transformation).
# In those cases, special characters for LIKE operators (e.g. \, *, _) should be
# escaped on database side.
#
# Note: we use str.format() here for readability as '%' is used as a wildcard for
# the LIKE operator.
pattern_esc = r"REPLACE(REPLACE(REPLACE({}, '\', '\\'), '%%', '\%%'), '_', '\_')"
pattern_ops = {
"contains": r"LIKE '%%' || {} || '%%' ESCAPE '\'",
"icontains": r"LIKE '%%' || UPPER({}) || '%%' ESCAPE '\'",
"startswith": r"LIKE {} || '%%' ESCAPE '\'",
"istartswith": r"LIKE UPPER({}) || '%%' ESCAPE '\'",
"endswith": r"LIKE '%%' || {} ESCAPE '\'",
"iendswith": r"LIKE '%%' || UPPER({}) ESCAPE '\'",
}
Database = Database
SchemaEditorClass = DatabaseSchemaEditor
# Classes instantiated in __init__().
client_class = DatabaseClient
creation_class = DatabaseCreation
features_class = DatabaseFeatures
introspection_class = DatabaseIntrospection
ops_class = DatabaseOperations
def get_connection_params(self):
settings_dict = self.settings_dict
if not settings_dict["NAME"]:
raise ImproperlyConfigured(
"settings.DATABASES is improperly configured. "
"Please supply the NAME value."
)
kwargs = {
"database": settings_dict["NAME"],
"detect_types": Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES,
**settings_dict["OPTIONS"],
}
# Always allow the underlying SQLite connection to be shareable
# between multiple threads. The safe-guarding will be handled at a
# higher level by the `BaseDatabaseWrapper.allow_thread_sharing`
# property. This is necessary as the shareability is disabled by
# default in pysqlite and it cannot be changed once a connection is
# opened.
if "check_same_thread" in kwargs and kwargs["check_same_thread"]:
warnings.warn(
"The `check_same_thread` option was provided and set to "
"True. It will be overridden with False. Use the "
"`DatabaseWrapper.allow_thread_sharing` property instead "
"for controlling thread shareability.",
RuntimeWarning,
)
kwargs.update({"check_same_thread": False, "uri": True})
return kwargs
def get_database_version(self):
return self.Database.sqlite_version_info
@async_unsafe
def get_new_connection(self, conn_params):
conn = Database.connect(**conn_params)
register_functions(conn)
conn.execute("PRAGMA foreign_keys = ON")
# The macOS bundled SQLite defaults legacy_alter_table ON, which
# prevents atomic table renames (feature supports_atomic_references_rename)
conn.execute("PRAGMA legacy_alter_table = OFF")
return conn
def create_cursor(self, name=None):
return self.connection.cursor(factory=SQLiteCursorWrapper)
@async_unsafe
def close(self):
self.validate_thread_sharing()
# If database is in memory, closing the connection destroys the
# database. To prevent accidental data loss, ignore close requests on
# an in-memory db.
if not self.is_in_memory_db():
BaseDatabaseWrapper.close(self)
def _savepoint_allowed(self):
# When 'isolation_level' is not None, sqlite3 commits before each
# savepoint; it's a bug. When it is None, savepoints don't make sense
# because autocommit is enabled. The only exception is inside 'atomic'
# blocks. To work around that bug, on SQLite, 'atomic' starts a
# transaction explicitly rather than simply disable autocommit.
return self.in_atomic_block
def _set_autocommit(self, autocommit):
if autocommit:
level = None
else:
# sqlite3's internal default is ''. It's different from None.
# See Modules/_sqlite/connection.c.
level = ""
# 'isolation_level' is a misleading API.
# SQLite always runs at the SERIALIZABLE isolation level.
with self.wrap_database_errors:
self.connection.isolation_level = level
def disable_constraint_checking(self):
with self.cursor() as cursor:
cursor.execute("PRAGMA foreign_keys = OFF")
# Foreign key constraints cannot be turned off while in a multi-
# statement transaction. Fetch the current state of the pragma
# to determine if constraints are effectively disabled.
enabled = cursor.execute("PRAGMA foreign_keys").fetchone()[0]
return not bool(enabled)
def enable_constraint_checking(self):
with self.cursor() as cursor:
cursor.execute("PRAGMA foreign_keys = ON")
def check_constraints(self, table_names=None):
"""
Check each table name in `table_names` for rows with invalid foreign
key references. This method is intended to be used in conjunction with
`disable_constraint_checking()` and `enable_constraint_checking()`, to
determine if rows with invalid references were entered while constraint
checks were off.
"""
if self.features.supports_pragma_foreign_key_check:
with self.cursor() as cursor:
if table_names is None:
violations = cursor.execute("PRAGMA foreign_key_check").fetchall()
else:
violations = chain.from_iterable(
cursor.execute(
"PRAGMA foreign_key_check(%s)"
% self.ops.quote_name(table_name)
).fetchall()
for table_name in table_names
)
# See https://www.sqlite.org/pragma.html#pragma_foreign_key_check
for (
table_name,
rowid,
referenced_table_name,
foreign_key_index,
) in violations:
foreign_key = cursor.execute(
"PRAGMA foreign_key_list(%s)" % self.ops.quote_name(table_name)
).fetchall()[foreign_key_index]
column_name, referenced_column_name = foreign_key[3:5]
primary_key_column_name = self.introspection.get_primary_key_column(
cursor, table_name
)
primary_key_value, bad_value = cursor.execute(
"SELECT %s, %s FROM %s WHERE rowid = %%s"
% (
self.ops.quote_name(primary_key_column_name),
self.ops.quote_name(column_name),
self.ops.quote_name(table_name),
),
(rowid,),
).fetchone()
raise IntegrityError(
"The row in table '%s' with primary key '%s' has an "
"invalid foreign key: %s.%s contains a value '%s' that "
"does not have a corresponding value in %s.%s."
% (
table_name,
primary_key_value,
table_name,
column_name,
bad_value,
referenced_table_name,
referenced_column_name,
)
)
else:
with self.cursor() as cursor:
if table_names is None:
table_names = self.introspection.table_names(cursor)
for table_name in table_names:
primary_key_column_name = self.introspection.get_primary_key_column(
cursor, table_name
)
if not primary_key_column_name:
continue
relations = self.introspection.get_relations(cursor, table_name)
for column_name, (
referenced_column_name,
referenced_table_name,
) in relations:
cursor.execute(
"""
SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
LEFT JOIN `%s` as REFERRED
ON (REFERRING.`%s` = REFERRED.`%s`)
WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL
"""
% (
primary_key_column_name,
column_name,
table_name,
referenced_table_name,
column_name,
referenced_column_name,
column_name,
referenced_column_name,
)
)
for bad_row in cursor.fetchall():
raise IntegrityError(
"The row in table '%s' with primary key '%s' has an "
"invalid foreign key: %s.%s contains a value '%s' that "
"does not have a corresponding value in %s.%s."
% (
table_name,
bad_row[0],
table_name,
column_name,
bad_row[1],
referenced_table_name,
referenced_column_name,
)
)
def is_usable(self):
return True
def _start_transaction_under_autocommit(self):
"""
Start a transaction explicitly in autocommit mode.
Staying in autocommit mode works around a bug of sqlite3 that breaks
savepoints when autocommit is disabled.
"""
self.cursor().execute("BEGIN")
def is_in_memory_db(self):
return self.creation.is_in_memory_db(self.settings_dict["NAME"])
FORMAT_QMARK_REGEX = _lazy_re_compile(r"(?<!%)%s")
class SQLiteCursorWrapper(Database.Cursor):
"""
Django uses "format" style placeholders, but pysqlite2 uses "qmark" style.
This fixes it -- but note that if you want to use a literal "%s" in a query,
you'll need to use "%%s".
"""
def execute(self, query, params=None):
if params is None:
return Database.Cursor.execute(self, query)
query = self.convert_query(query)
return Database.Cursor.execute(self, query, params)
def executemany(self, query, param_list):
query = self.convert_query(query)
return Database.Cursor.executemany(self, query, param_list)
def convert_query(self, query):
return FORMAT_QMARK_REGEX.sub("?", query).replace("%%", "%")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.