1
0
mirror of https://github.com/django/django.git synced 2025-10-24 06:06: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

@@ -12,7 +12,9 @@ module. They are described in more detail in the `PostgreSQL docs
.. note::
All functions come without default aliases, so you must explicitly provide
one. For example::
one. For example:
.. code-block:: pycon
>>> SomeModel.objects.aggregate(arr=ArrayAgg('somefield'))
{'arr': [0, 1, 2]}
@@ -100,6 +102,8 @@ General-purpose aggregation functions
published = models.BooleanField()
rank = models.IntegerField()
.. code-block:: pycon
>>> from django.db.models import Q
>>> from django.contrib.postgres.aggregates import BoolAnd
>>> Comment.objects.aggregate(booland=BoolAnd('published'))
@@ -122,6 +126,8 @@ General-purpose aggregation functions
published = models.BooleanField()
rank = models.IntegerField()
.. code-block:: pycon
>>> from django.db.models import Q
>>> from django.contrib.postgres.aggregates import BoolOr
>>> Comment.objects.aggregate(boolor=BoolOr('published'))
@@ -163,6 +169,8 @@ General-purpose aggregation functions
end = models.DateTimeField()
requirements = models.JSONField(blank=True, null=True)
.. code-block:: pycon
>>> from django.contrib.postgres.aggregates import JSONBAgg
>>> Room.objects.annotate(
... requirements=JSONBAgg(
@@ -217,6 +225,8 @@ General-purpose aggregation functions
headline = models.CharField(max_length=100)
publications = models.ManyToManyField(Publication)
.. code-block:: pycon
>>> article = Article.objects.create(headline="NASA uses Python")
>>> article.publications.create(title="The Python Journal")
<Publication: Publication object (1)>
@@ -354,7 +364,9 @@ field or an expression returning a numeric data. Both are required.
Usage examples
==============
We will use this example table::
We will use this example table:
.. code-block:: text
| FIELD1 | FIELD2 | FIELD3 |
|--------|--------|--------|
@@ -362,8 +374,9 @@ We will use this example table::
| bar | 2 | (null) |
| test | 3 | 13 |
Here's some examples of some of the general-purpose aggregation functions:
Here's some examples of some of the general-purpose aggregation functions::
.. code-block:: pycon
>>> TestModel.objects.aggregate(result=StringAgg('field1', delimiter=';'))
{'result': 'foo;bar;test'}
@@ -374,7 +387,9 @@ Here's some examples of some of the general-purpose aggregation functions::
The next example shows the usage of statistical aggregate functions. The
underlying math will be not described (you can read about this, for example, at
`wikipedia <https://en.wikipedia.org/wiki/Regression_analysis>`_)::
`wikipedia <https://en.wikipedia.org/wiki/Regression_analysis>`_):
.. code-block:: pycon
>>> TestModel.objects.aggregate(count=RegrCount(y='field3', x='field2'))
{'count': 2}

View File

@@ -22,7 +22,9 @@ in the way that it does not act as an aggregate function and does not require
an SQL ``GROUP BY`` clause to build the list of values.
For example, if you want to annotate all related books to an author as JSON
objects::
objects:
.. code-block:: pycon
>>> from django.db.models import OuterRef
>>> from django.db.models.functions import JSONObject

View File

@@ -127,7 +127,9 @@ We will use the following example model::
The :lookup:`contains` lookup is overridden on :class:`ArrayField`. The
returned objects will be those where the values passed are a subset of the
data. It uses the SQL operator ``@>``. For example::
data. It uses the SQL operator ``@>``. For example:
.. code-block:: pycon
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
>>> Post.objects.create(name='Second post', tags=['thoughts'])
@@ -149,7 +151,9 @@ data. It uses the SQL operator ``@>``. For example::
This is the inverse of the :lookup:`contains <arrayfield.contains>` lookup -
the objects returned will be those where the data is a subset of the values
passed. It uses the SQL operator ``<@``. For example::
passed. It uses the SQL operator ``<@``. For example:
.. code-block:: pycon
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
>>> Post.objects.create(name='Second post', tags=['thoughts'])
@@ -167,7 +171,9 @@ passed. It uses the SQL operator ``<@``. For example::
~~~~~~~~~~~
Returns objects where the data shares any results with the values passed. Uses
the SQL operator ``&&``. For example::
the SQL operator ``&&``. For example:
.. code-block:: pycon
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
>>> Post.objects.create(name='Second post', tags=['thoughts', 'tutorial'])
@@ -193,7 +199,9 @@ the SQL operator ``&&``. For example::
~~~~~~~
Returns the length of the array. The lookups available afterward are those
available for :class:`~django.db.models.IntegerField`. For example::
available for :class:`~django.db.models.IntegerField`. For example:
.. code-block:: pycon
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
>>> Post.objects.create(name='Second post', tags=['thoughts'])
@@ -209,7 +217,9 @@ Index transforms
Index transforms index into the array. Any non-negative integer can be used.
There are no errors if it exceeds the :attr:`size <ArrayField.size>` of the
array. The lookups available after the transform are those from the
:attr:`base_field <ArrayField.base_field>`. For example::
:attr:`base_field <ArrayField.base_field>`. For example:
.. code-block:: pycon
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
>>> Post.objects.create(name='Second post', tags=['thoughts'])
@@ -236,7 +246,9 @@ Slice transforms
Slice transforms take a slice of the array. Any two non-negative integers can
be used, separated by a single underscore. The lookups available after the
transform do not change. For example::
transform do not change. For example:
.. code-block:: pycon
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
>>> Post.objects.create(name='Second post', tags=['thoughts'])
@@ -374,7 +386,9 @@ We will use the following example model::
Key lookups
~~~~~~~~~~~
To query based on a given key, you can use that key as the lookup name::
To query based on a given key, you can use that key as the lookup name:
.. code-block:: pycon
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
>>> Dog.objects.create(name='Meg', data={'breed': 'collie'})
@@ -382,12 +396,16 @@ To query based on a given key, you can use that key as the lookup name::
>>> Dog.objects.filter(data__breed='collie')
<QuerySet [<Dog: Meg>]>
You can chain other lookups after key lookups::
You can chain other lookups after key lookups:
.. code-block:: pycon
>>> Dog.objects.filter(data__breed__contains='l')
<QuerySet [<Dog: Rufus>, <Dog: Meg>]>
or use ``F()`` expressions to annotate a key value. For example::
or use ``F()`` expressions to annotate a key value. For example:
.. code-block:: pycon
>>> from django.db.models import F
>>> rufus = Dog.objects.annotate(breed=F("data__breed"))[0]
@@ -419,7 +437,9 @@ need to use the :lookup:`hstorefield.contains` lookup instead.
The :lookup:`contains` lookup is overridden on
:class:`~django.contrib.postgres.fields.HStoreField`. The returned objects are
those where the given ``dict`` of key-value pairs are all contained in the
field. It uses the SQL operator ``@>``. For example::
field. It uses the SQL operator ``@>``. For example:
.. code-block:: pycon
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
@@ -439,7 +459,9 @@ field. It uses the SQL operator ``@>``. For example::
This is the inverse of the :lookup:`contains <hstorefield.contains>` lookup -
the objects returned will be those where the key-value pairs on the object are
a subset of those in the value passed. It uses the SQL operator ``<@``. For
example::
example:
.. code-block:: pycon
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
@@ -457,7 +479,9 @@ example::
~~~~~~~~~~~
Returns objects where the given key is in the data. Uses the SQL operator
``?``. For example::
``?``. For example:
.. code-block:: pycon
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
@@ -471,7 +495,9 @@ Returns objects where the given key is in the data. Uses the SQL operator
~~~~~~~~~~~~~~~~
Returns objects where any of the given keys are in the data. Uses the SQL
operator ``?|``. For example::
operator ``?|``. For example:
.. code-block:: pycon
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
>>> Dog.objects.create(name='Meg', data={'owner': 'Bob'})
@@ -486,7 +512,9 @@ operator ``?|``. For example::
~~~~~~~~~~~~
Returns objects where all of the given keys are in the data. Uses the SQL operator
``?&``. For example::
``?&``. For example:
.. code-block:: pycon
>>> Dog.objects.create(name='Rufus', data={})
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
@@ -503,7 +531,9 @@ Returns objects where the array of keys is the given value. Note that the order
is not guaranteed to be reliable, so this transform is mainly useful for using
in conjunction with lookups on
:class:`~django.contrib.postgres.fields.ArrayField`. Uses the SQL function
``akeys()``. For example::
``akeys()``. For example:
.. code-block:: pycon
>>> Dog.objects.create(name='Rufus', data={'toy': 'bone'})
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
@@ -520,7 +550,9 @@ Returns objects where the array of values is the given value. Note that the
order is not guaranteed to be reliable, so this transform is mainly useful for
using in conjunction with lookups on
:class:`~django.contrib.postgres.fields.ArrayField`. Uses the SQL function
``avals()``. For example::
``avals()``. For example:
.. code-block:: pycon
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
@@ -646,7 +678,9 @@ model::
def __str__(self):
return self.name
We will also use the following example objects::
We will also use the following example objects:
.. code-block:: pycon
>>> import datetime
>>> from django.utils import timezone
@@ -689,7 +723,9 @@ The ``contained_by`` lookup is also available on the non-range field types:
:class:`~django.db.models.BigIntegerField`,
:class:`~django.db.models.DecimalField`, :class:`~django.db.models.FloatField`,
:class:`~django.db.models.DateField`, and
:class:`~django.db.models.DateTimeField`. For example::
:class:`~django.db.models.DateTimeField`. For example:
.. code-block:: pycon
>>> from django.db.backends.postgresql.psycopg_any import DateTimeTZRange
>>> Event.objects.filter(

View File

@@ -23,7 +23,9 @@ Fields
It specifies the underlying form field for the array. This is not used
to render any HTML, but it is used to process the submitted data and
validate it. For example::
validate it. For example:
.. code-block:: pycon
>>> from django import forms
>>> from django.contrib.postgres.forms import SimpleArrayField
@@ -45,7 +47,9 @@ Fields
This is an optional argument which defaults to a comma: ``,``. This
value is used to split the submitted data. It allows you to chain
``SimpleArrayField`` for multidimensional data::
``SimpleArrayField`` for multidimensional data:
.. code-block:: pycon
>>> from django import forms
>>> from django.contrib.postgres.forms import SimpleArrayField

View File

@@ -20,7 +20,9 @@ operation to install it.
.. _pgcrypto extension: https://www.postgresql.org/docs/current/pgcrypto.html
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.contrib.postgres.functions import RandomUUID
>>> Article.objects.update(uuid=RandomUUID())
@@ -41,7 +43,9 @@ sets up a transaction and thus sets the time that ``TransactionNow()`` will
return; nested calls create savepoints which do not affect the transaction
time.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.contrib.postgres.functions import TransactionNow
>>> Article.objects.filter(published__lte=TransactionNow())

View File

@@ -23,7 +23,9 @@ extension using the
operation.
The ``trigram_similar`` lookup can be used on
:class:`~django.db.models.CharField` and :class:`~django.db.models.TextField`::
:class:`~django.db.models.CharField` and :class:`~django.db.models.TextField`:
.. code-block:: pycon
>>> City.objects.filter(name__trigram_similar="Middlesborough")
['<City: Middlesbrough>']
@@ -47,7 +49,9 @@ extension using the
operation.
The ``trigram_word_similar`` lookup can be used on
:class:`~django.db.models.CharField` and :class:`~django.db.models.TextField`::
:class:`~django.db.models.CharField` and :class:`~django.db.models.TextField`:
.. code-block:: pycon
>>> Sentence.objects.filter(name__trigram_word_similar='Middlesborough')
['<Sentence: Gumby rides on the path of Middlesbrough>']
@@ -91,7 +95,9 @@ operation is available if you want to perform this activation using migrations).
.. _unaccent extension on PostgreSQL: https://www.postgresql.org/docs/current/unaccent.html
The ``unaccent`` lookup can be used on
:class:`~django.db.models.CharField` and :class:`~django.db.models.TextField`::
:class:`~django.db.models.CharField` and :class:`~django.db.models.TextField`:
.. code-block:: pycon
>>> City.objects.filter(name__unaccent="México")
['<City: Mexico>']

View File

@@ -22,7 +22,9 @@ The ``search`` lookup
.. fieldlookup:: search
A common way to use full text search is to search a single term against a
single column in the database. For example::
single column in the database. For example:
.. code-block:: pycon
>>> Entry.objects.filter(body_text__search='Cheese')
[<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>]
@@ -42,7 +44,9 @@ To use the ``search`` lookup, ``'django.contrib.postgres'`` must be in your
Searching against a single field is great but rather limiting. The ``Entry``
instances we're searching belong to a ``Blog``, which has a ``tagline`` field.
To query against both fields, use a ``SearchVector``::
To query against both fields, use a ``SearchVector``:
.. code-block:: pycon
>>> from django.contrib.postgres.search import SearchVector
>>> Entry.objects.annotate(
@@ -56,7 +60,9 @@ arguments will be concatenated together using a space so that the search
document includes them all.
``SearchVector`` objects can be combined together, allowing you to reuse them.
For example::
For example:
.. code-block:: pycon
>>> Entry.objects.annotate(
... search=SearchVector('body_text') + SearchVector('blog__tagline'),
@@ -96,7 +102,9 @@ Examples:
>>> SearchQuery("'tomato' & ('red' | 'green')", search_type='raw') # boolean operators
>>> SearchQuery("'tomato' ('red' OR 'green')", search_type='websearch') # websearch operators
``SearchQuery`` terms can be combined logically to provide more flexibility::
``SearchQuery`` terms can be combined logically to provide more flexibility:
.. code-block:: pycon
>>> from django.contrib.postgres.search import SearchQuery
>>> SearchQuery('meat') & SearchQuery('cheese') # AND
@@ -117,7 +125,9 @@ sort of relevancy. PostgreSQL provides a ranking function which takes into
account how often the query terms appear in the document, how close together
the terms are in the document, and how important the part of the document is
where they occur. The better the match, the higher the value of the rank. To
order by relevancy::
order by relevancy:
.. code-block:: pycon
>>> from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
>>> vector = SearchVector('body_text')
@@ -134,7 +144,9 @@ account.
Provide an integer to the ``normalization`` parameter to control rank
normalization. This integer is a bit mask, so you can combine multiple
behaviors::
behaviors:
.. code-block:: pycon
>>> from django.db.models import Value
>>> Entry.objects.annotate(
@@ -182,7 +194,9 @@ between fragments. PostgreSQL's default is ``" ... "``.
The PostgreSQL documentation has more details on `highlighting search
results`_.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.contrib.postgres.search import SearchHeadline, SearchQuery
>>> query = SearchQuery('red tomato')
@@ -209,7 +223,9 @@ Changing the search configuration
You can specify the ``config`` attribute to a :class:`SearchVector` and
:class:`SearchQuery` to use a different search configuration. This allows using
different language parsers and dictionaries as defined by the database::
different language parsers and dictionaries as defined by the database:
.. code-block:: pycon
>>> from django.contrib.postgres.search import SearchQuery, SearchVector
>>> Entry.objects.annotate(
@@ -217,7 +233,9 @@ different language parsers and dictionaries as defined by the database::
... ).filter(search=SearchQuery('œuf', config='french'))
[<Entry: Pain perdu>]
The value of ``config`` could also be stored in another column::
The value of ``config`` could also be stored in another column:
.. code-block:: pycon
>>> from django.db.models import F
>>> Entry.objects.annotate(
@@ -231,7 +249,9 @@ Weighting queries
=================
Every field may not have the same relevance in a query, so you can set weights
of various vectors before you combine them::
of various vectors before you combine them:
.. code-block:: pycon
>>> from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
>>> vector = SearchVector('body_text', weight='A') + SearchVector('blog__tagline', weight='B')
@@ -241,7 +261,9 @@ of various vectors before you combine them::
The weight should be one of the following letters: D, C, B, A. By default,
these weights refer to the numbers ``0.1``, ``0.2``, ``0.4``, and ``1.0``,
respectively. If you wish to weight them differently, pass a list of four
floats to :class:`SearchRank` as ``weights`` in the same order above::
floats to :class:`SearchRank` as ``weights`` in the same order above:
.. code-block:: pycon
>>> rank = SearchRank(vector, query, weights=[0.2, 0.4, 0.6, 0.8])
>>> Entry.objects.annotate(rank=rank).filter(rank__gte=0.3).order_by('-rank')
@@ -277,7 +299,9 @@ The PostgreSQL documentation has details on
If this approach becomes too slow, you can add a ``SearchVectorField`` to your
model. You'll need to keep it populated with triggers, for example, as
described in the `PostgreSQL documentation`_. You can then query the field as
if it were an annotated ``SearchVector``::
if it were an annotated ``SearchVector``:
.. code-block:: pycon
>>> Entry.objects.update(search_vector=SearchVector('body_text'))
>>> Entry.objects.filter(search_vector='cheese')
@@ -307,7 +331,9 @@ operation.
Accepts a field name or expression, and a string or expression. Returns the
trigram similarity between the two arguments.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.contrib.postgres.search import TrigramSimilarity
>>> Author.objects.create(name='Katy Stevens')
@@ -326,7 +352,9 @@ Usage example::
Accepts a string or expression, and a field name or expression. Returns the
trigram word similarity between the two arguments.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.contrib.postgres.search import TrigramWordSimilarity
>>> Author.objects.create(name='Katy Stevens')
@@ -357,7 +385,9 @@ extent boundaries to match word boundaries.
Accepts a field name or expression, and a string or expression. Returns the
trigram distance between the two arguments.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.contrib.postgres.search import TrigramDistance
>>> Author.objects.create(name='Katy Stevens')
@@ -376,7 +406,9 @@ Usage example::
Accepts a string or expression, and a field name or expression. Returns the
trigram word distance between the two arguments.
Usage example::
Usage example:
.. code-block:: pycon
>>> from django.contrib.postgres.search import TrigramWordDistance
>>> Author.objects.create(name='Katy Stevens')