Removed redundant QuerySet.all() calls in docs and tests.

Most QuerySet methods are mapped onto the Manager and, in general,
it isn't necessary to call .all() on the manager.
This commit is contained in:
Nick Pope 2022-02-22 09:29:38 +00:00 committed by GitHub
parent 7ba6ebe914
commit 847f46e9bf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
47 changed files with 184 additions and 209 deletions

View File

@ -156,7 +156,7 @@ the field value on multiple objects - which could be very much faster than
pulling them all into Python from the database, looping over them, incrementing
the field value of each one, and saving each one back to the database::
Reporter.objects.all().update(stories_filed=F('stories_filed') + 1)
Reporter.objects.update(stories_filed=F('stories_filed') + 1)
``F()`` therefore can offer performance advantages by:

View File

@ -1110,7 +1110,7 @@ item in the Pizza ``QuerySet``.
We can reduce to just two queries using ``prefetch_related``:
>>> Pizza.objects.all().prefetch_related('toppings')
>>> Pizza.objects.prefetch_related('toppings')
This implies a ``self.toppings.all()`` for each ``Pizza``; now each time
``self.toppings.all()`` is called, instead of having to go to the database for
@ -1648,7 +1648,7 @@ one, doing so will result in an error.
# Two equivalent QuerySets:
CommonlyUsedModel.objects.all()
ManagedModel.objects.all().defer('f2')
ManagedModel.objects.defer('f2')
If many fields need to be duplicated in the unmanaged model, it may be best
to create an abstract model with the shared fields and then have the
@ -3771,7 +3771,7 @@ as the string based lookups passed to
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
# This will only execute two queries regardless of the number of Question
# and Choice objects.
>>> Question.objects.prefetch_related(Prefetch('choice_set')).all()
>>> Question.objects.prefetch_related(Prefetch('choice_set'))
<QuerySet [<Question: What's up?>]>
The ``queryset`` argument supplies a base ``QuerySet`` for the given lookup.

View File

@ -56,12 +56,12 @@ above::
# Average price across all books.
>>> from django.db.models import Avg
>>> Book.objects.all().aggregate(Avg('price'))
>>> Book.objects.aggregate(Avg('price'))
{'price__avg': 34.35}
# Max price across all books.
>>> from django.db.models import Max
>>> Book.objects.all().aggregate(Max('price'))
>>> Book.objects.aggregate(Max('price'))
{'price__max': Decimal('81.20')}
# Difference between the highest priced book and the average price of all books.
@ -111,7 +111,7 @@ belong to this ``QuerySet``. This is done by appending an ``aggregate()``
clause onto the ``QuerySet``::
>>> from django.db.models import Avg
>>> Book.objects.all().aggregate(Avg('price'))
>>> Book.objects.aggregate(Avg('price'))
{'price__avg': 34.35}
The ``all()`` is redundant in this example, so this could be simplified to::

View File

@ -459,10 +459,10 @@ which you want to run the query. For example::
>>> Author.objects.all()
>>> # So will this.
>>> Author.objects.using('default').all()
>>> Author.objects.using('default')
>>> # This will run on the 'other' database.
>>> Author.objects.using('other').all()
>>> Author.objects.using('other')
Selecting a database for ``save()``
-----------------------------------

View File

@ -1327,7 +1327,7 @@ new value to be the new model instance you want to point to. For example::
>>> b = Blog.objects.get(pk=1)
# Change every Entry so that it belongs to this Blog.
>>> Entry.objects.all().update(blog=b)
>>> Entry.objects.update(blog=b)
The ``update()`` method is applied instantly and returns the number of rows
matched by the query (which may not be equal to the number of rows updated if
@ -1361,7 +1361,7 @@ update one field based on the value of another field in the model. This is
especially useful for incrementing counters based upon their current value. For
example, to increment the pingback count for every entry in the blog::
>>> Entry.objects.all().update(number_of_pingbacks=F('number_of_pingbacks') + 1)
>>> Entry.objects.update(number_of_pingbacks=F('number_of_pingbacks') + 1)
However, unlike ``F()`` objects in filter and exclude clauses, you can't
introduce joins when you use ``F()`` objects in an update -- you can only

View File

@ -113,7 +113,7 @@ class DepartmentListFilterLookupWithNonStringValue(SimpleListFilter):
employee.department.id, # Intentionally not a string (Refs #19318)
employee.department.code,
)
for employee in model_admin.get_queryset(request).all()
for employee in model_admin.get_queryset(request)
}
)
@ -1150,7 +1150,7 @@ class ListFiltersTests(TestCase):
# Make sure the correct queryset is returned
queryset = changelist.get_queryset(request)
self.assertEqual(list(queryset), list(Book.objects.all().order_by("-id")))
self.assertEqual(list(queryset), list(Book.objects.order_by("-id")))
# Make sure the correct choice is selected
filterspec = changelist.get_filters(request)[0][1]

View File

@ -1595,7 +1595,7 @@ class SeleniumTests(AdminSeleniumTestCase):
self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click()
# The objects have been created in the database.
self.assertEqual(Inner4Stacked.objects.all().count(), 4)
self.assertEqual(Inner4Stacked.objects.count(), 4)
def test_delete_invalid_tabular_inlines(self):
from selenium.common.exceptions import NoSuchElementException
@ -1664,7 +1664,7 @@ class SeleniumTests(AdminSeleniumTestCase):
self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click()
# The objects have been created in the database.
self.assertEqual(Inner4Tabular.objects.all().count(), 4)
self.assertEqual(Inner4Tabular.objects.count(), 4)
def test_add_inlines(self):
"""
@ -1750,8 +1750,8 @@ class SeleniumTests(AdminSeleniumTestCase):
self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click()
# The objects have been created in the database
self.assertEqual(ProfileCollection.objects.all().count(), 1)
self.assertEqual(Profile.objects.all().count(), 3)
self.assertEqual(ProfileCollection.objects.count(), 1)
self.assertEqual(Profile.objects.count(), 3)
def test_add_inline_link_absent_for_view_only_parent_model(self):
from selenium.common.exceptions import NoSuchElementException

View File

@ -190,7 +190,7 @@ class AdminActionsTest(TestCase):
)
# SubscriberAdmin.delete_queryset() sets overridden to True.
self.assertIs(SubscriberAdmin.overridden, True)
self.assertEqual(Subscriber.objects.all().count(), 0)
self.assertEqual(Subscriber.objects.count(), 0)
def test_delete_selected_uses_get_deleted_objects(self):
"""The delete_selected action uses ModelAdmin.get_deleted_objects()."""

View File

@ -1478,7 +1478,7 @@ class AdminCustomTemplateTests(AdminViewBasicTestCase):
self.assertRedirects(
post, reverse("admin:admin_views_customarticle_changelist")
)
self.assertEqual(CustomArticle.objects.all().count(), 1)
self.assertEqual(CustomArticle.objects.count(), 1)
article_pk = CustomArticle.objects.all()[0].pk
# Test custom delete, change, and object history templates
@ -5668,7 +5668,7 @@ class SeleniumTests(AdminSeleniumTestCase):
# Save and check that everything is properly stored in the database
with self.wait_page_loaded():
self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click()
self.assertEqual(MainPrepopulated.objects.all().count(), 1)
self.assertEqual(MainPrepopulated.objects.count(), 1)
MainPrepopulated.objects.get(
name=" the mAin nÀMë and it's awεšomeıııİ",
pubdate="2012-02-18",
@ -5677,7 +5677,7 @@ class SeleniumTests(AdminSeleniumTestCase):
slug2="option-two-the-main-name-and-its-awesomeiiii",
slug3="the-main-nàmë-and-its-awεšomeıııi",
)
self.assertEqual(RelatedPrepopulated.objects.all().count(), 6)
self.assertEqual(RelatedPrepopulated.objects.count(), 6)
RelatedPrepopulated.objects.get(
name=" here is a sŤāÇkeð inline ! ",
pubdate="2011-12-17",

View File

@ -178,7 +178,7 @@ class AggregateTestCase(TestCase):
s3.books.add(cls.b3, cls.b4, cls.b6)
def test_empty_aggregate(self):
self.assertEqual(Author.objects.all().aggregate(), {})
self.assertEqual(Author.objects.aggregate(), {})
def test_aggregate_in_order_by(self):
msg = (
@ -209,11 +209,7 @@ class AggregateTestCase(TestCase):
vals = Book.objects.filter(rating__lt=4.5).aggregate(Avg("authors__age"))
self.assertEqual(vals, {"authors__age__avg": Approximate(38.2857, places=2)})
vals = (
Author.objects.all()
.filter(name__contains="a")
.aggregate(Avg("book__rating"))
)
vals = Author.objects.filter(name__contains="a").aggregate(Avg("book__rating"))
self.assertEqual(vals, {"book__rating__avg": 4.0})
vals = Book.objects.aggregate(Sum("publisher__num_awards"))
@ -1016,7 +1012,7 @@ class AggregateTestCase(TestCase):
"""
Aggregation over sliced queryset works correctly.
"""
qs = Book.objects.all().order_by("-rating")[0:3]
qs = Book.objects.order_by("-rating")[0:3]
vals = qs.aggregate(average_top3_rating=Avg("rating"))["average_top3_rating"]
self.assertAlmostEqual(vals, 4.5, places=2)
@ -1026,8 +1022,7 @@ class AggregateTestCase(TestCase):
select_related() stuff.
"""
qs = (
Book.objects.all()
.select_for_update()
Book.objects.select_for_update()
.order_by("pk")
.select_related("publisher")
.annotate(max_pk=Max("pk"))
@ -2047,14 +2042,14 @@ class AggregateTestCase(TestCase):
self.assertEqual(result["num_awards__sum"], 20)
def test_exists_none_with_aggregate(self):
qs = Book.objects.all().annotate(
qs = Book.objects.annotate(
count=Count("id"),
exists=Exists(Author.objects.none()),
)
self.assertEqual(len(qs), 6)
def test_exists_extra_where_with_aggregate(self):
qs = Book.objects.all().annotate(
qs = Book.objects.annotate(
count=Count("id"),
exists=Exists(Author.objects.extra(where=["1=0"])),
)

View File

@ -471,13 +471,9 @@ class AggregationTests(TestCase):
def test_aggregate_annotation(self):
# Aggregates can be composed over annotations.
# The return type is derived from the composed aggregate
vals = (
Book.objects.all()
.annotate(num_authors=Count("authors__id"))
.aggregate(
vals = Book.objects.annotate(num_authors=Count("authors__id")).aggregate(
Max("pages"), Max("price"), Sum("num_authors"), Avg("num_authors")
)
)
self.assertEqual(
vals,
{
@ -588,10 +584,10 @@ class AggregationTests(TestCase):
"pubdate, publisher, publisher_id, rating, store, tags"
)
with self.assertRaisesMessage(FieldError, msg):
Book.objects.all().aggregate(num_authors=Count("foo"))
Book.objects.aggregate(num_authors=Count("foo"))
with self.assertRaisesMessage(FieldError, msg):
Book.objects.all().annotate(num_authors=Count("foo"))
Book.objects.annotate(num_authors=Count("foo"))
msg = (
"Cannot resolve keyword 'foo' into field. Choices are: authors, "
@ -599,7 +595,7 @@ class AggregationTests(TestCase):
"pages, price, pubdate, publisher, publisher_id, rating, store, tags"
)
with self.assertRaisesMessage(FieldError, msg):
Book.objects.all().annotate(num_authors=Count("authors__id")).aggregate(
Book.objects.annotate(num_authors=Count("authors__id")).aggregate(
Max("foo")
)
@ -932,7 +928,7 @@ class AggregationTests(TestCase):
"the default name for another annotation."
)
with self.assertRaisesMessage(ValueError, msg):
Book.objects.all().annotate(
Book.objects.annotate(
Avg("authors__age"), authors__age__avg=Avg("authors__age")
)

View File

@ -529,8 +529,8 @@ class AnonymousUserTests(SimpleTestCase):
self.assertIs(self.user.is_staff, False)
self.assertIs(self.user.is_active, False)
self.assertIs(self.user.is_superuser, False)
self.assertEqual(self.user.groups.all().count(), 0)
self.assertEqual(self.user.user_permissions.all().count(), 0)
self.assertEqual(self.user.groups.count(), 0)
self.assertEqual(self.user.user_permissions.count(), 0)
self.assertEqual(self.user.get_user_permissions(), set())
self.assertEqual(self.user.get_group_permissions(), set())

View File

@ -28,13 +28,13 @@ class Tests(TestCase):
"""Raise NotSupportedError when aggregating on date/time fields."""
for aggregate in (Sum, Avg, Variance, StdDev):
with self.assertRaises(NotSupportedError):
Item.objects.all().aggregate(aggregate("time"))
Item.objects.aggregate(aggregate("time"))
with self.assertRaises(NotSupportedError):
Item.objects.all().aggregate(aggregate("date"))
Item.objects.aggregate(aggregate("date"))
with self.assertRaises(NotSupportedError):
Item.objects.all().aggregate(aggregate("last_modified"))
Item.objects.aggregate(aggregate("last_modified"))
with self.assertRaises(NotSupportedError):
Item.objects.all().aggregate(
Item.objects.aggregate(
**{
"complex": aggregate("last_modified")
+ aggregate("last_modified")

View File

@ -32,12 +32,12 @@ class ModelInstanceCreationTests(TestCase):
pub_date=datetime(2005, 7, 28),
)
self.assertIsNone(a.id)
self.assertEqual(Article.objects.all().count(), 0)
self.assertEqual(Article.objects.count(), 0)
# Save it into the database. You have to call save() explicitly.
a.save()
self.assertIsNotNone(a.id)
self.assertEqual(Article.objects.all().count(), 1)
self.assertEqual(Article.objects.count(), 1)
def test_can_initialize_model_instance_using_positional_arguments(self):
"""
@ -199,7 +199,7 @@ class ModelTest(TestCase):
for headline in headlines:
Article(headline=headline, pub_date=some_pub_date).save()
self.assertQuerysetEqual(
Article.objects.all().order_by("headline"),
Article.objects.order_by("headline"),
sorted(headlines),
transform=lambda a: a.headline,
)

View File

@ -454,7 +454,7 @@ class BaseCacheTests:
Poll.objects.all().delete()
Poll.objects.create(question="What?")
self.assertEqual(expensive_calculation.num_runs, 1)
defer_qs = Poll.objects.all().defer("question")
defer_qs = Poll.objects.defer("question")
self.assertEqual(defer_qs.count(), 1)
self.assertEqual(expensive_calculation.num_runs, 1)
cache.set("deferred_queryset", defer_qs)
@ -467,7 +467,7 @@ class BaseCacheTests:
Poll.objects.all().delete()
Poll.objects.create(question="What?")
self.assertEqual(expensive_calculation.num_runs, 1)
defer_qs = Poll.objects.all().defer("question")
defer_qs = Poll.objects.defer("question")
self.assertEqual(defer_qs.count(), 1)
cache.set("deferred_queryset", defer_qs)
self.assertEqual(expensive_calculation.num_runs, 1)

View File

@ -82,7 +82,7 @@ class CustomColumnsTests(TestCase):
def test_author_querying(self):
self.assertSequenceEqual(
Author.objects.all().order_by("last_name"),
Author.objects.order_by("last_name"),
[self.a2, self.a1],
)
@ -119,7 +119,7 @@ class CustomColumnsTests(TestCase):
def test_m2m_table(self):
self.assertSequenceEqual(
self.article.authors.all().order_by("last_name"),
self.article.authors.order_by("last_name"),
[self.a2, self.a1],
)
self.assertSequenceEqual(self.a1.article_set.all(), [self.article])

View File

@ -48,7 +48,7 @@ class DeferTests(AssertionMixin, TestCase):
# 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.all().only("pk")[0], 2)
self.assert_delayed(self.s1.primary_set.only("pk")[0], 2)
def test_defer_only_chaining(self):
qs = Primary.objects.all()
@ -248,7 +248,7 @@ class TestDefer2(AssertionMixin, TestCase):
"""
related = Secondary.objects.create(first="x1", second="x2")
ChildProxy.objects.create(name="p1", value="xx", related=related)
children = ChildProxy.objects.all().select_related().only("id", "name")
children = ChildProxy.objects.select_related().only("id", "name")
self.assertEqual(len(children), 1)
child = children[0]
self.assert_delayed(child, 2)

View File

@ -226,7 +226,7 @@ class DeferRegressionTest(TestCase):
item = Item.objects.create(name="first", value=47)
RelatedItem.objects.create(item=item)
# Defer fields with only()
obj = ProxyRelated.objects.all().select_related().only("item__name")[0]
obj = ProxyRelated.objects.select_related().only("item__name")[0]
with self.assertNumQueries(0):
self.assertEqual(obj.item.name, "first")
with self.assertNumQueries(1):

View File

@ -721,7 +721,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[
(1, "one"),
(2, "two"),
@ -742,7 +742,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[(1, 1), (2, 2), (3, None), (2, 2), (3, None), (3, None), (4, None)],
transform=attrgetter("integer", "integer2"),
)
@ -756,7 +756,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[("1", 2), ("2", 5), ("3", 3), ("2", 5), ("3", 3), ("3", 3), ("4", 4)],
transform=attrgetter("string", "integer"),
)
@ -769,7 +769,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[
(1, "equal"),
(2, "+1"),
@ -814,7 +814,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[(1, 1), (2, 2), (3, None), (2, 2), (3, None), (3, None), (4, None)],
transform=attrgetter("integer", "big_integer"),
)
@ -828,7 +828,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[
(1, b"one"),
(2, b"two"),
@ -850,7 +850,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[
(1, True),
(2, True),
@ -871,7 +871,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[
(1, date(2015, 1, 1)),
(2, date(2015, 1, 2)),
@ -892,7 +892,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[
(1, datetime(2015, 1, 1)),
(2, datetime(2015, 1, 2)),
@ -915,7 +915,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[
(1, Decimal("1.1")),
(2, Decimal("2.2")),
@ -936,7 +936,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[
(1, timedelta(1)),
(2, timedelta(2)),
@ -958,7 +958,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[
(1, "1@example.com"),
(2, "2@example.com"),
@ -979,7 +979,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[(1, "~/1"), (2, "~/2"), (3, ""), (2, "~/2"), (3, ""), (3, ""), (4, "")],
transform=lambda o: (o.integer, str(o.file)),
)
@ -993,7 +993,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[(1, "~/1"), (2, "~/2"), (3, ""), (2, "~/2"), (3, ""), (3, ""), (4, "")],
transform=attrgetter("integer", "file_path"),
)
@ -1006,7 +1006,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[(1, 1.1), (2, 2.2), (3, None), (2, 2.2), (3, None), (3, None), (4, None)],
transform=attrgetter("integer", "float"),
)
@ -1020,7 +1020,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[(1, "~/1"), (2, "~/2"), (3, ""), (2, "~/2"), (3, ""), (3, ""), (4, "")],
transform=lambda o: (o.integer, str(o.image)),
)
@ -1034,7 +1034,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[
(1, "1.1.1.1"),
(2, "2.2.2.2"),
@ -1055,7 +1055,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[
(1, True),
(2, False),
@ -1076,7 +1076,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[(1, 1), (2, 2), (3, None), (2, 2), (3, None), (3, None), (4, None)],
transform=attrgetter("integer", "positive_big_integer"),
)
@ -1089,7 +1089,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[(1, 1), (2, 2), (3, None), (2, 2), (3, None), (3, None), (4, None)],
transform=attrgetter("integer", "positive_integer"),
)
@ -1102,7 +1102,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[(1, 1), (2, 2), (3, None), (2, 2), (3, None), (3, None), (4, None)],
transform=attrgetter("integer", "positive_small_integer"),
)
@ -1116,7 +1116,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[(1, "1"), (2, "2"), (3, ""), (2, "2"), (3, ""), (3, ""), (4, "")],
transform=attrgetter("integer", "slug"),
)
@ -1129,7 +1129,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[(1, 1), (2, 2), (3, None), (2, 2), (3, None), (3, None), (4, None)],
transform=attrgetter("integer", "small_integer"),
)
@ -1156,7 +1156,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[(1, "1"), (2, "2"), (3, ""), (2, "2"), (3, ""), (3, ""), (4, "")],
transform=attrgetter("integer", "text"),
)
@ -1169,7 +1169,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[
(1, time(1)),
(2, time(2)),
@ -1191,7 +1191,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[
(1, "http://1.example.com/"),
(2, "http://2.example.com/"),
@ -1212,7 +1212,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[
(1, UUID("11111111111111111111111111111111")),
(2, UUID("22222222222222222222222222222222")),
@ -1235,7 +1235,7 @@ class CaseExpressionTests(TestCase):
),
)
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by("pk"),
CaseTestModel.objects.order_by("pk"),
[
(1, obj1.pk),
(2, obj2.pk),
@ -1550,7 +1550,7 @@ class CaseDocumentationExamples(TestCase):
),
)
self.assertQuerysetEqual(
Client.objects.all().order_by("pk"),
Client.objects.order_by("pk"),
[("Jane Doe", "G"), ("James Smith", "R"), ("Jack Black", "P")],
transform=attrgetter("name", "account_type"),
)

View File

@ -128,7 +128,7 @@ class ExtraRegressTests(TestCase):
Regression test for #8063: limiting a query shouldn't discard any
extra() bits.
"""
qs = User.objects.all().extra(where=["id=%s"], params=[self.u.id])
qs = User.objects.extra(where=["id=%s"], params=[self.u.id])
self.assertSequenceEqual(qs, [self.u])
self.assertSequenceEqual(qs[:1], [self.u])

View File

@ -238,7 +238,7 @@ class MultiColumnFKTests(TestCase):
for m in Membership.objects.select_related("person").order_by("pk")
]
normal_people = [m.person for m in Membership.objects.all().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):

View File

@ -232,9 +232,9 @@ class TestFirstLast(TestCase):
with self.assertRaises(IndexError):
IndexErrorArticle.objects.all()[:10:2]
with self.assertRaises(IndexError):
IndexErrorArticle.objects.all().first()
IndexErrorArticle.objects.first()
with self.assertRaises(IndexError):
IndexErrorArticle.objects.all().last()
IndexErrorArticle.objects.last()
check()

View File

@ -690,7 +690,7 @@ class GISFunctionsTests(FuncTestMixin, TestCase):
)
def test_diff_intersection_union(self):
geom = Point(5, 23, srid=4326)
qs = Country.objects.all().annotate(
qs = Country.objects.annotate(
difference=functions.Difference("mpoly", geom),
sym_difference=functions.SymDifference("mpoly", geom),
union=functions.Union("mpoly", geom),

View File

@ -21,12 +21,12 @@ class GeoJSONSerializerTests(TestCase):
self.assertIn("geojson", public_formats)
def test_serialization_base(self):
geojson = serializers.serialize("geojson", City.objects.all().order_by("name"))
geojson = serializers.serialize("geojson", City.objects.order_by("name"))
geodata = json.loads(geojson)
self.assertEqual(len(geodata["features"]), len(City.objects.all()))
self.assertEqual(geodata["features"][0]["geometry"]["type"], "Point")
self.assertEqual(geodata["features"][0]["properties"]["name"], "Chicago")
first_city = City.objects.all().order_by("name").first()
first_city = City.objects.order_by("name").first()
self.assertEqual(geodata["features"][0]["properties"]["pk"], str(first_city.pk))
def test_geometry_field_option(self):
@ -81,7 +81,7 @@ class GeoJSONSerializerTests(TestCase):
def test_srid_option(self):
geojson = serializers.serialize(
"geojson", City.objects.all().order_by("name"), srid=2847
"geojson", City.objects.order_by("name"), srid=2847
)
geodata = json.loads(geojson)
coordinates = geodata["features"][0]["geometry"]["coordinates"]

View File

@ -217,7 +217,7 @@ class GeoModelTest(TestCase):
Test a dumpdata/loaddata cycle with geographic data.
"""
out = StringIO()
original_data = list(City.objects.all().order_by("name"))
original_data = list(City.objects.order_by("name"))
call_command("dumpdata", "geoapp.City", stdout=out)
result = out.getvalue()
houston = City.objects.get(name="Houston")
@ -228,7 +228,7 @@ class GeoModelTest(TestCase):
tmp.write(result)
tmp.seek(0)
call_command("loaddata", tmp.name, verbosity=0)
self.assertEqual(original_data, list(City.objects.all().order_by("name")))
self.assertEqual(original_data, list(City.objects.order_by("name")))
@skipUnlessDBFeature("supports_empty_geometries")
def test_empty_geometries(self):
@ -623,7 +623,7 @@ class GeoQuerySetTest(TestCase):
"""
Testing if extent supports limit.
"""
extent1 = City.objects.all().aggregate(Extent("point"))["point__extent"]
extent1 = City.objects.aggregate(Extent("point"))["point__extent"]
extent2 = City.objects.all()[:3].aggregate(Extent("point"))["point__extent"]
self.assertNotEqual(extent1, extent2)
@ -633,7 +633,7 @@ class GeoQuerySetTest(TestCase):
"""
if not connection.features.supports_make_line_aggr:
with self.assertRaises(NotSupportedError):
City.objects.all().aggregate(MakeLine("point"))
City.objects.aggregate(MakeLine("point"))
return
# MakeLine on an inappropriate field returns simply None

View File

@ -108,7 +108,7 @@ class RelatedGeoModelTest(TestCase):
select_related on a query over a model with an FK to a model subclass.
"""
# Regression test for #9752.
list(DirectoryEntry.objects.all().select_related())
list(DirectoryEntry.objects.select_related())
def test06_f_expressions(self):
"Testing F() expressions on GeometryFields."

View File

@ -73,7 +73,7 @@ class BooleanFieldTests(TestCase):
# When an extra clause exists, the boolean conversions are applied with
# an offset (#13293).
b5 = BooleanModel.objects.all().extra(select={"string_col": "string"})[0]
b5 = BooleanModel.objects.extra(select={"string_col": "string"})[0]
self.assertNotIsInstance(b5.pk, bool)
def test_select_related(self):

View File

@ -1617,7 +1617,7 @@ class ModelFormBasicTests(TestCase):
# Set up a callable initial value
def formfield_for_dbfield(db_field, **kwargs):
if db_field.name == "categories":
kwargs["initial"] = lambda: Category.objects.all().order_by("name")[:2]
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

View File

@ -55,7 +55,7 @@ class InlineFormsetTests(TestCase):
form_set = FormSet(data, instance=user)
if form_set.is_valid():
form_set.save()
usersite = UserSite.objects.all().values()
usersite = UserSite.objects.values()
self.assertEqual(usersite[0]["data"], 10)
self.assertEqual(usersite[0]["user_id"], "apollo13")
else:
@ -73,7 +73,7 @@ class InlineFormsetTests(TestCase):
form_set = FormSet(data, instance=user)
if form_set.is_valid():
form_set.save()
usersite = UserSite.objects.all().values()
usersite = UserSite.objects.values()
self.assertEqual(usersite[0]["data"], 11)
self.assertEqual(usersite[0]["user_id"], "apollo13")
else:
@ -93,7 +93,7 @@ class InlineFormsetTests(TestCase):
form_set = FormSet(data, instance=user)
if form_set.is_valid():
form_set.save()
usersite = UserSite.objects.all().values().order_by("data")
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)
@ -131,7 +131,7 @@ class InlineFormsetTests(TestCase):
form_set = FormSet(data, instance=restaurant)
if form_set.is_valid():
form_set.save()
manager = Manager.objects.all().values()
manager = Manager.objects.values()
self.assertEqual(manager[0]["name"], "Guido Van Rossum")
else:
self.fail("Errors found on formset:%s" % form_set.errors)
@ -147,7 +147,7 @@ class InlineFormsetTests(TestCase):
form_set = FormSet(data, instance=restaurant)
if form_set.is_valid():
form_set.save()
manager = Manager.objects.all().values()
manager = Manager.objects.values()
self.assertEqual(manager[0]["name"], "Terry Gilliam")
else:
self.fail("Errors found on formset:%s" % form_set.errors)
@ -164,7 +164,7 @@ class InlineFormsetTests(TestCase):
form_set = FormSet(data, instance=restaurant)
if form_set.is_valid():
form_set.save()
manager = Manager.objects.all().values().order_by("name")
manager = Manager.objects.values().order_by("name")
self.assertEqual(manager[0]["name"], "John Cleese")
self.assertEqual(manager[1]["name"], "Terry Gilliam")
else:

View File

@ -260,7 +260,7 @@ class ModelInheritanceTest(TestCase):
"""
Regression test for #11764
"""
wholesalers = list(Wholesaler.objects.all().select_related())
wholesalers = list(Wholesaler.objects.select_related())
self.assertEqual(wholesalers, [])
def test_issue_7853(self):
@ -525,7 +525,7 @@ class ModelInheritanceTest(TestCase):
serves_pizza=True,
serves_hot_dogs=True,
)
p = Place.objects.all().select_related("restaurant")[0]
p = Place.objects.select_related("restaurant")[0]
self.assertIsInstance(p.restaurant.serves_pizza, bool)
def test_inheritance_select_related(self):

View File

@ -219,11 +219,11 @@ class QueryTestCase(TestCase):
# Retrieve related object by descriptor. Related objects should be
# database-bound.
self.assertEqual(
list(dive.authors.all().values_list("name", flat=True)), ["Mark Pilgrim"]
list(dive.authors.values_list("name", flat=True)), ["Mark Pilgrim"]
)
self.assertEqual(
list(mark.book_set.all().values_list("title", flat=True)),
list(mark.book_set.values_list("title", flat=True)),
["Dive into Python"],
)
@ -985,7 +985,7 @@ class QueryTestCase(TestCase):
# Retrieve related object by descriptor. Related objects should be
# database-bound.
self.assertEqual(
list(dive.reviews.all().values_list("source", flat=True)), ["Python Weekly"]
list(dive.reviews.values_list("source", flat=True)), ["Python Weekly"]
)
def test_generic_key_reverse_operations(self):
@ -2415,7 +2415,7 @@ class RouteForWriteTestCase(TestCase):
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
book.authors.all().update(name="Different")
book.authors.update(name="Different")
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Person)
@ -2497,7 +2497,7 @@ class RouteForWriteTestCase(TestCase):
book.authors.add(auth)
with self.assertRaises(RouterUsed) as cm:
with self.override_router():
auth.book_set.all().update(title="Different")
auth.book_set.update(title="Different")
e = cm.exception
self.assertEqual(e.mode, RouterUsed.WRITE)
self.assertEqual(e.model, Book)

View File

@ -185,8 +185,8 @@ class OneToOneTests(TestCase):
bar.save()
self.p1.delete()
self.assertEqual(Place.objects.all().count(), 1)
self.assertEqual(UndergroundBar.objects.all().count(), 1)
self.assertEqual(Place.objects.count(), 1)
self.assertEqual(UndergroundBar.objects.count(), 1)
def test_create_models_m2m(self):
"""

View File

@ -236,7 +236,7 @@ class OrderingTests(TestCase):
and then take the first two).
"""
self.assertQuerysetEqual(
Article.objects.all().reverse()[:2],
Article.objects.reverse()[:2],
[
"Article 1",
"Article 3",

View File

@ -278,9 +278,7 @@ class TestQuerying(PostgreSQLTestCase):
IntegerArrayModel.objects.create(field=[2, 3])
self.assertSequenceEqual(
NullableIntegerArrayModel.objects.filter(
field__in=IntegerArrayModel.objects.all().values_list(
"field", flat=True
)
field__in=IntegerArrayModel.objects.values_list("field", flat=True)
),
self.objs[2:3],
)

View File

@ -269,7 +269,7 @@ class PrefetchRelatedTests(TestDataMixin, TestCase):
list(qs.all())
def test_attribute_error(self):
qs = Reader.objects.all().prefetch_related("books_read__xyz")
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()"
@ -872,43 +872,33 @@ class CustomPrefetchTests(TestCase):
# Test ForwardManyToOneDescriptor.
houses = House.objects.select_related("owner")
with self.assertNumQueries(6):
rooms = Room.objects.all().prefetch_related("house")
rooms = Room.objects.prefetch_related("house")
lst1 = self.traverse_qs(rooms, [["house", "owner"]])
with self.assertNumQueries(2):
rooms = Room.objects.all().prefetch_related(
Prefetch("house", queryset=houses.all())
)
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.all().prefetch_related(
Prefetch("house", queryset=houses.all(), to_attr="house_attr")
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.all()
.prefetch_related(
room = Room.objects.prefetch_related(
Prefetch("house", queryset=houses.filter(address="DoesNotExist"))
)
.first()
)
).first()
with self.assertRaises(ObjectDoesNotExist):
getattr(room, "house")
room = (
Room.objects.all()
.prefetch_related(
room = Room.objects.prefetch_related(
Prefetch(
"house",
queryset=houses.filter(address="DoesNotExist"),
to_attr="house_attr",
)
)
.first()
)
).first()
self.assertIsNone(room.house_attr)
rooms = Room.objects.all().prefetch_related(
rooms = Room.objects.prefetch_related(
Prefetch("house", queryset=House.objects.only("name"))
)
with self.assertNumQueries(2):
@ -919,20 +909,20 @@ class CustomPrefetchTests(TestCase):
# Test ReverseOneToOneDescriptor.
houses = House.objects.select_related("owner")
with self.assertNumQueries(6):
rooms = Room.objects.all().prefetch_related("main_room_of")
rooms = Room.objects.prefetch_related("main_room_of")
lst1 = self.traverse_qs(rooms, [["main_room_of", "owner"]])
with self.assertNumQueries(2):
rooms = Room.objects.all().prefetch_related(
Prefetch("main_room_of", queryset=houses.all())
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.all().prefetch_related(
Room.objects.prefetch_related(
Prefetch(
"main_room_of",
queryset=houses.all(),
queryset=houses,
to_attr="main_room_of_attr",
)
)
@ -1346,7 +1336,7 @@ class ForeignKeyToFieldTest(TestCase):
def test_m2m(self):
with self.assertNumQueries(3):
qs = Author.objects.all().prefetch_related("favorite_authors", "favors_me")
qs = Author.objects.prefetch_related("favorite_authors", "favors_me")
favorites = [
(
[str(i_like) for i_like in author.favorite_authors.all()],

View File

@ -28,8 +28,8 @@ class ProxyModelInheritanceTests(TransactionTestCase):
from app1.models import ProxyModel
from app2.models import NiceModel
self.assertEqual(NiceModel.objects.all().count(), 0)
self.assertEqual(ProxyModel.objects.all().count(), 0)
self.assertEqual(NiceModel.objects.count(), 0)
self.assertEqual(ProxyModel.objects.count(), 0)
class MultiTableInheritanceProxyTest(TestCase):

View File

@ -20,7 +20,7 @@ class ExplainTests(TestCase):
Tag.objects.filter(name="test").annotate(Count("children")),
Tag.objects.filter(name="test").values_list("name"),
Tag.objects.order_by().union(Tag.objects.order_by().filter(name="test")),
Tag.objects.all().select_for_update().filter(name="test"),
Tag.objects.select_for_update().filter(name="test"),
]
supported_formats = connection.features.supported_explain_formats
all_formats = (
@ -60,7 +60,7 @@ class ExplainTests(TestCase):
@skipUnlessDBFeature("validates_explain_options")
def test_unknown_options(self):
with self.assertRaisesMessage(ValueError, "Unknown options: test, test2"):
Tag.objects.all().explain(test=1, test2=1)
Tag.objects.explain(test=1, test2=1)
def test_unknown_format(self):
msg = "DOES NOT EXIST is not a recognized format."
@ -69,7 +69,7 @@ class ExplainTests(TestCase):
sorted(connection.features.supported_explain_formats)
)
with self.assertRaisesMessage(ValueError, msg):
Tag.objects.all().explain(format="does not exist")
Tag.objects.explain(format="does not exist")
@unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific")
def test_postgres_options(self):

View File

@ -110,7 +110,7 @@ class QuerySetSetOperationTests(TestCase):
self.assertEqual(len(qs3.union(qs3)), 0)
def test_empty_qs_union_with_ordered_qs(self):
qs1 = Number.objects.all().order_by("num")
qs1 = Number.objects.order_by("num")
qs2 = Number.objects.none().union(qs1).order_by("num")
self.assertEqual(list(qs1), list(qs2))

View File

@ -1787,7 +1787,7 @@ class Queries5Tests(TestCase):
[self.rank3, self.rank2, self.rank1],
)
self.assertSequenceEqual(
Ranking.objects.all().order_by("rank"),
Ranking.objects.order_by("rank"),
[self.rank1, self.rank2, self.rank3],
)
@ -1944,9 +1944,9 @@ class NullableRelOrderingTests(TestCase):
s = SingleObject.objects.create(name="s")
r = RelatedObject.objects.create(single=s, f=1)
p2 = Plaything.objects.create(name="p2", others=r)
qs = Plaything.objects.all().filter(others__isnull=False).order_by("pk")
qs = Plaything.objects.filter(others__isnull=False).order_by("pk")
self.assertNotIn("JOIN", str(qs.query))
qs = Plaything.objects.all().filter(others__f__isnull=False).order_by("pk")
qs = Plaything.objects.filter(others__f__isnull=False).order_by("pk")
self.assertIn("INNER", str(qs.query))
qs = qs.order_by("others__single__name")
# The ordering by others__single__pk will add one new join (to single)
@ -2219,16 +2219,16 @@ class QuerysetOrderedTests(unittest.TestCase):
def test_cleared_default_ordering(self):
self.assertIs(Tag.objects.all().ordered, True)
self.assertIs(Tag.objects.all().order_by().ordered, False)
self.assertIs(Tag.objects.order_by().ordered, False)
def test_explicit_ordering(self):
self.assertIs(Annotation.objects.all().order_by("id").ordered, True)
self.assertIs(Annotation.objects.order_by("id").ordered, True)
def test_empty_queryset(self):
self.assertIs(Annotation.objects.none().ordered, True)
def test_order_by_extra(self):
self.assertIs(Annotation.objects.all().extra(order_by=["id"]).ordered, True)
self.assertIs(Annotation.objects.extra(order_by=["id"]).ordered, True)
def test_annotated_ordering(self):
qs = Annotation.objects.annotate(num_notes=Count("notes"))
@ -2685,7 +2685,7 @@ class QuerySetSupportsPythonIdioms(TestCase):
]
def get_ordered_articles(self):
return Article.objects.all().order_by("name")
return Article.objects.order_by("name")
def test_can_get_items_using_index_and_slice_notation(self):
self.assertEqual(self.get_ordered_articles()[0].name, "Article 1")
@ -2839,7 +2839,7 @@ class EscapingTests(TestCase):
r_a = ReservedName.objects.create(name="a", order=42)
r_b = ReservedName.objects.create(name="b", order=37)
self.assertSequenceEqual(
ReservedName.objects.all().order_by("order"),
ReservedName.objects.order_by("order"),
[r_b, r_a],
)
self.assertSequenceEqual(
@ -2983,7 +2983,7 @@ class ConditionalTests(TestCase):
# ... but you can still order in a non-recursive fashion among linked
# fields (the previous test failed because the default ordering was
# recursive).
self.assertQuerysetEqual(LoopX.objects.all().order_by("y__x__y__x__id"), [])
self.assertQuerysetEqual(LoopX.objects.order_by("y__x__y__x__id"), [])
# When grouping without specifying ordering, we add an explicit "ORDER BY NULL"
# portion in MySQL to prevent unnecessary sorting.
@ -4175,7 +4175,7 @@ class RelatedLookupTypeTests(TestCase):
pob.save()
self.assertSequenceEqual(
ObjectB.objects.filter(
objecta__in=ObjectB.objects.all().values_list("num")
objecta__in=ObjectB.objects.values_list("num")
).order_by("pk"),
[ob, pob],
)

View File

@ -90,7 +90,7 @@ class SelectForUpdateTests(TransactionTestCase):
generated SQL when select_for_update is invoked.
"""
with transaction.atomic(), CaptureQueriesContext(connection) as ctx:
list(Person.objects.all().select_for_update())
list(Person.objects.select_for_update())
self.assertTrue(self.has_for_update_sql(ctx.captured_queries))
@skipUnlessDBFeature("has_select_for_update_nowait")
@ -100,7 +100,7 @@ class SelectForUpdateTests(TransactionTestCase):
generated SQL when select_for_update is invoked.
"""
with transaction.atomic(), CaptureQueriesContext(connection) as ctx:
list(Person.objects.all().select_for_update(nowait=True))
list(Person.objects.select_for_update(nowait=True))
self.assertTrue(self.has_for_update_sql(ctx.captured_queries, nowait=True))
@skipUnlessDBFeature("has_select_for_update_skip_locked")
@ -110,7 +110,7 @@ class SelectForUpdateTests(TransactionTestCase):
generated SQL when select_for_update is invoked.
"""
with transaction.atomic(), CaptureQueriesContext(connection) as ctx:
list(Person.objects.all().select_for_update(skip_locked=True))
list(Person.objects.select_for_update(skip_locked=True))
self.assertTrue(self.has_for_update_sql(ctx.captured_queries, skip_locked=True))
@skipUnlessDBFeature("has_select_for_no_key_update")
@ -120,7 +120,7 @@ class SelectForUpdateTests(TransactionTestCase):
select_for_update() is invoked.
"""
with transaction.atomic(), CaptureQueriesContext(connection) as ctx:
list(Person.objects.all().select_for_update(no_key=True))
list(Person.objects.select_for_update(no_key=True))
self.assertIs(self.has_for_update_sql(ctx.captured_queries, no_key=True), True)
@skipUnlessDBFeature("has_select_for_update_of")
@ -499,7 +499,7 @@ class SelectForUpdateTests(TransactionTestCase):
"""
msg = "select_for_update cannot be used outside of a transaction."
with self.assertRaisesMessage(transaction.TransactionManagementError, msg):
list(Person.objects.all().select_for_update())
list(Person.objects.select_for_update())
@skipUnlessDBFeature("has_select_for_update")
def test_for_update_requires_transaction_only_in_execution(self):
@ -508,7 +508,7 @@ class SelectForUpdateTests(TransactionTestCase):
when select_for_update is invoked outside of a transaction -
only when the query is executed.
"""
people = Person.objects.all().select_for_update()
people = Person.objects.select_for_update()
msg = "select_for_update cannot be used outside of a transaction."
with self.assertRaisesMessage(transaction.TransactionManagementError, msg):
list(people)
@ -517,7 +517,7 @@ class SelectForUpdateTests(TransactionTestCase):
def test_select_for_update_with_limit(self):
other = Person.objects.create(name="Grappeli", born=self.city1, died=self.city2)
with transaction.atomic():
qs = list(Person.objects.all().order_by("pk").select_for_update()[1:2])
qs = list(Person.objects.order_by("pk").select_for_update()[1:2])
self.assertEqual(qs[0], other)
@skipIfDBFeature("supports_select_for_update_with_limit")
@ -528,7 +528,7 @@ class SelectForUpdateTests(TransactionTestCase):
)
with self.assertRaisesMessage(NotSupportedError, msg):
with transaction.atomic():
list(Person.objects.all().order_by("pk").select_for_update()[1:2])
list(Person.objects.order_by("pk").select_for_update()[1:2])
def run_select_for_update(self, status, **kwargs):
"""

View File

@ -94,7 +94,7 @@ class SelectRelatedTests(TestCase):
def test_list_with_select_related(self):
"""select_related() applies to entire lists, not just items."""
with self.assertNumQueries(1):
world = Species.objects.all().select_related()
world = Species.objects.select_related()
families = [o.genus.family.name for o in world]
self.assertEqual(
sorted(families),
@ -113,7 +113,7 @@ class SelectRelatedTests(TestCase):
well.
"""
with self.assertNumQueries(5):
world = Species.objects.all().select_related("genus__family")
world = Species.objects.select_related("genus__family")
orders = [o.genus.family.order.name for o in world]
self.assertEqual(
sorted(orders), ["Agaricales", "Diptera", "Fabales", "Primates"]

View File

@ -92,7 +92,7 @@ class SelectRelatedRegressTests(TestCase):
c = Class.objects.create(org=o)
Enrollment.objects.create(std=s, cls=c)
e_related = Enrollment.objects.all().select_related()[0]
e_related = Enrollment.objects.select_related()[0]
self.assertEqual(e_related.std.person.user.name, "std")
self.assertEqual(e_related.cls.org.person.user.name, "org")
@ -228,9 +228,7 @@ class SelectRelatedRegressTests(TestCase):
c = C.objects.create(
name="c", lots_of_text="lots_of_text_c", is_published=True, c_a=a, c_b=b
)
results = (
C.objects.all()
.only(
results = C.objects.only(
"name",
"lots_of_text",
"c_a",
@ -238,9 +236,7 @@ class SelectRelatedRegressTests(TestCase):
"c_b__lots_of_text",
"c_a__name",
"c_b__name",
)
.select_related()
)
).select_related()
self.assertSequenceEqual(results, [c])
with self.assertNumQueries(0):
qs_c = results[0]

View File

@ -282,7 +282,7 @@ class SerializersTestBase:
with self.assertNumQueries(3):
serializers.serialize(
self.serializer_name,
Article.objects.all().prefetch_related("categories", "meta_data"),
Article.objects.prefetch_related("categories", "meta_data"),
)
# One query for the Article table, and two m2m queries for each
# article.
@ -361,7 +361,7 @@ class SerializersTestBase:
for obj in deserial_objs:
self.assertFalse(obj.object.id)
obj.save()
self.assertEqual(Category.objects.all().count(), 5)
self.assertEqual(Category.objects.count(), 5)
def test_deterministic_mapping_ordering(self):
"""Mapping such as fields should be deterministically ordered. (#24558)"""
@ -454,9 +454,9 @@ class SerializersTransactionTestBase:
obj.save()
for model_cls in (Category, Author, Article):
self.assertEqual(model_cls.objects.all().count(), 1)
self.assertEqual(model_cls.objects.count(), 1)
art_obj = Article.objects.all()[0]
self.assertEqual(art_obj.categories.all().count(), 1)
self.assertEqual(art_obj.categories.count(), 1)
self.assertEqual(art_obj.author.name, "Agnes")

View File

@ -329,7 +329,7 @@ class LiveServerDatabase(LiveServerBase):
with self.urlopen("/create_model_instance/"):
pass
self.assertQuerysetEqual(
Person.objects.all().order_by("pk"),
Person.objects.order_by("pk"),
["jane", "robert", "emily"],
lambda b: b.name,
)

View File

@ -23,7 +23,7 @@ class SitesFrameworkTestCase(TestCase):
article = ExclusiveArticle.objects.create(
title="Breaking News!", site_id=settings.SITE_ID
)
self.assertEqual(ExclusiveArticle.on_site.all().get(), article)
self.assertEqual(ExclusiveArticle.on_site.get(), article)
def test_sites_m2m(self):
article = SyndicatedArticle.objects.create(title="Fresh News!")
@ -31,14 +31,14 @@ class SitesFrameworkTestCase(TestCase):
article.sites.add(Site.objects.get(id=settings.SITE_ID + 1))
article2 = SyndicatedArticle.objects.create(title="More News!")
article2.sites.add(Site.objects.get(id=settings.SITE_ID + 1))
self.assertEqual(SyndicatedArticle.on_site.all().get(), article)
self.assertEqual(SyndicatedArticle.on_site.get(), article)
def test_custom_named_field(self):
article = CustomArticle.objects.create(
title="Tantalizing News!",
places_this_article_should_appear_id=settings.SITE_ID,
)
self.assertEqual(CustomArticle.on_site.all().get(), article)
self.assertEqual(CustomArticle.on_site.get(), article)
@isolate_apps("sites_framework")

View File

@ -270,37 +270,37 @@ class AssertQuerysetEqualTests(TestCase):
def test_ordered(self):
self.assertQuerysetEqual(
Person.objects.all().order_by("name"),
Person.objects.order_by("name"),
[self.p1, self.p2],
)
def test_unordered(self):
self.assertQuerysetEqual(
Person.objects.all().order_by("name"), [self.p2, self.p1], ordered=False
Person.objects.order_by("name"), [self.p2, self.p1], ordered=False
)
def test_queryset(self):
self.assertQuerysetEqual(
Person.objects.all().order_by("name"),
Person.objects.all().order_by("name"),
Person.objects.order_by("name"),
Person.objects.order_by("name"),
)
def test_flat_values_list(self):
self.assertQuerysetEqual(
Person.objects.all().order_by("name").values_list("name", flat=True),
Person.objects.order_by("name").values_list("name", flat=True),
["p1", "p2"],
)
def test_transform(self):
self.assertQuerysetEqual(
Person.objects.all().order_by("name"),
Person.objects.order_by("name"),
[self.p1.pk, self.p2.pk],
transform=lambda x: x.pk,
)
def test_repr_transform(self):
self.assertQuerysetEqual(
Person.objects.all().order_by("name"),
Person.objects.order_by("name"),
[repr(self.p1), repr(self.p2)],
transform=repr,
)

View File

@ -203,7 +203,7 @@ class LegacyDatabaseTests(TestCase):
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.all().aggregate(Min("dt"), Max("dt"))
result = Event.objects.aggregate(Min("dt"), Max("dt"))
self.assertEqual(
result,
{
@ -499,7 +499,7 @@ class NewDatabaseTests(TestCase):
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.all().aggregate(Min("dt"), Max("dt"))
result = Event.objects.aggregate(Min("dt"), Max("dt"))
self.assertEqual(
result,
{