1
0
mirror of https://github.com/django/django.git synced 2025-10-24 14:16:09 +00:00

[4.2.x] Refs #34140 -- Applied rst code-block to non-Python examples.

Thanks to J.V. Zammit, Paolo Melchiorre, and Mariusz Felisiak for
reviews.

Backport of 534ac48297 from main.
This commit is contained in:
Carlton Gibson
2023-02-09 16:48:46 +01:00
committed by Mariusz Felisiak
parent 4a89aa25c9
commit b784768eef
120 changed files with 3998 additions and 1397 deletions

View File

@@ -48,7 +48,9 @@ objects that have an ``output_field`` that is a
:class:`~django.db.models.BooleanField`. The result is provided using the
``then`` keyword.
Some examples::
Some examples:
.. code-block:: pycon
>>> from django.db.models import F, Q, When
>>> # String arguments refer to fields; the following two examples are equivalent:
@@ -83,7 +85,9 @@ Keep in mind that each of these values can be an expression.
Since the ``then`` keyword argument is reserved for the result of the
``When()``, there is a potential conflict if a
:class:`~django.db.models.Model` has a field named ``then``. This can be
resolved in two ways::
resolved in two ways:
.. code-block:: pycon
>>> When(then__exact=0, then=1)
>>> When(Q(then=0), then=1)
@@ -99,7 +103,9 @@ A ``Case()`` expression is like the :keyword:`if` ... :keyword:`elif` ...
truthful value. The ``result`` expression from the matching ``When()`` object
is returned.
An example::
An example:
.. code-block:: pycon
>>>
>>> from datetime import date, timedelta
@@ -133,7 +139,9 @@ argument is returned. If a ``default`` argument isn't provided, ``None`` is
used.
If we wanted to change our previous query to get the discount based on how long
the ``Client`` has been with us, we could do so using lookups::
the ``Client`` has been with us, we could do so using lookups:
.. code-block:: pycon
>>> a_month_ago = date.today() - timedelta(days=30)
>>> a_year_ago = date.today() - timedelta(days=365)
@@ -156,7 +164,9 @@ the ``Client`` has been with us, we could do so using lookups::
``Case()`` also works in a ``filter()`` clause. For example, to find gold
clients that registered more than a month ago and platinum clients that
registered more than a year ago::
registered more than a year ago:
.. code-block:: pycon
>>> a_month_ago = date.today() - timedelta(days=30)
>>> a_year_ago = date.today() - timedelta(days=365)
@@ -180,7 +190,9 @@ Conditional update
Let's say we want to change the ``account_type`` for our clients to match
their registration dates. We can do this using a conditional expression and the
:meth:`~django.db.models.query.QuerySet.update` method::
:meth:`~django.db.models.query.QuerySet.update` method:
.. code-block:: pycon
>>> a_month_ago = date.today() - timedelta(days=30)
>>> a_year_ago = date.today() - timedelta(days=365)
@@ -204,7 +216,9 @@ Conditional aggregation
What if we want to find out how many clients there are for each
``account_type``? We can use the ``filter`` argument of :ref:`aggregate
functions <aggregation-functions>` to achieve this::
functions <aggregation-functions>` to achieve this:
.. code-block:: pycon
>>> # Create some more Clients first so we can have something to count
>>> Client.objects.create(
@@ -255,7 +269,9 @@ Conditional filter
When a conditional expression returns a boolean value, it is possible to use it
directly in filters. This means that it will not be added to the ``SELECT``
columns, but you can still use it to filter results::
columns, but you can still use it to filter results:
.. code-block:: pycon
>>> non_unique_account_type = Client.objects.filter(
... account_type=OuterRef('account_type'),

View File

@@ -35,7 +35,9 @@ Comparison and conversion functions
Forces the result type of ``expression`` to be the one from ``output_field``.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Cast
@@ -56,7 +58,9 @@ first non-null value (note that an empty string is not considered a null
value). Each argument must be of a similar type, so mixing text and numbers
will result in a database error.
Usage examples::
Usage examples:
.. code-block:: pycon
>>> # Get a screen name from least to most public
>>> from django.db.models import Sum
@@ -99,12 +103,16 @@ Usage examples::
Takes an expression and a collation name to query against.
For example, to filter case-insensitively in SQLite::
For example, to filter case-insensitively in SQLite:
.. code-block:: pycon
>>> Author.objects.filter(name=Collate(Value('john'), 'nocase'))
<QuerySet [<Author: John>, <Author: john>]>
It can also be used when ordering, for example with PostgreSQL::
It can also be used when ordering, for example with PostgreSQL:
.. code-block:: pycon
>>> Author.objects.order_by(Collate('name', 'et-x-icu'))
<QuerySet [<Author: Ursula>, <Author: Veronika>, <Author: Ülle>]>
@@ -129,6 +137,8 @@ Usage example::
modified = models.DateTimeField(auto_now=True)
blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
.. code-block:: pycon
>>> from django.db.models.functions import Greatest
>>> blog = Blog.objects.create(body='Greatest is the best.')
>>> comment = Comment.objects.create(body='No, Least is better.', blog=blog)
@@ -159,7 +169,9 @@ and ``comment.modified``.
Takes a list of key-value pairs and returns a JSON object containing those
pairs.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models import F
>>> from django.db.models.functions import JSONObject, Lower
@@ -272,7 +284,9 @@ returned when this timezone is active will be the same as above except for:
databases and from Python's standard functions. This function will return
``1`` for Sunday, ``2`` for Monday, through ``7`` for Saturday.
The equivalent calculation in Python is::
The equivalent calculation in Python is:
.. code-block:: pycon
>>> from datetime import datetime
>>> dt = datetime(2015, 6, 15)
@@ -292,7 +306,9 @@ Each ``lookup_name`` above has a corresponding ``Extract`` subclass (listed
below) that should typically be used instead of the more verbose equivalent,
e.g. use ``ExtractYear(...)`` rather than ``Extract(..., lookup_name='year')``.
Usage example::
Usage example:
.. code-block:: pycon
>>> from datetime import datetime
>>> from django.db.models.functions import Extract
@@ -356,7 +372,9 @@ class is also a ``Transform`` registered on ``DateField`` and ``DateTimeField``
as ``__(lookup_name)``, e.g. ``__year``.
Since ``DateField``\s don't have a time component, only ``Extract`` subclasses
that deal with date-parts can be used with ``DateField``::
that deal with date-parts can be used with ``DateField``:
.. code-block:: pycon
>>> from datetime import datetime, timezone
>>> from django.db.models.functions import (
@@ -406,7 +424,9 @@ These are logically equivalent to ``Extract('datetime_field', lookup_name)``.
Each class is also a ``Transform`` registered on ``DateTimeField`` as
``__(lookup_name)``, e.g. ``__minute``.
``DateTimeField`` examples::
``DateTimeField`` examples:
.. code-block:: pycon
>>> from datetime import datetime, timezone
>>> from django.db.models.functions import (
@@ -443,7 +463,9 @@ When :setting:`USE_TZ` is ``True`` then datetimes are stored in the database
in UTC. If a different timezone is active in Django, the datetime is converted
to that timezone before the value is extracted. The example below converts to
the Melbourne timezone (UTC +10:00), which changes the day, weekday, and hour
values that are returned::
values that are returned:
.. code-block:: pycon
>>> from django.utils import timezone
>>> import zoneinfo
@@ -460,7 +482,9 @@ values that are returned::
{'day': 16, 'weekday': 3, 'isoweekday': 2, 'hour': 9}
Explicitly passing the timezone to the ``Extract`` function behaves in the same
way, and takes priority over an active timezone::
way, and takes priority over an active timezone:
.. code-block:: pycon
>>> import zoneinfo
>>> melb = zoneinfo.ZoneInfo('Australia/Melbourne')
@@ -482,7 +506,9 @@ way, and takes priority over an active timezone::
Returns the database server's current date and time when the query is executed,
typically using the SQL ``CURRENT_TIMESTAMP``.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Now
>>> Article.objects.filter(published__lte=Now())
@@ -566,7 +592,9 @@ The subclasses are all defined as transforms, but they aren't registered with
any fields, because the lookup names are already reserved by the ``Extract``
subclasses.
Usage example::
Usage example:
.. code-block:: pycon
>>> from datetime import datetime
>>> from django.db.models import Count, DateTimeField
@@ -622,7 +650,9 @@ with less precision. ``expression`` can have an ``output_field`` of either
``DateField`` or ``DateTimeField``.
Since ``DateField``\s don't have a time component, only ``Trunc`` subclasses
that deal with date-parts can be used with ``DateField``::
that deal with date-parts can be used with ``DateField``:
.. code-block:: pycon
>>> from datetime import datetime, timezone
>>> from django.db.models import Count
@@ -700,7 +730,9 @@ truncate all parts of the date up to ``kind`` and allow grouping or filtering
datetimes with less precision. ``expression`` must have an ``output_field`` of
``DateTimeField``.
Usage example::
Usage example:
.. code-block:: pycon
>>> from datetime import date, datetime, timezone
>>> from django.db.models import Count
@@ -753,7 +785,9 @@ with less precision. ``expression`` can have an ``output_field`` of either
``TimeField`` or ``DateTimeField``.
Since ``TimeField``\s don't have a date component, only ``Trunc`` subclasses
that deal with time-parts can be used with ``TimeField``::
that deal with time-parts can be used with ``TimeField``:
.. code-block:: pycon
>>> from datetime import datetime, timezone
>>> from django.db.models import Count, TimeField
@@ -802,7 +836,9 @@ We'll be using the following model in math function examples::
Returns the absolute value of a numeric field or expression.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Abs
>>> Vector.objects.create(x=-0.5, y=1.1)
@@ -810,7 +846,9 @@ Usage example::
>>> vector.x_abs, vector.y_abs
(0.5, 1.1)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Abs
@@ -826,7 +864,9 @@ It can also be registered as a transform. For example::
Returns the arccosine of a numeric field or expression. The expression value
must be within the range -1 to 1.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import ACos
>>> Vector.objects.create(x=0.5, y=-0.9)
@@ -834,7 +874,9 @@ Usage example::
>>> vector.x_acos, vector.y_acos
(1.0471975511965979, 2.6905658417935308)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import ACos
@@ -850,7 +892,9 @@ It can also be registered as a transform. For example::
Returns the arcsine of a numeric field or expression. The expression value must
be in the range -1 to 1.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import ASin
>>> Vector.objects.create(x=0, y=1)
@@ -858,7 +902,9 @@ Usage example::
>>> vector.x_asin, vector.y_asin
(0.0, 1.5707963267948966)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import ASin
@@ -873,7 +919,9 @@ It can also be registered as a transform. For example::
Returns the arctangent of a numeric field or expression.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import ATan
>>> Vector.objects.create(x=3.12, y=6.987)
@@ -881,7 +929,9 @@ Usage example::
>>> vector.x_atan, vector.y_atan
(1.2606282660069106, 1.428638798133829)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import ATan
@@ -896,7 +946,9 @@ It can also be registered as a transform. For example::
Returns the arctangent of ``expression1 / expression2``.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import ATan2
>>> Vector.objects.create(x=2.5, y=1.9)
@@ -912,7 +964,9 @@ Usage example::
Returns the smallest integer greater than or equal to a numeric field or
expression.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Ceil
>>> Vector.objects.create(x=3.12, y=7.0)
@@ -920,7 +974,9 @@ Usage example::
>>> vector.x_ceil, vector.y_ceil
(4.0, 7.0)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Ceil
@@ -935,7 +991,9 @@ It can also be registered as a transform. For example::
Returns the cosine of a numeric field or expression.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Cos
>>> Vector.objects.create(x=-8.0, y=3.1415926)
@@ -943,7 +1001,9 @@ Usage example::
>>> vector.x_cos, vector.y_cos
(-0.14550003380861354, -0.9999999999999986)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Cos
@@ -958,7 +1018,9 @@ It can also be registered as a transform. For example::
Returns the cotangent of a numeric field or expression.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Cot
>>> Vector.objects.create(x=12.0, y=1.0)
@@ -966,7 +1028,9 @@ Usage example::
>>> vector.x_cot, vector.y_cot
(-1.5726734063976826, 0.642092615934331)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Cot
@@ -981,7 +1045,9 @@ It can also be registered as a transform. For example::
Converts a numeric field or expression from radians to degrees.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Degrees
>>> Vector.objects.create(x=-1.57, y=3.14)
@@ -989,7 +1055,9 @@ Usage example::
>>> vector.x_d, vector.y_d
(-89.95437383553924, 179.9087476710785)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Degrees
@@ -1005,7 +1073,9 @@ It can also be registered as a transform. For example::
Returns the value of ``e`` (the natural logarithm base) raised to the power of
a numeric field or expression.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Exp
>>> Vector.objects.create(x=5.4, y=-2.0)
@@ -1013,7 +1083,9 @@ Usage example::
>>> vector.x_exp, vector.y_exp
(221.40641620418717, 0.1353352832366127)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Exp
@@ -1029,7 +1101,9 @@ It can also be registered as a transform. For example::
Returns the largest integer value not greater than a numeric field or
expression.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Floor
>>> Vector.objects.create(x=5.4, y=-2.3)
@@ -1037,7 +1111,9 @@ Usage example::
>>> vector.x_floor, vector.y_floor
(5.0, -3.0)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Floor
@@ -1052,7 +1128,9 @@ It can also be registered as a transform. For example::
Returns the natural logarithm a numeric field or expression.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Ln
>>> Vector.objects.create(x=5.4, y=233.0)
@@ -1060,7 +1138,9 @@ Usage example::
>>> vector.x_ln, vector.y_ln
(1.6863989535702288, 5.4510384535657)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Ln
@@ -1076,7 +1156,9 @@ It can also be registered as a transform. For example::
Accepts two numeric fields or expressions and returns the logarithm of
the first to base of the second.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Log
>>> Vector.objects.create(x=2.0, y=4.0)
@@ -1092,7 +1174,9 @@ Usage example::
Accepts two numeric fields or expressions and returns the remainder of
the first divided by the second (modulo operation).
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Mod
>>> Vector.objects.create(x=5.4, y=2.3)
@@ -1115,7 +1199,9 @@ Returns the value of the mathematical constant ``π``.
Accepts two numeric fields or expressions and returns the value of the first
raised to the power of the second.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Power
>>> Vector.objects.create(x=2, y=-2)
@@ -1130,7 +1216,9 @@ Usage example::
Converts a numeric field or expression from degrees to radians.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Radians
>>> Vector.objects.create(x=-90, y=180)
@@ -1138,7 +1226,9 @@ Usage example::
>>> vector.x_r, vector.y_r
(-1.5707963267948966, 3.141592653589793)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Radians
@@ -1162,7 +1252,9 @@ Rounds a numeric field or expression to ``precision`` (must be an integer)
decimal places. By default, it rounds to the nearest integer. Whether half
values are rounded up or down depends on the database.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Round
>>> Vector.objects.create(x=5.4, y=-2.37)
@@ -1170,7 +1262,9 @@ Usage example::
>>> vector.x_r, vector.y_r
(5.0, -2.4)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Round
@@ -1185,7 +1279,9 @@ It can also be registered as a transform. For example::
Returns the sign (-1, 0, 1) of a numeric field or expression.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Sign
>>> Vector.objects.create(x=5.4, y=-2.3)
@@ -1193,7 +1289,9 @@ Usage example::
>>> vector.x_sign, vector.y_sign
(1, -1)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Sign
@@ -1208,7 +1306,9 @@ It can also be registered as a transform. For example::
Returns the sine of a numeric field or expression.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Sin
>>> Vector.objects.create(x=5.4, y=-2.3)
@@ -1216,7 +1316,9 @@ Usage example::
>>> vector.x_sin, vector.y_sin
(-0.7727644875559871, -0.7457052121767203)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Sin
@@ -1231,7 +1333,9 @@ It can also be registered as a transform. For example::
Returns the square root of a nonnegative numeric field or expression.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Sqrt
>>> Vector.objects.create(x=4.0, y=12.0)
@@ -1239,7 +1343,9 @@ Usage example::
>>> vector.x_sqrt, vector.y_sqrt
(2.0, 3.46410)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Sqrt
@@ -1254,7 +1360,9 @@ It can also be registered as a transform. For example::
Returns the tangent of a numeric field or expression.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Tan
>>> Vector.objects.create(x=0, y=12)
@@ -1262,7 +1370,9 @@ Usage example::
>>> vector.x_tan, vector.y_tan
(0.0, -0.6358599286615808)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import FloatField
>>> from django.db.models.functions import Tan
@@ -1287,7 +1397,9 @@ function.
Like :class:`Length`, it can be registered as a transform on ``IntegerField``.
The default lookup name is ``chr``.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Chr
>>> Author.objects.create(name='Margaret Smith')
@@ -1311,7 +1423,9 @@ This function will never have a null result. On backends where a null argument
results in the entire expression being null, Django will ensure that each null
part is converted to an empty string first.
Usage example::
Usage example:
.. code-block:: pycon
>>> # Get the display name as "name (goes_by)"
>>> from django.db.models import CharField, Value as V
@@ -1333,7 +1447,9 @@ Usage example::
Returns the first ``length`` characters of the given text field or expression.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Left
>>> Author.objects.create(name='Margaret Smith')
@@ -1349,7 +1465,9 @@ Usage example::
Accepts a single text field or expression and returns the number of characters
the value has. If the expression is null, then the length will also be null.
Usage example::
Usage example:
.. code-block:: pycon
>>> # Get the length of the name and goes_by fields
>>> from django.db.models.functions import Length
@@ -1360,7 +1478,9 @@ Usage example::
>>> print(author.name_length, author.goes_by_length)
(14, None)
It can also be registered as a transform. For example::
It can also be registered as a transform. For example:
.. code-block:: pycon
>>> from django.db.models import CharField
>>> from django.db.models.functions import Length
@@ -1378,7 +1498,9 @@ representation.
It can also be registered as a transform as described in :class:`Length`.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Lower
>>> Author.objects.create(name='Margaret Smith')
@@ -1395,7 +1517,9 @@ Returns the value of the given text field or expression padded on the left side
with ``fill_text`` so that the resulting value is ``length`` characters long.
The default ``fill_text`` is a space.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models import Value
>>> from django.db.models.functions import LPad
@@ -1423,7 +1547,9 @@ string.
It can also be registered as a transform as described in :class:`Length`.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import MD5
>>> Author.objects.create(name='Margaret Smith')
@@ -1444,7 +1570,9 @@ than one character long.
It can also be registered as a transform as described in :class:`Length`.
The default lookup name is ``ord``.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Ord
>>> Author.objects.create(name='Margaret Smith')
@@ -1460,7 +1588,9 @@ Usage example::
Returns the value of the given text field or expression repeated ``number``
times.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Repeat
>>> Author.objects.create(name='John', alias='j')
@@ -1478,7 +1608,9 @@ Replaces all occurrences of ``text`` with ``replacement`` in ``expression``.
The default replacement text is the empty string. The arguments to the function
are case-sensitive.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models import Value
>>> from django.db.models.functions import Replace
@@ -1500,7 +1632,9 @@ expression in reverse order.
It can also be registered as a transform as described in :class:`Length`. The
default lookup name is ``reverse``.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Reverse
>>> Author.objects.create(name='Margaret Smith')
@@ -1515,7 +1649,9 @@ Usage example::
Returns the last ``length`` characters of the given text field or expression.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Right
>>> Author.objects.create(name='Margaret Smith')
@@ -1553,7 +1689,9 @@ the string.
They can also be registered as transforms as described in :class:`Length`.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import SHA1
>>> Author.objects.create(name='Margaret Smith')
@@ -1581,7 +1719,9 @@ Returns a positive integer corresponding to the 1-indexed position of the first
occurrence of ``substring`` inside ``string``, or 0 if ``substring`` is not
found.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models import Value as V
>>> from django.db.models.functions import StrIndex
@@ -1613,7 +1753,9 @@ Returns a substring of length ``length`` from the field or expression starting
at position ``pos``. The position is 1-indexed, so the position must be greater
than 0. If ``length`` is ``None``, then the rest of the string will be returned.
Usage example::
Usage example:
.. code-block:: pycon
>>> # Set the alias to the first 5 characters of the name as lowercase
>>> from django.db.models.functions import Lower, Substr
@@ -1631,7 +1773,9 @@ Usage example::
Returns the value of the given text field or expression with leading and
trailing spaces removed.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Trim
>>> Author.objects.create(name=' John ', alias='j')
@@ -1650,7 +1794,9 @@ representation.
It can also be registered as a transform as described in :class:`Length`.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.db.models.functions import Upper
>>> Author.objects.create(name='Margaret Smith')

View File

@@ -232,7 +232,9 @@ directly support ``output_field`` you will need to wrap the expression with
F('active_at') + F('duration'), output_field=DateTimeField()))
When referencing relational fields such as ``ForeignKey``, ``F()`` returns the
primary key value rather than a model instance::
primary key value rather than a model instance:
.. code-block:: pycon
>> car = Company.objects.annotate(built_by=F('manufacturer'))[0]
>> car.manufacturer
@@ -547,7 +549,9 @@ You can add an explicit subquery to a ``QuerySet`` using the ``Subquery``
expression.
For example, to annotate each post with the email address of the author of the
newest comment on that post::
newest comment on that post:
.. code-block:: pycon
>>> from django.db.models import OuterRef, Subquery
>>> newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')
@@ -584,7 +588,9 @@ outer queryset is resolved.
Instances of ``OuterRef`` may be used in conjunction with nested instances
of ``Subquery`` to refer to a containing queryset that isn't the immediate
parent. For example, this queryset would need to be within a nested pair of
``Subquery`` instances to resolve correctly::
``Subquery`` instances to resolve correctly:
.. code-block:: pycon
>>> Book.objects.filter(author=OuterRef(OuterRef('pk')))
@@ -593,7 +599,9 @@ Limiting a subquery to a single column
There are times when a single column must be returned from a ``Subquery``, for
instance, to use a ``Subquery`` as the target of an ``__in`` lookup. To return
all comments for posts published within the last day::
all comments for posts published within the last day:
.. code-block:: pycon
>>> from datetime import timedelta
>>> from django.utils import timezone
@@ -608,7 +616,9 @@ Limiting the subquery to a single row
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To prevent a subquery from returning multiple rows, a slice (``[:1]``) of the
queryset is used::
queryset is used:
.. code-block:: pycon
>>> subquery = Subquery(newest.values('email')[:1])
>>> Post.objects.annotate(newest_commenter_email=subquery)
@@ -630,7 +640,9 @@ many cases it will perform better than a subquery since the database is able to
stop evaluation of the subquery when a first matching row is found.
For example, to annotate each post with whether or not it has a comment from
within the last day::
within the last day:
.. code-block:: pycon
>>> from django.db.models import Exists, OuterRef
>>> from datetime import timedelta
@@ -668,7 +680,9 @@ Filtering on a ``Subquery()`` or ``Exists()`` expressions
``Subquery()`` that returns a boolean value and ``Exists()`` may be used as a
``condition`` in :class:`~django.db.models.expressions.When` expressions, or to
directly filter a queryset::
directly filter a queryset:
.. code-block:: pycon
>>> recent_comments = Comment.objects.filter(...) # From above
>>> Post.objects.filter(Exists(recent_comments))
@@ -684,7 +698,9 @@ combination of :meth:`~.QuerySet.filter`, :meth:`~.QuerySet.values`, and
:meth:`~.QuerySet.annotate` to get the subquery grouping correct.
Assuming both models have a ``length`` field, to find posts where the post
length is greater than the total length of all combined comments::
length is greater than the total length of all combined comments:
.. code-block:: pycon
>>> from django.db.models import OuterRef, Subquery, Sum
>>> comments = Comment.objects.filter(post=OuterRef('pk')).order_by().values('post')
@@ -710,7 +726,9 @@ Raw SQL expressions
.. class:: RawSQL(sql, params, output_field=None)
Sometimes database expressions can't easily express a complex ``WHERE`` clause.
In these edge cases, use the ``RawSQL`` expression. For example::
In these edge cases, use the ``RawSQL`` expression. For example:
.. code-block:: pycon
>>> from django.db.models.expressions import RawSQL
>>> queryset.annotate(val=RawSQL("select col from sometable where othercol = %s", (param,)))
@@ -719,7 +737,9 @@ These extra lookups may not be portable to different database engines (because
you're explicitly writing SQL code) and violate the DRY principle, so you
should avoid them if possible.
``RawSQL`` expressions can also be used as the target of ``__in`` filters::
``RawSQL`` expressions can also be used as the target of ``__in`` filters:
.. code-block:: pycon
>>> queryset.filter(id__in=RawSQL("select id from sometable where col = %s", (param,)))
@@ -732,7 +752,9 @@ should avoid them if possible.
your SQL with user-provided data.
You also must not quote placeholders in the SQL string. This example is
vulnerable to SQL injection because of the quotes around ``%s``::
vulnerable to SQL injection because of the quotes around ``%s``:
.. code-block:: pycon
RawSQL("select col from sometable where othercol = '%s'") # unsafe!
@@ -789,7 +811,9 @@ computation. See :ref:`window-frames` for details.
Support for ``order_by`` by field name references was added.
For example, to annotate each movie with the average rating for the movies by
the same studio in the same genre and release year::
the same studio in the same genre and release year:
.. code-block:: pycon
>>> from django.db.models import Avg, F, Window
>>> Movie.objects.annotate(
@@ -807,7 +831,9 @@ same partition and frame. For example, you could modify the previous example
to also include the best and worst rating in each movie's group (same studio,
genre, and release year) by using three window functions in the same query. The
partition and ordering from the previous example is extracted into a dictionary
to reduce repetition::
to reduce repetition:
.. code-block:: pycon
>>> from django.db.models import Avg, F, Max, Min, Window
>>> window = {
@@ -833,7 +859,9 @@ performing aggregation.
For example, a query that relies on aggregation and has an ``OR``-ed filter
against a window function and a field is not supported. Applying combined
predicates post-aggregation could cause rows that would normally be excluded
from groups to be included::
from groups to be included:
.. code-block:: pycon
>>> qs = Movie.objects.annotate(
>>> category_rank=Window(
@@ -882,7 +910,9 @@ ordinary sequence of rows.
This attribute is set to ``'ROWS'``.
Both classes return SQL with the template::
Both classes return SQL with the template:
.. code-block:: sql
%(frame_type)s BETWEEN %(start)s AND %(end)s
@@ -913,7 +943,9 @@ includes both the ``start`` and ``end`` points, this may be expressed with::
If a movie's "peers" are described as movies released by the same studio in the
same genre in the same year, this ``RowRange`` example annotates each movie
with the average rating of a movie's two prior and two following peers::
with the average rating of a movie's two prior and two following peers:
.. code-block:: pycon
>>> from django.db.models import Avg, F, RowRange, Window
>>> Movie.objects.annotate(
@@ -929,7 +961,9 @@ If the database supports it, you can specify the start and end points based on
values of an expression in the partition. If the ``released`` field of the
``Movie`` model stores the release month of each movies, this ``ValueRange``
example annotates each movie with the average rating of a movie's peers
released between twelve months before and twelve months after the each movie::
released between twelve months before and twelve months after the each movie:
.. code-block:: pycon
>>> from django.db.models import Avg, F, ValueRange, Window
>>> Movie.objects.annotate(
@@ -1016,7 +1050,9 @@ calling the appropriate methods on the wrapped expression.
.. method:: get_source_expressions()
Returns an ordered list of inner expressions. For example::
Returns an ordered list of inner expressions. For example:
.. code-block:: pycon
>>> Sum(F('foo')).get_source_expressions()
[F('foo')]
@@ -1194,7 +1230,9 @@ to play nice with other query expressions::
def set_source_expressions(self, expressions):
self.expressions = expressions
Let's see how it works::
Let's see how it works:
.. code-block:: pycon
>>> from django.db.models import F, Value, CharField
>>> qs = Company.objects.annotate(

View File

@@ -249,7 +249,9 @@ the ``.name`` and ``.value`` properties on the members.
If you don't need to have the human-readable names translated, you can have
them inferred from the member name (replacing underscores with spaces and using
title-case)::
title-case):
.. code-block:: pycon
>>> class Vehicle(models.TextChoices):
... CAR = 'C'
@@ -274,7 +276,9 @@ Django provides an ``IntegerChoices`` class. For example::
It is also possible to make use of the `Enum Functional API
<https://docs.python.org/3/library/enum.html#functional-api>`_ with the caveat
that labels are automatically generated as highlighted above::
that labels are automatically generated as highlighted above:
.. code-block:: pycon
>>> MedalType = models.TextChoices('MedalType', 'GOLD SILVER BRONZE')
>>> MedalType.choices
@@ -1597,7 +1601,9 @@ The possible values for :attr:`~ForeignKey.on_delete` are found in
``Artist`` can be deleted even if that implies deleting an ``Album``
which is referenced by a ``Song``, because ``Song`` also references
``Artist`` itself through a cascading relationship. For example::
``Artist`` itself through a cascading relationship. For example:
.. code-block:: pycon
>>> artist_one = Artist.objects.create(name='artist one')
>>> artist_two = Artist.objects.create(name='artist two')
@@ -2025,7 +2031,9 @@ With the following example::
related_name='supervisor_of',
)
your resulting ``User`` model will have the following attributes::
your resulting ``User`` model will have the following attributes:
.. code-block:: pycon
>>> user = User.objects.get(pk=1)
>>> hasattr(user, 'myspecialuser')

View File

@@ -125,7 +125,9 @@ Refreshing objects from database
================================
If you delete a field from a model instance, accessing it again reloads the
value from the database::
value from the database:
.. code-block:: pycon
>>> obj = MyModel.objects.first()
>>> del obj.field
@@ -435,7 +437,9 @@ Auto-incrementing primary keys
If a model has an :class:`~django.db.models.AutoField` — an auto-incrementing
primary key — then that auto-incremented value will be calculated and saved as
an attribute on your object the first time you call ``save()``::
an attribute on your object the first time you call ``save()``:
.. code-block:: pycon
>>> b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')
>>> b2.id # Returns None, because b2 doesn't have an ID yet.
@@ -467,7 +471,9 @@ Explicitly specifying auto-primary-key values
If a model has an :class:`~django.db.models.AutoField` but you want to define a
new object's ID explicitly when saving, define it explicitly before saving,
rather than relying on the auto-assignment of the ID::
rather than relying on the auto-assignment of the ID:
.. code-block:: pycon
>>> b3 = Blog(id=3, name='Cheddar Talk', tagline='Thoughts on cheese.')
>>> b3.id # Returns 3.
@@ -593,7 +599,9 @@ Updating attributes based on existing fields
Sometimes you'll need to perform a simple arithmetic task on a field, such
as incrementing or decrementing the current value. One way of achieving this is
doing the arithmetic in Python like::
doing the arithmetic in Python like:
.. code-block:: pycon
>>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
>>> product.number_sold += 1
@@ -608,7 +616,9 @@ the update relative to the original field value, rather than as an explicit
assignment of a new value. Django provides :class:`F expressions
<django.db.models.F>` for performing this kind of relative update. Using
:class:`F expressions <django.db.models.F>`, the previous example is expressed
as::
as:
.. code-block:: pycon
>>> from django.db.models import F
>>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
@@ -882,7 +892,7 @@ For example::
name = models.CharField(max_length=60)
shirt_size = models.CharField(max_length=2, choices=SHIRT_SIZES)
::
.. code-block:: pycon
>>> p = Person(name="Fred Flintstone", shirt_size="L")
>>> p.save()

View File

@@ -234,20 +234,26 @@ not be looking at your Django code. For example::
and ``set_RELATED_order()``, where ``RELATED`` is the lowercased model name. For
example, assuming that a ``Question`` object has multiple related ``Answer``
objects, the list returned contains the primary keys of the related ``Answer``
objects::
objects:
.. code-block:: pycon
>>> question = Question.objects.get(id=1)
>>> question.get_answer_order()
[1, 2, 3]
The order of a ``Question`` object's related ``Answer`` objects can be set by
passing in a list of ``Answer`` primary keys::
passing in a list of ``Answer`` primary keys:
.. code-block:: pycon
>>> question.set_answer_order([3, 1, 2])
The related objects also get two methods, ``get_next_in_order()`` and
``get_previous_in_order()``, which can be used to access those objects in their
proper order. Assuming the ``Answer`` objects are ordered by ``id``::
proper order. Assuming the ``Answer`` objects are ordered by ``id``:
.. code-block:: pycon
>>> answer = Answer.objects.get(id=2)
>>> answer.get_next_in_order()

View File

@@ -107,7 +107,9 @@ than the results that are currently in the database.
If you only want to pickle the necessary information to recreate the
``QuerySet`` from the database at a later time, pickle the ``query`` attribute
of the ``QuerySet``. You can then recreate the original ``QuerySet`` (without
any results loaded) using some code like this::
any results loaded) using some code like this:
.. code-block:: pycon
>>> import pickle
>>> query = pickle.loads(s) # Assuming 's' is the pickled string.
@@ -122,7 +124,9 @@ described here.
.. admonition:: Restrictions on ``QuerySet.values_list()``
If you recreate :meth:`QuerySet.values_list` using the pickled ``query``
attribute, it will be converted to :meth:`QuerySet.values`::
attribute, it will be converted to :meth:`QuerySet.values`:
.. code-block:: pycon
>>> import pickle
>>> qs = Blog.objects.values_list('id', 'name')
@@ -277,7 +281,9 @@ that reference a single field can be anonymous arguments. Everything
else must be a keyword argument.
For example, if you were manipulating a list of blogs, you may want
to determine how many entries have been made in each blog::
to determine how many entries have been made in each blog:
.. code-block:: pycon
>>> from django.db.models import Count
>>> q = Blog.objects.annotate(Count('entry'))
@@ -290,7 +296,9 @@ to determine how many entries have been made in each blog::
The ``Blog`` model doesn't define an ``entry__count`` attribute by itself,
but by using a keyword argument to specify the aggregate function, you can
control the name of the annotation::
control the name of the annotation:
.. code-block:: pycon
>>> q = Blog.objects.annotate(number_of_entries=Count('entry'))
# The number of entries on the first blog, using the name provided
@@ -313,7 +321,9 @@ Not selecting the unused value removes redundant work from the database which
should result in better performance.
For example, if you want to find blogs with more than 5 entries, but are not
interested in the exact number of entries, you could do this::
interested in the exact number of entries, you could do this:
.. code-block:: pycon
>>> from django.db.models import Count
>>> blogs = Blog.objects.alias(entries=Count('entry')).filter(entries__gt=5)
@@ -532,7 +542,9 @@ field names, the database will only compare the specified field names.
value in column ``a``. If you don't specify an order, you'll get some
arbitrary row.
Examples (those after the first will only work on PostgreSQL)::
Examples (those after the first will only work on PostgreSQL):
.. code-block:: pycon
>>> Author.objects.distinct()
[...]
@@ -579,7 +591,9 @@ Each of those dictionaries represents an object, with the keys corresponding to
the attribute names of model objects.
This example compares the dictionaries of ``values()`` with the normal model
objects::
objects:
.. code-block:: pycon
# This list contains a Blog object.
>>> Blog.objects.filter(name__startswith='Beatles')
@@ -595,7 +609,9 @@ the fields, each dictionary will contain only the field keys/values for the
fields you specify. If you don't specify the fields, each dictionary will
contain a key and value for every field in the database table.
Example::
Example:
.. code-block:: pycon
>>> Blog.objects.values()
<QuerySet [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]>
@@ -603,14 +619,18 @@ Example::
<QuerySet [{'id': 1, 'name': 'Beatles Blog'}]>
The ``values()`` method also takes optional keyword arguments,
``**expressions``, which are passed through to :meth:`annotate`::
``**expressions``, which are passed through to :meth:`annotate`:
.. code-block:: pycon
>>> from django.db.models.functions import Lower
>>> Blog.objects.values(lower_name=Lower('name'))
<QuerySet [{'lower_name': 'beatles blog'}]>
You can use built-in and :doc:`custom lookups </howto/custom-lookups>` in
ordering. For example::
ordering. For example:
.. code-block:: pycon
>>> from django.db.models import CharField
>>> from django.db.models.functions import Lower
@@ -620,7 +640,9 @@ ordering. For example::
An aggregate within a ``values()`` clause is applied before other arguments
within the same ``values()`` clause. If you need to group by another value,
add it to an earlier ``values()`` clause instead. For example::
add it to an earlier ``values()`` clause instead. For example:
.. code-block:: pycon
>>> from django.db.models import Count
>>> Blog.objects.values('entry__authors', entries=Count('entry'))
@@ -639,7 +661,9 @@ A few subtleties that are worth mentioning:
or ``foo_id`` and you will get back the same thing (the dictionary key
will match the field name you passed in).
For example::
For example:
.. code-block:: pycon
>>> Entry.objects.values()
<QuerySet [{'blog_id': 1, 'headline': 'First Entry', ...}, ...]>
@@ -666,7 +690,9 @@ A few subtleties that are worth mentioning:
* Combining transforms and aggregates requires the use of two :meth:`annotate`
calls, either explicitly or as keyword arguments to :meth:`values`. As above,
if the transform has been registered on the relevant field type the first
:meth:`annotate` can be omitted, thus the following examples are equivalent::
:meth:`annotate` can be omitted, thus the following examples are equivalent:
.. code-block:: pycon
>>> from django.db.models import CharField, Count
>>> from django.db.models.functions import Lower
@@ -698,7 +724,9 @@ but it doesn't really matter. This is your chance to really flaunt your
individualism.
You can also refer to fields on related models with reverse relations through
``OneToOneField``, ``ForeignKey`` and ``ManyToManyField`` attributes::
``OneToOneField``, ``ForeignKey`` and ``ManyToManyField`` attributes:
.. code-block:: pycon
>>> Blog.objects.values('name', 'entry__headline')
<QuerySet [{'name': 'My blog', 'entry__headline': 'An entry'},
@@ -728,7 +756,9 @@ You can also refer to fields on related models with reverse relations through
This is similar to ``values()`` except that instead of returning dictionaries,
it returns tuples when iterated over. Each tuple contains the value from the
respective field or expression passed into the ``values_list()`` call — so the
first item is the first field, etc. For example::
first item is the first field, etc. For example:
.. code-block:: pycon
>>> Entry.objects.values_list('id', 'headline')
<QuerySet [(1, 'First entry'), ...]>
@@ -738,7 +768,9 @@ first item is the first field, etc. For example::
If you only pass in a single field, you can also pass in the ``flat``
parameter. If ``True``, this will mean the returned results are single values,
rather than one-tuples. An example should make the difference clearer::
rather than one-tuples. An example should make the difference clearer:
.. code-block:: pycon
>>> Entry.objects.values_list('id').order_by('id')
<QuerySet[(1,), (2,), (3,), ...]>
@@ -749,7 +781,9 @@ rather than one-tuples. An example should make the difference clearer::
It is an error to pass in ``flat`` when there is more than one field.
You can pass ``named=True`` to get results as a
:func:`~python:collections.namedtuple`::
:func:`~python:collections.namedtuple`:
.. code-block:: pycon
>>> Entry.objects.values_list('id', 'headline', named=True)
<QuerySet [Row(id=1, headline='First entry'), ...]>
@@ -761,7 +795,9 @@ If you don't pass any values to ``values_list()``, it will return all the
fields in the model, in the order they were declared.
A common need is to get a specific field value of a certain model instance. To
achieve that, use ``values_list()`` followed by a ``get()`` call::
achieve that, use ``values_list()`` followed by a ``get()`` call:
.. code-block:: pycon
>>> Entry.objects.values_list('headline', flat=True).get(pk=1)
'First entry'
@@ -773,7 +809,9 @@ other multivalued relations (such as the one-to-many relation of a reverse
foreign key) because the "one row, one object" assumption doesn't hold.
For example, notice the behavior when querying across a
:class:`~django.db.models.ManyToManyField`::
:class:`~django.db.models.ManyToManyField`:
.. code-block:: pycon
>>> Author.objects.values_list('name', 'entry__headline')
<QuerySet [('Noam Chomsky', 'Impressions of Gaza'),
@@ -785,7 +823,9 @@ Authors with multiple entries appear multiple times and authors without any
entries have ``None`` for the entry headline.
Similarly, when querying a reverse foreign key, ``None`` appears for entries
not having any author::
not having any author:
.. code-block:: pycon
>>> Entry.objects.values_list('authors')
<QuerySet [('Noam Chomsky',), ('George Orwell',), (None,)]>
@@ -823,7 +863,9 @@ given ``type``.
``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or
``'DESC'``. This specifies how to order the results.
Examples::
Examples:
.. code-block:: pycon
>>> Entry.objects.dates('pub_date', 'year')
[datetime.date(2005, 1, 1)]
@@ -899,7 +941,9 @@ Calling ``none()`` will create a queryset that never returns any objects and no
query will be executed when accessing the results. A ``qs.none()`` queryset
is an instance of ``EmptyQuerySet``.
Examples::
Examples:
.. code-block:: pycon
>>> Entry.objects.none()
<QuerySet []>
@@ -941,7 +985,9 @@ of other models. Passing different models works as long as the ``SELECT`` list
is the same in all ``QuerySet``\s (at least the types, the names don't matter
as long as the types are in the same order). In such cases, you must use the
column names from the first ``QuerySet`` in ``QuerySet`` methods applied to the
resulting ``QuerySet``. For example::
resulting ``QuerySet``. For example:
.. code-block:: pycon
>>> qs1 = Author.objects.values_list('name')
>>> qs2 = Entry.objects.values_list('headline')
@@ -972,7 +1018,9 @@ See :meth:`union` for some restrictions.
.. method:: difference(*other_qs)
Uses SQL's ``EXCEPT`` operator to keep only elements present in the
``QuerySet`` but not in some other ``QuerySet``\s. For example::
``QuerySet`` but not in some other ``QuerySet``\s. For example:
.. code-block:: pycon
>>> qs1.difference(qs2, qs3)
@@ -1078,7 +1126,9 @@ specified. This is not recommended in most cases as it is likely to make the
underlying query more complex, and return more data, than is actually needed.
If you need to clear the list of related fields added by past calls of
``select_related`` on a ``QuerySet``, you can pass ``None`` as a parameter::
``select_related`` on a ``QuerySet``, you can pass ``None`` as a parameter:
.. code-block:: pycon
>>> without_relations = queryset.select_related(None)
@@ -1133,7 +1183,9 @@ For example, suppose you have these models::
", ".join(topping.name for topping in self.toppings.all()),
)
and run::
and run:
.. code-block:: pycon
>>> Pizza.objects.all()
["Hawaiian (ham, pineapple)", "Seafood (prawns, smoked salmon)"...
@@ -1203,12 +1255,16 @@ fields. Suppose we have an additional model to the example above::
The following are all legal:
.. code-block:: pycon
>>> Restaurant.objects.prefetch_related('pizzas__toppings')
This will prefetch all pizzas belonging to restaurants, and all toppings
belonging to those pizzas. This will result in a total of 3 database queries -
one for the restaurants, one for the pizzas, and one for the toppings.
.. code-block:: pycon
>>> Restaurant.objects.prefetch_related('best_pizza__toppings')
This will fetch the best pizza and all the toppings for the best pizza for each
@@ -1216,7 +1272,9 @@ restaurant. This will be done in 3 database queries - one for the restaurants,
one for the 'best pizzas', and one for the toppings.
The ``best_pizza`` relationship could also be fetched using ``select_related``
to reduce the query count to 2::
to reduce the query count to 2:
.. code-block:: pycon
>>> Restaurant.objects.select_related('best_pizza').prefetch_related('best_pizza__toppings')
@@ -1330,7 +1388,9 @@ where prefetching with a custom ``QuerySet`` is useful:
When using multiple databases, ``Prefetch`` will respect your choice of
database. If the inner query does not specify a database, it will use the
database selected by the outer query. All of the following are valid::
database selected by the outer query. All of the following are valid:
.. code-block:: pycon
>>> # Both inner and outer queries will use the 'replica' database
>>> Restaurant.objects.prefetch_related('pizzas__toppings').using('replica')
@@ -1398,14 +1458,18 @@ generated by a ``QuerySet``.
that we can enhance the QuerySet API to allow removing ``extra()``. We are
no longer improving or fixing bugs for this method.
For example, this use of ``extra()``::
For example, this use of ``extra()``:
.. code-block:: pycon
>>> qs.extra(
... select={'val': "select col from sometable where othercol = %s"},
... select_params=(someparam,),
... )
is equivalent to::
is equivalent to:
.. code-block:: pycon
>>> qs.annotate(val=RawSQL("select col from sometable where othercol = %s", (someparam,)))
@@ -1772,7 +1836,9 @@ evaluated against if you are using more than one database. The only argument
this method takes is the alias of a database, as defined in
:setting:`DATABASES`.
For example::
For example:
.. code-block:: pycon
# queries the database with the 'default' alias.
>>> Entry.objects.all()
@@ -1840,7 +1906,9 @@ lock, that still allows creating rows that merely reference locked rows
PostgreSQL documentation has more details about `row-level lock modes
<https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-ROWS>`_.
You can't use ``select_for_update()`` on nullable relations::
You can't use ``select_for_update()`` on nullable relations:
.. code-block:: pycon
>>> Person.objects.select_related('hometown').select_for_update()
Traceback (most recent call last):
@@ -1848,7 +1916,9 @@ You can't use ``select_for_update()`` on nullable relations::
django.db.utils.NotSupportedError: FOR UPDATE cannot be applied to the nullable side of an outer join
To avoid that restriction, you can exclude null objects if you don't care about
them::
them:
.. code-block:: pycon
>>> Person.objects.select_related('hometown').select_for_update().exclude(hometown=None)
<QuerySet [<Person: ...)>, ...]>
@@ -2199,7 +2269,9 @@ whenever a request to a page has a side effect on your data. For more, see
chapters = models.ManyToManyField(Chapter)
You can use ``get_or_create()`` through Book's chapters field, but it only
fetches inside the context of that book::
fetches inside the context of that book:
.. code-block:: pycon
>>> book = Book.objects.create(title="Ulysses")
>>> book.chapters.get_or_create(title="Telemachus")
@@ -2292,7 +2364,9 @@ exists in the database, an :exc:`~django.db.IntegrityError` is raised.
This method inserts the provided list of objects into the database in an
efficient manner (generally only 1 query, no matter how many objects there
are), and returns created objects as a list, in the same order as provided::
are), and returns created objects as a list, in the same order as provided:
.. code-block:: pycon
>>> objs = Entry.objects.bulk_create([
... Entry(headline='This is a test'),
@@ -2372,7 +2446,9 @@ support it).
This method efficiently updates the given fields on the provided model
instances, generally with one query, and returns the number of objects
updated::
updated:
.. code-block:: pycon
>>> objs = [
... Entry.objects.create(headline='Entry 1'),
@@ -2465,7 +2541,9 @@ in the queryset are returned. ``field_name`` must be a unique field or a
distinct field (if there's only one field specified in :meth:`distinct`).
``field_name`` defaults to the primary key.
Example::
Example:
.. code-block:: pycon
>>> Blog.objects.in_bulk([1])
{1: <Blog: Beatles Blog>}
@@ -2726,14 +2804,18 @@ aggregated. Complex aggregates cannot use anonymous arguments and must specify
a keyword argument as an alias.
For example, when you are working with blog entries, you may want to know the
number of authors that have contributed blog entries::
number of authors that have contributed blog entries:
.. code-block:: pycon
>>> from django.db.models import Count
>>> q = Blog.objects.aggregate(Count('entry'))
{'entry__count': 16}
By using a keyword argument to specify the aggregate function, you can
control the name of the aggregation value that is returned::
control the name of the aggregation value that is returned:
.. code-block:: pycon
>>> q = Blog.objects.aggregate(number_of_entries=Count('entry'))
{'number_of_entries': 16}
@@ -2832,31 +2914,41 @@ the number of rows matched (which may not be equal to the number of rows
updated if some rows already have the new value).
For example, to turn comments off for all blog entries published in 2010,
you could do this::
you could do this:
.. code-block:: pycon
>>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False)
(This assumes your ``Entry`` model has fields ``pub_date`` and ``comments_on``.)
You can update multiple fields — there's no limit on how many. For example,
here we update the ``comments_on`` and ``headline`` fields::
here we update the ``comments_on`` and ``headline`` fields:
.. code-block:: pycon
>>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False, headline='This is old')
The ``update()`` method is applied instantly, and the only restriction on the
:class:`.QuerySet` that is updated is that it can only update columns in the
model's main table, not on related models. You can't do this, for example::
model's main table, not on related models. You can't do this, for example:
.. code-block:: pycon
>>> Entry.objects.update(blog__name='foo') # Won't work!
Filtering based on related fields is still possible, though::
Filtering based on related fields is still possible, though:
.. code-block:: pycon
>>> Entry.objects.filter(blog__id=1).update(comments_on=True)
You cannot call ``update()`` on a :class:`.QuerySet` that has had a slice taken
or can otherwise no longer be filtered.
The ``update()`` method returns the number of affected rows::
The ``update()`` method returns the number of affected rows:
.. code-block:: pycon
>>> Entry.objects.filter(id=64).update(comments_on=True)
1
@@ -2930,7 +3022,9 @@ The ``delete()`` is applied instantly. You cannot call ``delete()`` on a
:class:`.QuerySet` that has had a slice taken or can otherwise no longer be
filtered.
For example, to delete all the entries in a particular blog::
For example, to delete all the entries in a particular blog:
.. code-block:: pycon
>>> b = Blog.objects.get(pk=1)
@@ -2941,7 +3035,9 @@ For example, to delete all the entries in a particular blog::
By default, Django's :class:`~django.db.models.ForeignKey` emulates the SQL
constraint ``ON DELETE CASCADE`` — in other words, any objects with foreign
keys pointing at the objects to be deleted will be deleted along with them.
For example::
For example:
.. code-block:: pycon
>>> blogs = Blog.objects.all()
@@ -3000,7 +3096,9 @@ database would execute the query, including any indexes or joins that would be
used. Knowing these details may help you improve the performance of slow
queries.
For example, when using PostgreSQL::
For example, when using PostgreSQL:
.. code-block:: pycon
>>> print(Blog.objects.filter(title='My Blog').explain())
Seq Scan on blog (cost=0.00..35.50 rows=10 width=12)
@@ -3019,7 +3117,9 @@ default, which is usually text-based. PostgreSQL supports ``'TEXT'``,
PostgreSQL's ``'TEXT'`` output and is used by default, if supported.
Some databases accept flags that can return more information about the query.
Pass these flags as keyword arguments. For example, when using PostgreSQL::
Pass these flags as keyword arguments. For example, when using PostgreSQL:
.. code-block:: pycon
>>> print(Blog.objects.filter(title='My Blog').explain(verbose=True, analyze=True))
Seq Scan on public.blog (cost=0.00..35.50 rows=10 width=12) (actual time=0.004..0.004 rows=10 loops=1)
@@ -4044,7 +4144,9 @@ in code that receives a list of model instances as opposed to a ``QuerySet``;
for example, when fetching models from a cache or instantiating them manually.
Pass an iterable of model instances (must all be of the same class) and the
lookups or :class:`Prefetch` objects you want to prefetch for. For example::
lookups or :class:`Prefetch` objects you want to prefetch for. For example:
.. code-block:: pycon
>>> from django.db.models import prefetch_related_objects
>>> restaurants = fetch_top_restaurants_from_cache() # A list of Restaurants
@@ -4073,7 +4175,9 @@ relationship but on the annotation name (``pizzas_vegetarian`` in example
below).
For example, to find restaurants that have vegetarian pizzas with
``'mozzarella'`` in the name::
``'mozzarella'`` in the name:
.. code-block:: pycon
>>> from django.db.models import FilteredRelation, Q
>>> Restaurant.objects.annotate(
@@ -4082,7 +4186,9 @@ For example, to find restaurants that have vegetarian pizzas with
... ),
... ).filter(pizzas_vegetarian__name__icontains='mozzarella')
If there are a large number of pizzas, this queryset performs better than::
If there are a large number of pizzas, this queryset performs better than:
.. code-block:: pycon
>>> Restaurant.objects.filter(
... pizzas__vegetarian=True,

View File

@@ -43,7 +43,9 @@ Related objects reference
Adds the specified model objects to the related object set.
Example::
Example:
.. code-block:: pycon
>>> b = Blog.objects.get(id=1)
>>> e = Entry.objects.get(id=234)
@@ -88,7 +90,9 @@ Related objects reference
*Asynchronous version*: ``acreate``
Creates a new object, saves it and puts it in the related object set.
Returns the newly created object::
Returns the newly created object:
.. code-block:: pycon
>>> b = Blog.objects.get(id=1)
>>> e = b.entry_set.create(
@@ -99,7 +103,9 @@ Related objects reference
# No need to call e.save() at this point -- it's already been saved.
This is equivalent to (but simpler than)::
This is equivalent to (but simpler than):
.. code-block:: pycon
>>> b = Blog.objects.get(id=1)
>>> e = Entry(
@@ -129,7 +135,9 @@ Related objects reference
*Asynchronous version*: ``aremove``
Removes the specified model objects from the related object set::
Removes the specified model objects from the related object set:
.. code-block:: pycon
>>> b = Blog.objects.get(id=1)
>>> e = Entry.objects.get(id=234)
@@ -176,7 +184,9 @@ Related objects reference
*Asynchronous version*: ``aclear``
Removes all objects from the related object set::
Removes all objects from the related object set:
.. code-block:: pycon
>>> b = Blog.objects.get(id=1)
>>> b.entry_set.clear()
@@ -200,7 +210,9 @@ Related objects reference
*Asynchronous version*: ``aset``
Replace the set of related objects::
Replace the set of related objects:
.. code-block:: pycon
>>> new_list = [obj1, obj2, obj3]
>>> e.related_set.set(new_list)