summaryrefslogtreecommitdiff
path: root/docs/topics/db
diff options
context:
space:
mode:
authorCarlton Gibson <carlton.gibson@noumenal.es>2023-02-09 16:48:46 +0100
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2023-02-10 21:12:06 +0100
commitb784768eef75afb32f6d2ce7166551a528bce0ec (patch)
treea375a57a50f1766538ea8a62ec49bda352d7f2b9 /docs/topics/db
parent4a89aa25c91e520c247aee428782274dcf10ffd0 (diff)
[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 534ac4829764f317cf2fbc4a18354fcc998c1425 from main.
Diffstat (limited to 'docs/topics/db')
-rw-r--r--docs/topics/db/aggregation.txt100
-rw-r--r--docs/topics/db/examples/many_to_many.txt113
-rw-r--r--docs/topics/db/examples/many_to_one.txt72
-rw-r--r--docs/topics/db/examples/one_to_one.txt64
-rw-r--r--docs/topics/db/fixtures.txt16
-rw-r--r--docs/topics/db/managers.txt4
-rw-r--r--docs/topics/db/models.txt46
-rw-r--r--docs/topics/db/multi-db.txt40
-rw-r--r--docs/topics/db/optimization.txt16
-rw-r--r--docs/topics/db/queries.txt264
-rw-r--r--docs/topics/db/search.txt20
-rw-r--r--docs/topics/db/sql.txt52
12 files changed, 602 insertions, 205 deletions
diff --git a/docs/topics/db/aggregation.txt b/docs/topics/db/aggregation.txt
index d871c548e2..d0004a2bff 100644
--- a/docs/topics/db/aggregation.txt
+++ b/docs/topics/db/aggregation.txt
@@ -44,7 +44,9 @@ Cheat sheet
===========
In a hurry? Here's how to do common aggregate queries, assuming the models
-above::
+above:
+
+.. code-block:: pycon
# Total number of books.
>>> Book.objects.count()
@@ -102,19 +104,25 @@ Generating aggregates over a ``QuerySet``
Django provides two ways to generate aggregates. The first way is to generate
summary values over an entire ``QuerySet``. For example, say you wanted to
calculate the average price of all books available for sale. Django's query
-syntax provides a means for describing the set of all books::
+syntax provides a means for describing the set of all books:
+
+.. code-block:: pycon
>>> Book.objects.all()
What we need is a way to calculate summary values over the objects that
belong to this ``QuerySet``. This is done by appending an ``aggregate()``
-clause onto the ``QuerySet``::
+clause onto the ``QuerySet``:
+
+.. code-block:: pycon
>>> from django.db.models import Avg
>>> Book.objects.all().aggregate(Avg('price'))
{'price__avg': 34.35}
-The ``all()`` is redundant in this example, so this could be simplified to::
+The ``all()`` is redundant in this example, so this could be simplified to:
+
+.. code-block:: pycon
>>> Book.objects.aggregate(Avg('price'))
{'price__avg': 34.35}
@@ -129,14 +137,18 @@ returns a dictionary of name-value pairs. The name is an identifier for the
aggregate value; the value is the computed aggregate. The name is
automatically generated from the name of the field and the aggregate function.
If you want to manually specify a name for the aggregate value, you can do so
-by providing that name when you specify the aggregate clause::
+by providing that name when you specify the aggregate clause:
+
+.. code-block:: pycon
>>> Book.objects.aggregate(average_price=Avg('price'))
{'average_price': 34.35}
If you want to generate more than one aggregate, you add another argument to
the ``aggregate()`` clause. So, if we also wanted to know the maximum and
-minimum price of all books, we would issue the query::
+minimum price of all books, we would issue the query:
+
+.. code-block:: pycon
>>> from django.db.models import Avg, Max, Min
>>> Book.objects.aggregate(Avg('price'), Max('price'), Min('price'))
@@ -159,7 +171,9 @@ specified values.
The syntax for these annotations is identical to that used for the
:meth:`~.QuerySet.aggregate` clause. Each argument to ``annotate()`` describes
an aggregate that is to be calculated. For example, to annotate books with the
-number of authors::
+number of authors:
+
+.. code-block:: pycon
# Build an annotated queryset
>>> from django.db.models import Count
@@ -178,7 +192,9 @@ number of authors::
As with ``aggregate()``, the name for the annotation is automatically derived
from the name of the aggregate function and the name of the field being
aggregated. You can override this default name by providing an alias when you
-specify the annotation::
+specify the annotation:
+
+.. code-block:: pycon
>>> q = Book.objects.annotate(num_authors=Count('authors'))
>>> q[0].num_authors
@@ -239,7 +255,9 @@ filters. Django will then handle any table joins that are required to retrieve
and aggregate the related value.
For example, to find the price range of books offered in each store,
-you could use the annotation::
+you could use the annotation:
+
+.. code-block:: pycon
>>> from django.db.models import Max, Min
>>> Store.objects.annotate(min_price=Min('books__price'), max_price=Max('books__price'))
@@ -250,13 +268,17 @@ price field of the book model to produce a minimum and maximum value.
The same rules apply to the ``aggregate()`` clause. If you wanted to
know the lowest and highest price of any book that is available for sale
-in any of the stores, you could use the aggregate::
+in any of the stores, you could use the aggregate:
+
+.. code-block:: pycon
>>> Store.objects.aggregate(min_price=Min('books__price'), max_price=Max('books__price'))
Join chains can be as deep as you require. For example, to extract the
age of the youngest author of any book available for sale, you could
-issue the query::
+issue the query:
+
+.. code-block:: pycon
>>> Store.objects.aggregate(youngest_age=Min('books__authors__age'))
@@ -270,7 +292,9 @@ of related models and double-underscores are used here too.
For example, we can ask for all publishers, annotated with their respective
total book stock counters (note how we use ``'book'`` to specify the
-``Publisher`` -> ``Book`` reverse foreign key hop)::
+``Publisher`` -> ``Book`` reverse foreign key hop):
+
+.. code-block:: pycon
>>> from django.db.models import Avg, Count, Min, Sum
>>> Publisher.objects.annotate(Count('book'))
@@ -278,7 +302,9 @@ total book stock counters (note how we use ``'book'`` to specify the
(Every ``Publisher`` in the resulting ``QuerySet`` will have an extra attribute
called ``book__count``.)
-We can also ask for the oldest book of any of those managed by every publisher::
+We can also ask for the oldest book of any of those managed by every publisher:
+
+.. code-block:: pycon
>>> Publisher.objects.aggregate(oldest_pubdate=Min('book__pubdate'))
@@ -288,7 +314,9 @@ such alias were specified, it would be the rather long ``'book__pubdate__min'``.
This doesn't apply just to foreign keys. It also works with many-to-many
relations. For example, we can ask for every author, annotated with the total
number of pages considering all the books the author has (co-)authored (note how we
-use ``'book'`` to specify the ``Author`` -> ``Book`` reverse many-to-many hop)::
+use ``'book'`` to specify the ``Author`` -> ``Book`` reverse many-to-many hop):
+
+.. code-block:: pycon
>>> Author.objects.annotate(total_pages=Sum('book__pages'))
@@ -297,7 +325,9 @@ called ``total_pages``. If no such alias were specified, it would be the rather
long ``book__pages__sum``.)
Or ask for the average rating of all the books written by author(s) we have on
-file::
+file:
+
+.. code-block:: pycon
>>> Author.objects.aggregate(average_rating=Avg('book__rating'))
@@ -317,7 +347,9 @@ constraining the objects that are considered for aggregation.
When used with an ``annotate()`` clause, a filter has the effect of
constraining the objects for which an annotation is calculated. For example,
you can generate an annotated list of all books that have a title starting
-with "Django" using the query::
+with "Django" using the query:
+
+.. code-block:: pycon
>>> from django.db.models import Avg, Count
>>> Book.objects.filter(name__startswith="Django").annotate(num_authors=Count('authors'))
@@ -325,7 +357,9 @@ with "Django" using the query::
When used with an ``aggregate()`` clause, a filter has the effect of
constraining the objects over which the aggregate is calculated.
For example, you can generate the average price of all books with a
-title that starts with "Django" using the query::
+title that starts with "Django" using the query:
+
+.. code-block:: pycon
>>> Book.objects.filter(name__startswith="Django").aggregate(Avg('price'))
@@ -339,7 +373,9 @@ used in ``filter()`` and ``exclude()`` clauses in the same way as any other
model field.
For example, to generate a list of books that have more than one author,
-you can issue the query::
+you can issue the query:
+
+.. code-block:: pycon
>>> Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__gt=1)
@@ -348,7 +384,9 @@ based upon that annotation.
If you need two annotations with two separate filters you can use the
``filter`` argument with any aggregate. For example, to generate a list of
-authors with a count of highly rated books::
+authors with a count of highly rated books:
+
+.. code-block:: pycon
>>> highly_rated = Count('book', filter=Q(book__rating__gte=7))
>>> Author.objects.annotate(num_books=Count('book'), highly_rated_books=highly_rated)
@@ -381,7 +419,9 @@ Given:
* Publisher B has two books with ratings 1 and 4.
* Publisher C has one book with rating 1.
-Here's an example with the ``Count`` aggregate::
+Here's an example with the ``Count`` aggregate:
+
+.. code-block:: pycon
>>> a, b = Publisher.objects.annotate(num_books=Count('book', distinct=True)).filter(book__rating__gt=3.0)
>>> a, a.num_books
@@ -406,7 +446,9 @@ The second query counts the number of books that have a rating exceeding 3.0
for each publisher. The filter precedes the annotation, so the filter
constrains the objects considered when calculating the annotation.
-Here's another example with the ``Avg`` aggregate::
+Here's another example with the ``Avg`` aggregate:
+
+.. code-block:: pycon
>>> a, b = Publisher.objects.annotate(avg_rating=Avg('book__rating')).filter(book__rating__gt=3.0)
>>> a, a.avg_rating
@@ -437,7 +479,9 @@ define an ``order_by()`` clause, the aggregates you provide can reference
any alias defined as part of an ``annotate()`` clause in the query.
For example, to order a ``QuerySet`` of books by the number of authors
-that have contributed to the book, you could use the following query::
+that have contributed to the book, you could use the following query:
+
+.. code-block:: pycon
>>> Book.objects.annotate(num_authors=Count('authors')).order_by('num_authors')
@@ -462,7 +506,9 @@ rating of books written by each author:
This will return one result for each author in the database, annotated with
their average book rating.
-However, the result will be slightly different if you use a ``values()`` clause::
+However, the result will be slightly different if you use a ``values()`` clause:
+
+.. code-block:: pycon
>>> Author.objects.values('name').annotate(average_rating=Avg('book__rating'))
@@ -486,7 +532,9 @@ the ``values()`` clause only constrains the fields that are generated on
output.
For example, if we reverse the order of the ``values()`` and ``annotate()``
-clause from our previous example::
+clause from our previous example:
+
+.. code-block:: pycon
>>> Author.objects.annotate(average_rating=Avg('book__rating')).values('name', 'average_rating')
@@ -563,7 +611,9 @@ any alias defined as part of an ``annotate()`` clause in the query.
For example, if you wanted to calculate the average number of authors per
book you first annotate the set of books with the author count, then
-aggregate that author count, referencing the annotation field::
+aggregate that author count, referencing the annotation field:
+
+.. code-block:: pycon
>>> from django.db.models import Avg, Count
>>> Book.objects.annotate(num_authors=Count('authors')).aggregate(Avg('num_authors'))
diff --git a/docs/topics/db/examples/many_to_many.txt b/docs/topics/db/examples/many_to_many.txt
index f53f3c131a..e47069c200 100644
--- a/docs/topics/db/examples/many_to_many.txt
+++ b/docs/topics/db/examples/many_to_many.txt
@@ -2,8 +2,6 @@
Many-to-many relationships
==========================
-.. highlight:: pycon
-
To define a many-to-many relationship, use
:class:`~django.db.models.ManyToManyField`.
@@ -36,7 +34,9 @@ objects, and a ``Publication`` has multiple ``Article`` objects:
What follows are examples of operations that can be performed using the Python
API facilities.
-Create a few ``Publications``::
+Create a few ``Publications``:
+
+.. code-block:: pycon
>>> p1 = Publication(title='The Python Journal')
>>> p1.save()
@@ -45,11 +45,15 @@ Create a few ``Publications``::
>>> p3 = Publication(title='Science Weekly')
>>> p3.save()
-Create an ``Article``::
+Create an ``Article``:
+
+.. code-block:: pycon
>>> a1 = Article(headline='Django lets you build web apps easily')
-You can't associate it with a ``Publication`` until it's been saved::
+You can't associate it with a ``Publication`` until it's been saved:
+
+.. code-block:: pycon
>>> a1.publications.add(p1)
Traceback (most recent call last):
@@ -57,26 +61,35 @@ You can't associate it with a ``Publication`` until it's been saved::
ValueError: "<Article: Django lets you build web apps easily>" needs to have a value for field "id" before this many-to-many relationship can be used.
Save it!
-::
+
+.. code-block:: pycon
>>> a1.save()
-Associate the ``Article`` with a ``Publication``::
+Associate the ``Article`` with a ``Publication``:
+
+.. code-block:: pycon
>>> a1.publications.add(p1)
-Create another ``Article``, and set it to appear in the ``Publications``::
+Create another ``Article``, and set it to appear in the ``Publications``:
+
+.. code-block:: pycon
>>> a2 = Article(headline='NASA uses Python')
>>> a2.save()
>>> a2.publications.add(p1, p2)
>>> a2.publications.add(p3)
-Adding a second time is OK, it will not duplicate the relation::
+Adding a second time is OK, it will not duplicate the relation:
+
+.. code-block:: pycon
>>> a2.publications.add(p3)
-Adding an object of the wrong type raises :exc:`TypeError`::
+Adding an object of the wrong type raises :exc:`TypeError`:
+
+.. code-block:: pycon
>>> a2.publications.add(a1)
Traceback (most recent call last):
@@ -84,18 +97,24 @@ Adding an object of the wrong type raises :exc:`TypeError`::
TypeError: 'Publication' instance expected
Create and add a ``Publication`` to an ``Article`` in one step using
-:meth:`~django.db.models.fields.related.RelatedManager.create`::
+:meth:`~django.db.models.fields.related.RelatedManager.create`:
+
+.. code-block:: pycon
>>> new_publication = a2.publications.create(title='Highlights for Children')
-``Article`` objects have access to their related ``Publication`` objects::
+``Article`` objects have access to their related ``Publication`` objects:
+
+.. code-block:: pycon
>>> a1.publications.all()
<QuerySet [<Publication: The Python Journal>]>
>>> a2.publications.all()
<QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>
-``Publication`` objects have access to their related ``Article`` objects::
+``Publication`` objects have access to their related ``Article`` objects:
+
+.. code-block:: pycon
>>> p2.article_set.all()
<QuerySet [<Article: NASA uses Python>]>
@@ -105,7 +124,9 @@ Create and add a ``Publication`` to an ``Article`` in one step using
<QuerySet [<Article: NASA uses Python>]>
Many-to-many relationships can be queried using :ref:`lookups across
-relationships <lookups-that-span-relationships>`::
+relationships <lookups-that-span-relationships>`:
+
+.. code-block:: pycon
>>> Article.objects.filter(publications__id=1)
<QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
@@ -123,7 +144,9 @@ relationships <lookups-that-span-relationships>`::
<QuerySet [<Article: NASA uses Python>]>
The :meth:`~django.db.models.query.QuerySet.count` function respects
-:meth:`~django.db.models.query.QuerySet.distinct` as well::
+:meth:`~django.db.models.query.QuerySet.distinct` as well:
+
+.. code-block:: pycon
>>> Article.objects.filter(publications__title__startswith="Science").count()
2
@@ -137,7 +160,9 @@ The :meth:`~django.db.models.query.QuerySet.count` function respects
<QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
Reverse m2m queries are supported (i.e., starting at the table that doesn't have
-a :class:`~django.db.models.ManyToManyField`)::
+a :class:`~django.db.models.ManyToManyField`):
+
+.. code-block:: pycon
>>> Publication.objects.filter(id=1)
<QuerySet [<Publication: The Python Journal>]>
@@ -162,12 +187,16 @@ a :class:`~django.db.models.ManyToManyField`)::
<QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>
Excluding a related item works as you would expect, too (although the SQL
-involved is a little complex)::
+involved is a little complex):
+
+.. code-block:: pycon
>>> Article.objects.exclude(publications=p2)
<QuerySet [<Article: Django lets you build web apps easily>]>
-If we delete a ``Publication``, its ``Articles`` won't be able to access it::
+If we delete a ``Publication``, its ``Articles`` won't be able to access it:
+
+.. code-block:: pycon
>>> p1.delete()
>>> Publication.objects.all()
@@ -176,7 +205,9 @@ If we delete a ``Publication``, its ``Articles`` won't be able to access it::
>>> a1.publications.all()
<QuerySet []>
-If we delete an ``Article``, its ``Publications`` won't be able to access it::
+If we delete an ``Article``, its ``Publications`` won't be able to access it:
+
+.. code-block:: pycon
>>> a2.delete()
>>> Article.objects.all()
@@ -184,7 +215,9 @@ If we delete an ``Article``, its ``Publications`` won't be able to access it::
>>> p2.article_set.all()
<QuerySet []>
-Adding via the 'other' end of an m2m::
+Adding via the 'other' end of an m2m:
+
+.. code-block:: pycon
>>> a4 = Article(headline='NASA finds intelligent life on Earth')
>>> a4.save()
@@ -194,7 +227,9 @@ Adding via the 'other' end of an m2m::
>>> a4.publications.all()
<QuerySet [<Publication: Science News>]>
-Adding via the other end using keywords::
+Adding via the other end using keywords:
+
+.. code-block:: pycon
>>> new_article = p2.article_set.create(headline='Oxygen-free diet works wonders')
>>> p2.article_set.all()
@@ -203,7 +238,9 @@ Adding via the other end using keywords::
>>> a5.publications.all()
<QuerySet [<Publication: Science News>]>
-Removing ``Publication`` from an ``Article``::
+Removing ``Publication`` from an ``Article``:
+
+.. code-block:: pycon
>>> a4.publications.remove(p2)
>>> p2.article_set.all()
@@ -211,7 +248,9 @@ Removing ``Publication`` from an ``Article``::
>>> a4.publications.all()
<QuerySet []>
-And from the other end::
+And from the other end:
+
+.. code-block:: pycon
>>> p2.article_set.remove(a5)
>>> p2.article_set.all()
@@ -219,7 +258,9 @@ And from the other end::
>>> a5.publications.all()
<QuerySet []>
-Relation sets can be set::
+Relation sets can be set:
+
+.. code-block:: pycon
>>> a4.publications.all()
<QuerySet [<Publication: Science News>]>
@@ -227,13 +268,17 @@ Relation sets can be set::
>>> a4.publications.all()
<QuerySet [<Publication: Science Weekly>]>
-Relation sets can be cleared::
+Relation sets can be cleared:
+
+.. code-block:: pycon
>>> p2.article_set.clear()
>>> p2.article_set.all()
<QuerySet []>
-And you can clear from the other end::
+And you can clear from the other end:
+
+.. code-block:: pycon
>>> p2.article_set.add(a4, a5)
>>> p2.article_set.all()
@@ -246,7 +291,9 @@ And you can clear from the other end::
>>> p2.article_set.all()
<QuerySet [<Article: Oxygen-free diet works wonders>]>
-Recreate the ``Article`` and ``Publication`` we have deleted::
+Recreate the ``Article`` and ``Publication`` we have deleted:
+
+.. code-block:: pycon
>>> p1 = Publication(title='The Python Journal')
>>> p1.save()
@@ -255,7 +302,9 @@ Recreate the ``Article`` and ``Publication`` we have deleted::
>>> a2.publications.add(p1, p2, p3)
Bulk delete some ``Publications`` - references to deleted publications should
-go::
+go:
+
+.. code-block:: pycon
>>> Publication.objects.filter(title__startswith='Science').delete()
>>> Publication.objects.all()
@@ -265,7 +314,9 @@ go::
>>> a2.publications.all()
<QuerySet [<Publication: The Python Journal>]>
-Bulk delete some articles - references to deleted objects should go::
+Bulk delete some articles - references to deleted objects should go:
+
+.. code-block:: pycon
>>> q = Article.objects.filter(headline__startswith='Django')
>>> print(q)
@@ -274,7 +325,9 @@ Bulk delete some articles - references to deleted objects should go::
After the :meth:`~django.db.models.query.QuerySet.delete`, the
:class:`~django.db.models.query.QuerySet` cache needs to be cleared, and the
-referenced objects should be gone::
+referenced objects should be gone:
+
+.. code-block:: pycon
>>> print(q)
<QuerySet []>
diff --git a/docs/topics/db/examples/many_to_one.txt b/docs/topics/db/examples/many_to_one.txt
index 20e489397c..f1311989ce 100644
--- a/docs/topics/db/examples/many_to_one.txt
+++ b/docs/topics/db/examples/many_to_one.txt
@@ -31,9 +31,9 @@ objects, but an ``Article`` can only have one ``Reporter`` object::
What follows are examples of operations that can be performed using the Python
API facilities.
-.. highlight:: pycon
+Create a few Reporters:
-Create a few Reporters::
+.. code-block:: pycon
>>> r = Reporter(first_name='John', last_name='Smith', email='john@example.com')
>>> r.save()
@@ -41,7 +41,9 @@ Create a few Reporters::
>>> r2 = Reporter(first_name='Paul', last_name='Jones', email='paul@example.com')
>>> r2.save()
-Create an Article::
+Create an Article:
+
+.. code-block:: pycon
>>> from datetime import date
>>> a = Article(id=None, headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
@@ -55,7 +57,9 @@ Create an Article::
Note that you must save an object before it can be assigned to a foreign key
relationship. For example, creating an ``Article`` with unsaved ``Reporter``
-raises ``ValueError``::
+raises ``ValueError``:
+
+.. code-block:: pycon
>>> r3 = Reporter(first_name='John', last_name='Smith', email='john@example.com')
>>> Article.objects.create(headline="This is a test", pub_date=date(2005, 7, 27), reporter=r3)
@@ -63,11 +67,15 @@ raises ``ValueError``::
...
ValueError: save() prohibited to prevent data loss due to unsaved related object 'reporter'.
-Article objects have access to their related Reporter objects::
+Article objects have access to their related Reporter objects:
+
+.. code-block:: pycon
>>> r = a.reporter
-Create an Article via the Reporter object::
+Create an Article via the Reporter object:
+
+.. code-block:: pycon
>>> new_article = r.article_set.create(headline="John's second story", pub_date=date(2005, 7, 29))
>>> new_article
@@ -77,7 +85,9 @@ Create an Article via the Reporter object::
>>> new_article.reporter.id
1
-Create a new article::
+Create a new article:
+
+.. code-block:: pycon
>>> new_article2 = Article.objects.create(headline="Paul's story", pub_date=date(2006, 1, 17), reporter=r)
>>> new_article2.reporter
@@ -87,7 +97,9 @@ Create a new article::
>>> r.article_set.all()
<QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
-Add the same article to a different article set - check that it moves::
+Add the same article to a different article set - check that it moves:
+
+.. code-block:: pycon
>>> r2.article_set.add(new_article2)
>>> new_article2.reporter.id
@@ -95,7 +107,9 @@ Add the same article to a different article set - check that it moves::
>>> new_article2.reporter
<Reporter: Paul Jones>
-Adding an object of the wrong type raises TypeError::
+Adding an object of the wrong type raises TypeError:
+
+.. code-block:: pycon
>>> r.article_set.add(r2)
Traceback (most recent call last):
@@ -118,7 +132,9 @@ Note that in the last example the article has moved from John to Paul.
Related managers support field lookups as well.
The API automatically follows relationships as far as you need.
Use double underscores to separate relationships.
-This works as many levels deep as you want. There's no limit. For example::
+This works as many levels deep as you want. There's no limit. For example:
+
+.. code-block:: pycon
>>> r.article_set.filter(headline__startswith='This')
<QuerySet [<Article: This is a test>]>
@@ -127,19 +143,25 @@ This works as many levels deep as you want. There's no limit. For example::
>>> Article.objects.filter(reporter__first_name='John')
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
-Exact match is implied here::
+Exact match is implied here:
+
+.. code-block:: pycon
>>> Article.objects.filter(reporter__first_name='John')
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
Query twice over the related field. This translates to an AND condition in the
-WHERE clause::
+WHERE clause:
+
+.. code-block:: pycon
>>> Article.objects.filter(reporter__first_name='John', reporter__last_name='Smith')
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
For the related lookup you can supply a primary key value or pass the related
-object explicitly::
+object explicitly:
+
+.. code-block:: pycon
>>> Article.objects.filter(reporter__pk=1)
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
@@ -153,12 +175,16 @@ object explicitly::
>>> Article.objects.filter(reporter__in=[r,r2]).distinct()
<QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
-You can also use a queryset instead of a literal list of instances::
+You can also use a queryset instead of a literal list of instances:
+
+.. code-block:: pycon
>>> Article.objects.filter(reporter__in=Reporter.objects.filter(first_name='John')).distinct()
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
-Querying in the opposite direction::
+Querying in the opposite direction:
+
+.. code-block:: pycon
>>> Reporter.objects.filter(article__pk=1)
<QuerySet [<Reporter: John Smith>]>
@@ -172,14 +198,18 @@ Querying in the opposite direction::
>>> Reporter.objects.filter(article__headline__startswith='This').distinct()
<QuerySet [<Reporter: John Smith>]>
-Counting in the opposite direction works in conjunction with ``distinct()``::
+Counting in the opposite direction works in conjunction with ``distinct()``:
+
+.. code-block:: pycon
>>> Reporter.objects.filter(article__headline__startswith='This').count()
3
>>> Reporter.objects.filter(article__headline__startswith='This').distinct().count()
1
-Queries can go round in circles::
+Queries can go round in circles:
+
+.. code-block:: pycon
>>> Reporter.objects.filter(article__reporter__first_name__startswith='John')
<QuerySet [<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]>
@@ -190,7 +220,9 @@ Queries can go round in circles::
If you delete a reporter, their articles will be deleted (assuming that the
ForeignKey was defined with :attr:`django.db.models.ForeignKey.on_delete` set to
-``CASCADE``, which is the default)::
+``CASCADE``, which is the default):
+
+.. code-block:: pycon
>>> Article.objects.all()
<QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
@@ -202,7 +234,9 @@ ForeignKey was defined with :attr:`django.db.models.ForeignKey.on_delete` set to
>>> Reporter.objects.order_by('first_name')
<QuerySet [<Reporter: John Smith>]>
-You can delete using a JOIN in the query::
+You can delete using a JOIN in the query:
+
+.. code-block:: pycon
>>> Reporter.objects.filter(article__headline__startswith='This').delete()
>>> Reporter.objects.all()
diff --git a/docs/topics/db/examples/one_to_one.txt b/docs/topics/db/examples/one_to_one.txt
index 92f5e9ce40..1a21993a06 100644
--- a/docs/topics/db/examples/one_to_one.txt
+++ b/docs/topics/db/examples/one_to_one.txt
@@ -38,31 +38,39 @@ In this example, a ``Place`` optionally can be a ``Restaurant``::
What follows are examples of operations that can be performed using the Python
API facilities.
-.. highlight:: pycon
+Create a couple of Places:
-Create a couple of Places::
+.. code-block:: pycon
>>> p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
>>> p1.save()
>>> p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
>>> p2.save()
-Create a Restaurant. Pass the "parent" object as this object's primary key::
+Create a Restaurant. Pass the "parent" object as this object's primary key:
+
+.. code-block:: pycon
>>> r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False)
>>> r.save()
-A Restaurant can access its place::
+A Restaurant can access its place:
+
+.. code-block:: pycon
>>> r.place
<Place: Demon Dogs the place>
-A Place can access its restaurant, if available::
+A Place can access its restaurant, if available:
+
+.. code-block:: pycon
>>> p1.restaurant
<Restaurant: Demon Dogs the restaurant>
-p2 doesn't have an associated restaurant::
+p2 doesn't have an associated restaurant:
+
+.. code-block:: pycon
>>> from django.core.exceptions import ObjectDoesNotExist
>>> try:
@@ -71,13 +79,17 @@ p2 doesn't have an associated restaurant::
>>> print("There is no restaurant here.")
There is no restaurant here.
-You can also use ``hasattr`` to avoid the need for exception catching::
+You can also use ``hasattr`` to avoid the need for exception catching:
+
+.. code-block:: pycon
>>> hasattr(p2, 'restaurant')
False
Set the place using assignment notation. Because place is the primary key on
-Restaurant, the save will create a new restaurant::
+Restaurant, the save will create a new restaurant:
+
+.. code-block:: pycon
>>> r.place = p2
>>> r.save()
@@ -86,7 +98,9 @@ Restaurant, the save will create a new restaurant::
>>> r.place
<Place: Ace Hardware the place>
-Set the place back again, using assignment in the reverse direction::
+Set the place back again, using assignment in the reverse direction:
+
+.. code-block:: pycon
>>> p1.restaurant = r
>>> p1.restaurant
@@ -94,7 +108,9 @@ Set the place back again, using assignment in the reverse direction::
Note that you must save an object before it can be assigned to a one-to-one
relationship. For example, creating a ``Restaurant`` with unsaved ``Place``
-raises ``ValueError``::
+raises ``ValueError``:
+
+.. code-block:: pycon
>>> p3 = Place(name='Demon Dogs', address='944 W. Fullerton')
>>> Restaurant.objects.create(place=p3, serves_hot_dogs=True, serves_pizza=False)
@@ -104,18 +120,24 @@ raises ``ValueError``::
Restaurant.objects.all() returns the Restaurants, not the Places. Note that
there are two restaurants - Ace Hardware the Restaurant was created in the call
-to r.place = p2::
+to r.place = p2:
+
+.. code-block:: pycon
>>> Restaurant.objects.all()
<QuerySet [<Restaurant: Demon Dogs the restaurant>, <Restaurant: Ace Hardware the restaurant>]>
Place.objects.all() returns all Places, regardless of whether they have
-Restaurants::
+Restaurants:
+
+.. code-block:: pycon
>>> Place.objects.order_by('name')
<QuerySet [<Place: Ace Hardware the place>, <Place: Demon Dogs the place>]>
-You can query the models using :ref:`lookups across relationships <lookups-that-span-relationships>`::
+You can query the models using :ref:`lookups across relationships <lookups-that-span-relationships>`:
+
+.. code-block:: pycon
>>> Restaurant.objects.get(place=p1)
<Restaurant: Demon Dogs the restaurant>
@@ -126,7 +148,9 @@ You can query the models using :ref:`lookups across relationships <lookups-that-
>>> Restaurant.objects.exclude(place__address__contains="Ashland")
<QuerySet [<Restaurant: Demon Dogs the restaurant>]>
-This also works in reverse::
+This also works in reverse:
+
+.. code-block:: pycon
>>> Place.objects.get(pk=1)
<Place: Demon Dogs the place>
@@ -140,20 +164,26 @@ This also works in reverse::
If you delete a place, its restaurant will be deleted (assuming that the
``OneToOneField`` was defined with
:attr:`~django.db.models.ForeignKey.on_delete` set to ``CASCADE``, which is the
-default)::
+default):
+
+.. code-block:: pycon
>>> p2.delete()
(2, {'one_to_one.Restaurant': 1, 'one_to_one.Place': 1})
>>> Restaurant.objects.all()
<QuerySet [<Restaurant: Demon Dogs the restaurant>]>
-Add a Waiter to the Restaurant::
+Add a Waiter to the Restaurant:
+
+.. code-block:: pycon
>>> w = r.waiter_set.create(name='Joe')
>>> w
<Waiter: Joe the waiter at Demon Dogs the restaurant>
-Query the waiters::
+Query the waiters:
+
+.. code-block:: pycon
>>> Waiter.objects.filter(restaurant__place=p1)
<QuerySet [<Waiter: Joe the waiter at Demon Dogs the restaurant>]>
diff --git a/docs/topics/db/fixtures.txt b/docs/topics/db/fixtures.txt
index b1425adc13..629c6c9a85 100644
--- a/docs/topics/db/fixtures.txt
+++ b/docs/topics/db/fixtures.txt
@@ -43,7 +43,9 @@ Django will load any and all fixtures it finds in these locations that match
the provided fixture names.
If the named fixture has a file extension, only fixtures of that type
-will be loaded. For example::
+will be loaded. For example:
+
+.. code-block:: shell
django-admin loaddata mydata.json
@@ -52,7 +54,9 @@ must correspond to the registered name of a
:ref:`serializer <serialization-formats>` (e.g., ``json`` or ``xml``).
If you omit the extensions, Django will search all available fixture types
-for a matching fixture. For example::
+for a matching fixture. For example:
+
+.. code-block:: shell
django-admin loaddata mydata
@@ -61,7 +65,9 @@ directory contained ``mydata.json``, that fixture would be loaded
as a JSON fixture.
The fixtures that are named can include directory components. These
-directories will be included in the search path. For example::
+directories will be included in the search path. For example:
+
+.. code-block:: shell
django-admin loaddata foo/bar/mydata.json
@@ -124,7 +130,9 @@ Compressed fixtures
===================
Fixtures may be compressed in ``zip``, ``gz``, ``bz2``, ``lzma``, or ``xz``
-format. For example::
+format. For example:
+
+.. code-block:: shell
django-admin loaddata mydata.json
diff --git a/docs/topics/db/managers.txt b/docs/topics/db/managers.txt
index 0a94ce7f52..f576b01ea2 100644
--- a/docs/topics/db/managers.txt
+++ b/docs/topics/db/managers.txt
@@ -425,7 +425,9 @@ Implementation concerns
Whatever features you add to your custom ``Manager``, it must be
possible to make a shallow copy of a ``Manager`` instance; i.e., the
-following code must work::
+following code must work:
+
+.. code-block:: pycon
>>> import copy
>>> manager = MyManager()
diff --git a/docs/topics/db/models.txt b/docs/topics/db/models.txt
index 2f8a5551ff..43a34bbe28 100644
--- a/docs/topics/db/models.txt
+++ b/docs/topics/db/models.txt
@@ -189,7 +189,7 @@ ones:
name = models.CharField(max_length=60)
shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)
- ::
+ .. code-block:: pycon
>>> p = Person(name="Fred Flintstone", shirt_size="L")
>>> p.save()
@@ -503,7 +503,9 @@ There are a few restrictions on the intermediate model:
Now that you have set up your :class:`~django.db.models.ManyToManyField` to use
your intermediary model (``Membership``, in this case), you're ready to start
creating some many-to-many relationships. You do this by creating instances of
-the intermediate model::
+the intermediate model:
+
+.. code-block:: pycon
>>> ringo = Person.objects.create(name="Ringo Starr")
>>> paul = Person.objects.create(name="Paul McCartney")
@@ -526,7 +528,9 @@ You can also use :meth:`~django.db.models.fields.related.RelatedManager.add`,
:meth:`~django.db.models.fields.related.RelatedManager.create`, or
:meth:`~django.db.models.fields.related.RelatedManager.set` to create
relationships, as long as you specify ``through_defaults`` for any required
-fields::
+fields:
+
+.. code-block:: pycon
>>> beatles.members.add(john, through_defaults={'date_joined': date(1960, 8, 1)})
>>> beatles.members.create(name="George Harrison", through_defaults={'date_joined': date(1960, 8, 1)})
@@ -537,7 +541,9 @@ You may prefer to create instances of the intermediate model directly.
If the custom through table defined by the intermediate model does not enforce
uniqueness on the ``(model1, model2)`` pair, allowing multiple values, the
:meth:`~django.db.models.fields.related.RelatedManager.remove` call will
-remove all intermediate model instances::
+remove all intermediate model instances:
+
+.. code-block:: pycon
>>> Membership.objects.create(person=ringo, group=beatles,
... date_joined=date(1968, 9, 4),
@@ -550,7 +556,9 @@ remove all intermediate model instances::
<QuerySet [<Person: Paul McCartney>]>
The :meth:`~django.db.models.fields.related.RelatedManager.clear`
-method can be used to remove all many-to-many relationships for an instance::
+method can be used to remove all many-to-many relationships for an instance:
+
+.. code-block:: pycon
>>> # Beatles have broken up
>>> beatles.members.clear()
@@ -560,13 +568,17 @@ method can be used to remove all many-to-many relationships for an instance::
Once you have established the many-to-many relationships, you can issue
queries. Just as with normal many-to-many relationships, you can query using
-the attributes of the many-to-many-related model::
+the attributes of the many-to-many-related model:
+
+.. code-block:: pycon
# Find all the groups with a member whose name starts with 'Paul'
>>> Group.objects.filter(members__name__startswith='Paul')
<QuerySet [<Group: The Beatles>]>
-As you are using an intermediate model, you can also query on its attributes::
+As you are using an intermediate model, you can also query on its attributes:
+
+.. code-block:: pycon
# Find all the members of the Beatles that joined after 1 Jan 1961
>>> Person.objects.filter(
@@ -575,7 +587,9 @@ As you are using an intermediate model, you can also query on its attributes::
<QuerySet [<Person: Ringo Starr]>
If you need to access a membership's information you may do so by directly
-querying the ``Membership`` model::
+querying the ``Membership`` model:
+
+.. code-block:: pycon
>>> ringos_membership = Membership.objects.get(group=beatles, person=ringo)
>>> ringos_membership.date_joined
@@ -585,7 +599,9 @@ querying the ``Membership`` model::
Another way to access the same information is by querying the
:ref:`many-to-many reverse relationship<m2m-reverse-relationships>` from a
-``Person`` object::
+``Person`` object:
+
+.. code-block:: pycon
>>> ringos_membership = ringo.membership_set.get(group=beatles)
>>> ringos_membership.date_joined
@@ -1120,14 +1136,18 @@ For example::
All of the fields of ``Place`` will also be available in ``Restaurant``,
although the data will reside in a different database table. So these are both
-possible::
+possible:
+
+.. code-block:: pycon
>>> Place.objects.filter(name="Bob's Cafe")
>>> Restaurant.objects.filter(name="Bob's Cafe")
If you have a ``Place`` that is also a ``Restaurant``, you can get from the
``Place`` object to the ``Restaurant`` object by using the lowercase version of
-the model name::
+the model name:
+
+.. code-block:: pycon
>>> p = Place.objects.get(id=12)
# If p is a Restaurant object, this will give the child class:
@@ -1264,7 +1284,9 @@ For example, suppose you want to add a method to the ``Person`` model. You can d
The ``MyPerson`` class operates on the same database table as its parent
``Person`` class. In particular, any new instances of ``Person`` will also be
-accessible through ``MyPerson``, and vice-versa::
+accessible through ``MyPerson``, and vice-versa:
+
+.. code-block:: pycon
>>> p = Person.objects.create(first_name="foobar")
>>> MyPerson.objects.get(first_name="foobar")
diff --git a/docs/topics/db/multi-db.txt b/docs/topics/db/multi-db.txt
index 6a5314603c..697addb539 100644
--- a/docs/topics/db/multi-db.txt
+++ b/docs/topics/db/multi-db.txt
@@ -85,7 +85,9 @@ The :djadmin:`migrate` management command operates on one database at a
time. By default, it operates on the ``default`` database, but by
providing the :option:`--database <migrate --database>` option, you can tell it
to synchronize a different database. So, to synchronize all models onto
-all databases in the first example above, you would need to call::
+all databases in the first example above, you would need to call:
+
+.. code-block:: shell
$ ./manage.py migrate
$ ./manage.py migrate --database=users
@@ -97,7 +99,9 @@ constraining the availability of particular models.
If, as in the second example above, you've left the ``default`` database empty,
you must provide a database name each time you run :djadmin:`migrate`. Omitting
-the database name would raise an error. For the second example::
+the database name would raise an error. For the second example:
+
+.. code-block:: shell
$ ./manage.py migrate --database=users
$ ./manage.py migrate --database=customers
@@ -405,7 +409,9 @@ catch-all nature of the PrimaryReplicaRouter implementation would mean
that all models would be available on all databases.
With this setup installed, and all databases migrated as per
-:ref:`synchronizing_multiple_databases`, lets run some Django code::
+:ref:`synchronizing_multiple_databases`, lets run some Django code:
+
+.. code-block:: pycon
>>> # This retrieval will be performed on the 'auth_db' database
>>> fred = User.objects.get(username='fred')
@@ -453,7 +459,9 @@ You can select the database for a ``QuerySet`` at any point in the
``QuerySet`` that uses the specified database.
``using()`` takes a single argument: the alias of the database on
-which you want to run the query. For example::
+which you want to run the query. For example:
+
+.. code-block:: pycon
>>> # This will run on the 'default' database.
>>> Author.objects.all()
@@ -471,7 +479,9 @@ Use the ``using`` keyword to ``Model.save()`` to specify to which
database the data should be saved.
For example, to save an object to the ``legacy_users`` database, you'd
-use this::
+use this:
+
+.. code-block:: pycon
>>> my_object.save(using='legacy_users')
@@ -486,7 +496,9 @@ use ``save(using=...)`` as a way to migrate the instance to a new
database. However, if you don't take appropriate steps, this could
have some unexpected consequences.
-Consider the following example::
+Consider the following example:
+
+.. code-block:: pycon
>>> p = Person(name='Fred')
>>> p.save(using='first') # (statement 1)
@@ -510,7 +522,9 @@ will be overridden when ``p`` is saved.
You can avoid this in two ways. First, you can clear the primary key
of the instance. If an object has no primary key, Django will treat it
as a new object, avoiding any loss of data on the ``second``
-database::
+database:
+
+.. code-block:: pycon
>>> p = Person(name='Fred')
>>> p.save(using='first')
@@ -518,7 +532,9 @@ database::
>>> p.save(using='second') # Write a completely new object.
The second option is to use the ``force_insert`` option to ``save()``
-to ensure that Django does an SQL ``INSERT``::
+to ensure that Django does an SQL ``INSERT``:
+
+.. code-block:: pycon
>>> p = Person(name='Fred')
>>> p.save(using='first')
@@ -534,7 +550,9 @@ Selecting a database to delete from
By default, a call to delete an existing object will be executed on
the same database that was used to retrieve the object in the first
-place::
+place:
+
+.. code-block:: pycon
>>> u = User.objects.using('legacy_users').get(username='fred')
>>> u.delete() # will delete from the `legacy_users` database
@@ -544,7 +562,9 @@ To specify the database from which a model will be deleted, pass a
argument works just like the ``using`` keyword argument to ``save()``.
For example, if you're migrating a user from the ``legacy_users``
-database to the ``new_users`` database, you might use these commands::
+database to the ``new_users`` database, you might use these commands:
+
+.. code-block:: pycon
>>> user_obj.save(using='new_users')
>>> user_obj.delete(using='legacy_users')
diff --git a/docs/topics/db/optimization.txt b/docs/topics/db/optimization.txt
index ca04c8fd55..54d79f1b84 100644
--- a/docs/topics/db/optimization.txt
+++ b/docs/topics/db/optimization.txt
@@ -82,13 +82,17 @@ Understand cached attributes
As well as caching of the whole ``QuerySet``, there is caching of the result of
attributes on ORM objects. In general, attributes that are not callable will be
cached. For example, assuming the :ref:`example blog models
-<queryset-model-example>`::
+<queryset-model-example>`:
+
+.. code-block:: pycon
>>> entry = Entry.objects.get(id=1)
>>> entry.blog # Blog object is retrieved at this point
>>> entry.blog # cached version, no DB access
-But in general, callable attributes cause DB lookups every time::
+But in general, callable attributes cause DB lookups every time:
+
+.. code-block:: pycon
>>> entry = Entry.objects.get(id=1)
>>> entry.authors.all() # query performed
@@ -164,18 +168,24 @@ First, the query will be quicker because of the underlying database index.
Also, the query could run much slower if multiple objects match the lookup;
having a unique constraint on the column guarantees this will never happen.
-So using the :ref:`example blog models <queryset-model-example>`::
+So using the :ref:`example blog models <queryset-model-example>`:
+
+.. code-block:: pycon
>>> entry = Entry.objects.get(id=10)
will be quicker than:
+.. code-block:: pycon
+
>>> entry = Entry.objects.get(headline="News Item Title")
because ``id`` is indexed by the database and is guaranteed to be unique.
Doing the following is potentially quite slow:
+.. code-block:: pycon
+
>>> entry = Entry.objects.get(headline__startswith="News")
First of all, ``headline`` is not indexed, which will make the underlying
diff --git a/docs/topics/db/queries.txt b/docs/topics/db/queries.txt
index 977e287c53..43bdd79966 100644
--- a/docs/topics/db/queries.txt
+++ b/docs/topics/db/queries.txt
@@ -59,7 +59,9 @@ class represents a particular record in the database table.
To create an object, instantiate it using keyword arguments to the model class,
then call :meth:`~django.db.models.Model.save` to save it to the database.
-Assuming models live in a file ``mysite/blog/models.py``, here's an example::
+Assuming models live in a file ``mysite/blog/models.py``, here's an example:
+
+.. code-block:: pycon
>>> from blog.models import Blog
>>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
@@ -86,7 +88,9 @@ To save changes to an object that's already in the database, use
:meth:`~django.db.models.Model.save`.
Given a ``Blog`` instance ``b5`` that has already been saved to the database,
-this example changes its name and updates its record in the database::
+this example changes its name and updates its record in the database:
+
+.. code-block:: pycon
>>> b5.name = 'New name'
>>> b5.save()
@@ -101,7 +105,9 @@ Updating a :class:`~django.db.models.ForeignKey` field works exactly the same
way as saving a normal field -- assign an object of the right type to the field
in question. This example updates the ``blog`` attribute of an ``Entry``
instance ``entry``, assuming appropriate instances of ``Entry`` and ``Blog``
-are already saved to the database (so we can retrieve them below)::
+are already saved to the database (so we can retrieve them below):
+
+.. code-block:: pycon
>>> from blog.models import Blog, Entry
>>> entry = Entry.objects.get(pk=1)
@@ -113,7 +119,9 @@ Updating a :class:`~django.db.models.ManyToManyField` works a little
differently -- use the
:meth:`~django.db.models.fields.related.RelatedManager.add` method on the field
to add a record to the relation. This example adds the ``Author`` instance
-``joe`` to the ``entry`` object::
+``joe`` to the ``entry`` object:
+
+.. code-block:: pycon
>>> from blog.models import Author
>>> joe = Author.objects.create(name="Joe")
@@ -121,7 +129,9 @@ to add a record to the relation. This example adds the ``Author`` instance
To add multiple records to a :class:`~django.db.models.ManyToManyField` in one
go, include multiple arguments in the call to
-:meth:`~django.db.models.fields.related.RelatedManager.add`, like this::
+:meth:`~django.db.models.fields.related.RelatedManager.add`, like this:
+
+.. code-block:: pycon
>>> john = Author.objects.create(name="John")
>>> paul = Author.objects.create(name="Paul")
@@ -150,7 +160,9 @@ You get a :class:`~django.db.models.query.QuerySet` by using your model's
:class:`~django.db.models.Manager`. Each model has at least one
:class:`~django.db.models.Manager`, and it's called
:attr:`~django.db.models.Model.objects` by default. Access it directly via the
-model class, like so::
+model class, like so:
+
+.. code-block:: pycon
>>> Blog.objects
<django.db.models.manager.Manager object at ...>
@@ -176,7 +188,9 @@ Retrieving all objects
The simplest way to retrieve objects from a table is to get all of them. To do
this, use the :meth:`~django.db.models.query.QuerySet.all` method on a
-:class:`~django.db.models.Manager`::
+:class:`~django.db.models.Manager`:
+
+.. code-block:: pycon
>>> all_entries = Entry.objects.all()
@@ -223,7 +237,9 @@ Chaining filters
The result of refining a :class:`~django.db.models.query.QuerySet` is itself a
:class:`~django.db.models.query.QuerySet`, so it's possible to chain
-refinements together. For example::
+refinements together. For example:
+
+.. code-block:: pycon
>>> Entry.objects.filter(
... headline__startswith='What'
@@ -250,7 +266,9 @@ the previous :class:`~django.db.models.query.QuerySet`. Each refinement creates
a separate and distinct :class:`~django.db.models.query.QuerySet` that can be
stored, used and reused.
-Example::
+Example:
+
+.. code-block:: pycon
>>> q1 = Entry.objects.filter(headline__startswith="What")
>>> q2 = q1.exclude(pub_date__gte=datetime.date.today())
@@ -274,7 +292,9 @@ refinement process.
:class:`~django.db.models.query.QuerySet` doesn't involve any database
activity. You can stack filters together all day long, and Django won't
actually run the query until the :class:`~django.db.models.query.QuerySet` is
-*evaluated*. Take a look at this example::
+*evaluated*. Take a look at this example:
+
+.. code-block:: pycon
>>> q = Entry.objects.filter(headline__startswith="What")
>>> q = q.filter(pub_date__lte=datetime.date.today())
@@ -301,7 +321,9 @@ the query - in this case, it will be a
If you know there is only one object that matches your query, you can use the
:meth:`~django.db.models.query.QuerySet.get` method on a
-:class:`~django.db.models.Manager` which returns the object directly::
+:class:`~django.db.models.Manager` which returns the object directly:
+
+.. code-block:: pycon
>>> one_entry = Entry.objects.get(pk=1)
@@ -345,11 +367,15 @@ Use a subset of Python's array-slicing syntax to limit your
:class:`~django.db.models.query.QuerySet` to a certain number of results. This
is the equivalent of SQL's ``LIMIT`` and ``OFFSET`` clauses.
-For example, this returns the first 5 objects (``LIMIT 5``)::
+For example, this returns the first 5 objects (``LIMIT 5``):
+
+.. code-block:: pycon
>>> Entry.objects.all()[:5]
-This returns the sixth through tenth objects (``OFFSET 5 LIMIT 5``)::
+This returns the sixth through tenth objects (``OFFSET 5 LIMIT 5``):
+
+.. code-block:: pycon
>>> Entry.objects.all()[5:10]
@@ -359,7 +385,9 @@ Generally, slicing a :class:`~django.db.models.query.QuerySet` returns a new
:class:`~django.db.models.query.QuerySet` -- it doesn't evaluate the query. An
exception is if you use the "step" parameter of Python slice syntax. For
example, this would actually execute the query in order to return a list of
-every *second* object of the first 10::
+every *second* object of the first 10:
+
+.. code-block:: pycon
>>> Entry.objects.all()[:10:2]
@@ -369,11 +397,15 @@ ambiguous nature of how that might work.
To retrieve a *single* object rather than a list
(e.g. ``SELECT foo FROM bar LIMIT 1``), use an index instead of a slice. For
example, this returns the first ``Entry`` in the database, after ordering
-entries alphabetically by headline::
+entries alphabetically by headline:
+
+.. code-block:: pycon
>>> Entry.objects.order_by('headline')[0]
-This is roughly equivalent to::
+This is roughly equivalent to:
+
+.. code-block:: pycon
>>> Entry.objects.order_by('headline')[0:1].get()
@@ -393,7 +425,9 @@ methods :meth:`~django.db.models.query.QuerySet.filter`,
:meth:`~django.db.models.query.QuerySet.get`.
Basic lookups keyword arguments take the form ``field__lookuptype=value``.
-(That's a double-underscore). For example::
+(That's a double-underscore). For example:
+
+.. code-block:: pycon
>>> Entry.objects.filter(pub_date__lte='2006-01-01')
@@ -426,7 +460,9 @@ a taste of what's available, here's some of the more common lookups you'll
probably use:
:lookup:`exact`
- An "exact" match. For example::
+ An "exact" match. For example:
+
+ .. code-block:: pycon
>>> Entry.objects.get(headline__exact="Cat bites dog")
@@ -440,7 +476,9 @@ probably use:
doesn't contain a double underscore -- the lookup type is assumed to be
``exact``.
- For example, the following two statements are equivalent::
+ For example, the following two statements are equivalent:
+
+ .. code-block:: pycon
>>> Blog.objects.get(id__exact=14) # Explicit form
>>> Blog.objects.get(id=14) # __exact is implied
@@ -448,7 +486,9 @@ probably use:
This is for convenience, because ``exact`` lookups are the common case.
:lookup:`iexact`
- A case-insensitive match. So, the query::
+ A case-insensitive match. So, the query:
+
+ .. code-block:: pycon
>>> Blog.objects.get(name__iexact="beatles blog")
@@ -491,7 +531,9 @@ across models, separated by double underscores, until you get to the field you
want.
This example retrieves all ``Entry`` objects with a ``Blog`` whose ``name``
-is ``'Beatles Blog'``::
+is ``'Beatles Blog'``:
+
+.. code-block:: pycon
>>> Entry.objects.filter(blog__name='Beatles Blog')
@@ -502,7 +544,9 @@ It works backwards, too. While it :attr:`can be customized
relationship in a lookup using the lowercase name of the model.
This example retrieves all ``Blog`` objects which have at least one ``Entry``
-whose ``headline`` contains ``'Lennon'``::
+whose ``headline`` contains ``'Lennon'``:
+
+.. code-block:: pycon
>>> Blog.objects.filter(entry__headline__contains='Lennon')
@@ -649,7 +693,9 @@ of two different fields on the same model instance.
For example, to find a list of all blog entries that have had more comments
than pingbacks, we construct an ``F()`` object to reference the pingback count,
-and use that ``F()`` object in the query::
+and use that ``F()`` object in the query:
+
+.. code-block:: pycon
>>> from django.db.models import F
>>> Entry.objects.filter(number_of_comments__gt=F('number_of_pingbacks'))
@@ -657,13 +703,17 @@ and use that ``F()`` object in the query::
Django supports the use of addition, subtraction, multiplication,
division, modulo, and power arithmetic with ``F()`` objects, both with constants
and with other ``F()`` objects. To find all the blog entries with more than
-*twice* as many comments as pingbacks, we modify the query::
+*twice* as many comments as pingbacks, we modify the query:
+
+.. code-block:: pycon
>>> Entry.objects.filter(number_of_comments__gt=F('number_of_pingbacks') * 2)
To find all the entries where the rating of the entry is less than the
sum of the pingback count and comment count, we would issue the
-query::
+query:
+
+.. code-block:: pycon
>>> Entry.objects.filter(rating__lt=F('number_of_comments') + F('number_of_pingbacks'))
@@ -671,19 +721,25 @@ You can also use the double underscore notation to span relationships in
an ``F()`` object. An ``F()`` object with a double underscore will introduce
any joins needed to access the related object. For example, to retrieve all
the entries where the author's name is the same as the blog name, we could
-issue the query::
+issue the query:
+
+.. code-block:: pycon
>>> Entry.objects.filter(authors__name=F('blog__name'))
For date and date/time fields, you can add or subtract a
:class:`~datetime.timedelta` object. The following would return all entries
-that were modified more than 3 days after they were published::
+that were modified more than 3 days after they were published:
+
+.. code-block:: pycon
>>> from datetime import timedelta
>>> Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3))
The ``F()`` objects support bitwise operations by ``.bitand()``, ``.bitor()``,
-``.bitxor()``, ``.bitrightshift()``, and ``.bitleftshift()``. For example::
+``.bitxor()``, ``.bitrightshift()``, and ``.bitleftshift()``. For example:
+
+.. code-block:: pycon
>>> F('somefield').bitand(16)
@@ -699,18 +755,24 @@ Expressions can reference transforms
Django supports using transforms in expressions.
For example, to find all ``Entry`` objects published in the same year as they
-were last modified::
+were last modified:
+
+.. code-block:: pycon
>>> from django.db.models import F
>>> Entry.objects.filter(pub_date__year=F('mod_date__year'))
-To find the earliest year an entry was published, we can issue the query::
+To find the earliest year an entry was published, we can issue the query:
+
+.. code-block:: pycon
>>> from django.db.models import Min
>>> Entry.objects.aggregate(first_published_year=Min('pub_date__year'))
This example finds the value of the highest rated entry and the total number
-of comments on all entries for each year::
+of comments on all entries for each year:
+
+.. code-block:: pycon
>>> from django.db.models import OuterRef, Subquery, Sum
>>> Entry.objects.values('pub_date__year').annotate(
@@ -729,14 +791,18 @@ For convenience, Django provides a ``pk`` lookup shortcut, which stands for
"primary key".
In the example ``Blog`` model, the primary key is the ``id`` field, so these
-three statements are equivalent::
+three statements are equivalent:
+
+.. code-block:: pycon
>>> Blog.objects.get(id__exact=14) # Explicit form
>>> Blog.objects.get(id=14) # __exact is implied
>>> Blog.objects.get(pk=14) # pk implies id__exact
The use of ``pk`` isn't limited to ``__exact`` queries -- any query term
-can be combined with ``pk`` to perform a query on the primary key of a model::
+can be combined with ``pk`` to perform a query on the primary key of a model:
+
+.. code-block:: pycon
# Get blogs entries with id 1, 4 and 7
>>> Blog.objects.filter(pk__in=[1,4,7])
@@ -745,7 +811,9 @@ can be combined with ``pk`` to perform a query on the primary key of a model::
>>> Blog.objects.filter(pk__gt=14)
``pk`` lookups also work across joins. For example, these three statements are
-equivalent::
+equivalent:
+
+.. code-block:: pycon
>>> Entry.objects.filter(blog__id__exact=3) # Explicit form
>>> Entry.objects.filter(blog__id=3) # __exact is implied
@@ -763,7 +831,9 @@ underscore signifies a single-character wildcard.)
This means things should work intuitively, so the abstraction doesn't leak.
For example, to retrieve all the entries that contain a percent sign, use the
-percent sign as any other character::
+percent sign as any other character:
+
+.. code-block:: pycon
>>> Entry.objects.filter(headline__contains='%')
@@ -798,7 +868,9 @@ results.
Keep this caching behavior in mind, because it may bite you if you don't use
your :class:`~django.db.models.query.QuerySet`\s correctly. For example, the
following will create two :class:`~django.db.models.query.QuerySet`\s, evaluate
-them, and throw them away::
+them, and throw them away:
+
+.. code-block:: pycon
>>> print([e.headline for e in Entry.objects.all()])
>>> print([e.pub_date for e in Entry.objects.all()])
@@ -809,7 +881,9 @@ the same database records, because an ``Entry`` may have been added or deleted
in the split second between the two requests.
To avoid this problem, save the :class:`~django.db.models.query.QuerySet` and
-reuse it::
+reuse it:
+
+.. code-block:: pycon
>>> queryset = Entry.objects.all()
>>> print([p.headline for p in queryset]) # Evaluate the query set.
@@ -825,14 +899,18 @@ returned by the subsequent query are not cached. Specifically, this means that
index will not populate the cache.
For example, repeatedly getting a certain index in a queryset object will query
-the database each time::
+the database each time:
+
+.. code-block:: pycon
>>> queryset = Entry.objects.all()
>>> print(queryset[5]) # Queries the database
>>> print(queryset[5]) # Queries the database again
However, if the entire queryset has already been evaluated, the cache will be
-checked instead::
+checked instead:
+
+.. code-block:: pycon
>>> queryset = Entry.objects.all()
>>> [entry for entry in queryset] # Queries the database
@@ -840,7 +918,9 @@ checked instead::
>>> print(queryset[5]) # Uses cache
Here are some examples of other actions that will result in the entire queryset
-being evaluated and therefore populate the cache::
+being evaluated and therefore populate the cache:
+
+.. code-block:: pycon
>>> [entry for entry in queryset]
>>> bool(queryset)
@@ -983,7 +1063,9 @@ is inside a :py:class:`list` or :py:class:`dict`, it will always be interpreted
as JSON ``null``.
When querying, ``None`` value will always be interpreted as JSON ``null``. To
-query for SQL ``NULL``, use :lookup:`isnull`::
+query for SQL ``NULL``, use :lookup:`isnull`:
+
+.. code-block:: pycon
>>> Dog.objects.create(name='Max', data=None) # SQL NULL.
<Dog: Max>
@@ -1023,7 +1105,9 @@ Unless you are sure you wish to work with SQL ``NULL`` values, consider setting
Key, index, and path transforms
-------------------------------
-To query based on a given dictionary key, use that key as the lookup name::
+To query based on a given dictionary key, use that key as the lookup name:
+
+.. code-block:: pycon
>>> Dog.objects.create(name='Rufus', data={
... 'breed': 'labrador',
@@ -1040,13 +1124,17 @@ To query based on a given dictionary key, use that key as the lookup name::
>>> Dog.objects.filter(data__breed='collie')
<QuerySet [<Dog: Meg>]>
-Multiple keys can be chained together to form a path lookup::
+Multiple keys can be chained together to form a path lookup:
+
+.. code-block:: pycon
>>> Dog.objects.filter(data__owner__name='Bob')
<QuerySet [<Dog: Rufus>]>
If the key is an integer, it will be interpreted as an index transform in an
-array::
+array:
+
+.. code-block:: pycon
>>> Dog.objects.filter(data__owner__other_pets__0__name='Fishy')
<QuerySet [<Dog: Rufus>]>
@@ -1054,7 +1142,9 @@ array::
If the key you wish to query by clashes with the name of another lookup, use
the :lookup:`contains <jsonfield.contains>` lookup instead.
-To query for missing keys, use the ``isnull`` lookup::
+To query for missing keys, use the ``isnull`` lookup:
+
+.. code-block:: pycon
>>> Dog.objects.create(name='Shep', data={'breed': 'collie'})
<Dog: Shep>
@@ -1083,7 +1173,9 @@ To query for missing keys, use the ``isnull`` lookup::
:class:`~django.db.models.JSONField`. You can use the double underscore
notation in ``lookup`` to chain dictionary key and index transforms.
- For example::
+ For example:
+
+ .. code-block:: pycon
>>> from django.db.models.fields.json import KT
>>> Dog.objects.create(name="Shep", data={
@@ -1150,7 +1242,9 @@ Containment and key lookups
The :lookup:`contains` lookup is overridden on ``JSONField``. The returned
objects are those where the given ``dict`` of key-value pairs are all
-contained in the top-level of the field. For example::
+contained in the top-level of the field. For example:
+
+.. code-block:: pycon
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})
<Dog: Rufus>
@@ -1174,7 +1268,9 @@ contained in the top-level of the field. For example::
This is the inverse of the :lookup:`contains <jsonfield.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. For example::
+subset of those in the value passed. For example:
+
+.. code-block:: pycon
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})
<Dog: Rufus>
@@ -1197,7 +1293,9 @@ subset of those in the value passed. For example::
~~~~~~~~~~~
Returns objects where the given key is in the top-level of the data. For
-example::
+example:
+
+.. code-block:: pycon
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
<Dog: Rufus>
@@ -1212,7 +1310,9 @@ example::
~~~~~~~~~~~~
Returns objects where all of the given keys are in the top-level of the data.
-For example::
+For example:
+
+.. code-block:: pycon
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
<Dog: Rufus>
@@ -1227,7 +1327,9 @@ For example::
~~~~~~~~~~~~~~~~
Returns objects where any of the given keys are in the top-level of the data.
-For example::
+For example:
+
+.. code-block:: pycon
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
<Dog: Rufus>
@@ -1330,14 +1432,18 @@ To compare two model instances, use the standard Python comparison operator,
the double equals sign: ``==``. Behind the scenes, that compares the primary
key values of two models.
-Using the ``Entry`` example above, the following two statements are equivalent::
+Using the ``Entry`` example above, the following two statements are equivalent:
+
+.. code-block:: pycon
>>> some_entry == other_entry
>>> some_entry.id == other_entry.id
If a model's primary key isn't called ``id``, no problem. Comparisons will
always use the primary key, whatever it's called. For example, if a model's
-primary key field is called ``name``, these two statements are equivalent::
+primary key field is called ``name``, these two statements are equivalent:
+
+.. code-block:: pycon
>>> some_obj == other_obj
>>> some_obj.name == other_obj.name
@@ -1350,7 +1456,9 @@ Deleting objects
The delete method, conveniently, is named
:meth:`~django.db.models.Model.delete`. This method immediately deletes the
object and returns the number of objects deleted and a dictionary with
-the number of deletions per object type. Example::
+the number of deletions per object type. Example:
+
+.. code-block:: pycon
>>> e.delete()
(1, {'blog.Entry': 1})
@@ -1361,7 +1469,9 @@ You can also delete objects in bulk. Every
members of that :class:`~django.db.models.query.QuerySet`.
For example, this deletes all ``Entry`` objects with a ``pub_date`` year of
-2005::
+2005:
+
+.. code-block:: pycon
>>> Entry.objects.filter(pub_date__year=2005).delete()
(5, {'webapp.Entry': 5})
@@ -1470,7 +1580,9 @@ a :class:`~django.db.models.query.QuerySet`. You can do this with the
You can only set non-relation fields and :class:`~django.db.models.ForeignKey`
fields using this method. To update a non-relation field, provide the new value
as a constant. To update :class:`~django.db.models.ForeignKey` fields, set the
-new value to be the new model instance you want to point to. For example::
+new value to be the new model instance you want to point to. For example:
+
+.. code-block:: pycon
>>> b = Blog.objects.get(pk=1)
@@ -1483,7 +1595,9 @@ some rows already have the new value). The only restriction on the
:class:`~django.db.models.query.QuerySet` being updated is that it can only
access one database table: the model's main table. You can filter based on
related fields, but you can only update columns in the model's main
-table. Example::
+table. Example:
+
+.. code-block:: pycon
>>> b = Blog.objects.get(pk=1)
@@ -1507,14 +1621,18 @@ them and call :meth:`~django.db.models.Model.save`::
Calls to update can also use :class:`F expressions <django.db.models.F>` to
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::
+example, to increment the pingback count for every entry in the blog:
+
+.. code-block:: pycon
>>> 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
reference fields local to the model being updated. If you attempt to introduce
-a join with an ``F()`` object, a ``FieldError`` will be raised::
+a join with an ``F()`` object, a ``FieldError`` will be raised:
+
+.. code-block:: pycon
# This will raise a FieldError
>>> Entry.objects.update(headline=F('blog__name'))
@@ -1555,14 +1673,18 @@ Forward
If a model has a :class:`~django.db.models.ForeignKey`, instances of that model
will have access to the related (foreign) object via an attribute of the model.
-Example::
+Example:
+
+.. code-block:: pycon
>>> e = Entry.objects.get(id=2)
>>> e.blog # Returns the related Blog object.
You can get and set via a foreign-key attribute. As you may expect, changes to
the foreign key aren't saved to the database until you call
-:meth:`~django.db.models.Model.save`. Example::
+:meth:`~django.db.models.Model.save`. Example:
+
+.. code-block:: pycon
>>> e = Entry.objects.get(id=2)
>>> e.blog = some_blog
@@ -1570,7 +1692,9 @@ the foreign key aren't saved to the database until you call
If a :class:`~django.db.models.ForeignKey` field has ``null=True`` set (i.e.,
it allows ``NULL`` values), you can assign ``None`` to remove the relation.
-Example::
+Example:
+
+.. code-block:: pycon
>>> e = Entry.objects.get(id=2)
>>> e.blog = None
@@ -1578,7 +1702,9 @@ Example::
Forward access to one-to-many relationships is cached the first time the
related object is accessed. Subsequent accesses to the foreign key on the same
-object instance are cached. Example::
+object instance are cached. Example:
+
+.. code-block:: pycon
>>> e = Entry.objects.get(id=2)
>>> print(e.blog) # Hits the database to retrieve the associated Blog.
@@ -1586,7 +1712,9 @@ object instance are cached. Example::
Note that the :meth:`~django.db.models.query.QuerySet.select_related`
:class:`~django.db.models.query.QuerySet` method recursively prepopulates the
-cache of all one-to-many relationships ahead of time. Example::
+cache of all one-to-many relationships ahead of time. Example:
+
+.. code-block:: pycon
>>> e = Entry.objects.select_related().get(id=2)
>>> print(e.blog) # Doesn't hit the database; uses cached version.
@@ -1605,7 +1733,9 @@ source model name, lowercased. This :class:`~django.db.models.Manager` returns
``QuerySets``, which can be filtered and manipulated as described in the
"Retrieving objects" section above.
-Example::
+Example:
+
+.. code-block:: pycon
>>> b = Blog.objects.get(id=1)
>>> b.entry_set.all() # Returns all Entry objects related to Blog.
@@ -1618,7 +1748,9 @@ You can override the ``FOO_set`` name by setting the
:attr:`~django.db.models.ForeignKey.related_name` parameter in the
:class:`~django.db.models.ForeignKey` definition. For example, if the ``Entry``
model was altered to ``blog = ForeignKey(Blog, on_delete=models.CASCADE,
-related_name='entries')``, the above example code would look like this::
+related_name='entries')``, the above example code would look like this:
+
+.. code-block:: pycon
>>> b = Blog.objects.get(id=1)
>>> b.entries.all() # Returns all Entry objects related to Blog.
diff --git a/docs/topics/db/search.txt b/docs/topics/db/search.txt
index 1c4ccca81e..f3c7d24a2f 100644
--- a/docs/topics/db/search.txt
+++ b/docs/topics/db/search.txt
@@ -17,7 +17,9 @@ Standard textual queries
------------------------
Text-based fields have a selection of matching operations. For example, you may
-wish to allow lookup up an author like so::
+wish to allow lookup up an author like so:
+
+.. code-block:: pycon
>>> Author.objects.filter(name__contains='Terry')
[<Author: Terry Gilliam>, <Author: Terry Jones>]
@@ -47,7 +49,9 @@ demonstrate the kind of functionality databases may have.
In the above example, we determined that a case insensitive lookup would be
more useful. When dealing with non-English names, a further improvement is to
-use :lookup:`unaccented comparison <unaccent>`::
+use :lookup:`unaccented comparison <unaccent>`:
+
+.. code-block:: pycon
>>> Author.objects.filter(name__unaccent__icontains='Helen')
[<Author: Helen Mirren>, <Author: Helena Bonham Carter>, <Author: Hélène Joy>]
@@ -58,7 +62,9 @@ will pick up ``Helena`` or ``Hélène``, but not the reverse. Another option
would be to use a :lookup:`trigram_similar` comparison, which compares
sequences of letters.
-For example::
+For example:
+
+.. code-block:: pycon
>>> Author.objects.filter(name__unaccent__lower__trigram_similar='Hélène')
[<Author: Helen Mirren>, <Author: Hélène Joy>]
@@ -110,12 +116,16 @@ as categorization.
The :mod:`django.contrib.postgres` module provides some helpers to make these
queries. For example, a query might select all the blog entries which mention
-"cheese"::
+"cheese":
+
+.. code-block:: pycon
>>> Entry.objects.filter(body_text__search='cheese')
[<Entry: Cheese on Toast recipes>, <Entry: Pizza recipes>]
-You can also filter on a combination of fields and on related models::
+You can also filter on a combination of fields and on related models:
+
+.. code-block:: pycon
>>> Entry.objects.annotate(
... search=SearchVector('blog__tagline', 'body_text'),
diff --git a/docs/topics/db/sql.txt b/docs/topics/db/sql.txt
index 93f7724774..6a76d5b0c8 100644
--- a/docs/topics/db/sql.txt
+++ b/docs/topics/db/sql.txt
@@ -56,7 +56,9 @@ This is best illustrated with an example. Suppose you have the following model::
last_name = models.CharField(...)
birth_date = models.DateField(...)
-You could then execute custom SQL like so::
+You could then execute custom SQL like so:
+
+.. code-block:: pycon
>>> for p in Person.objects.raw('SELECT * FROM myapp_person'):
... print(p)
@@ -104,7 +106,9 @@ Mapping query fields to model fields
``raw()`` automatically maps fields in the query to fields on the model.
The order of fields in your query doesn't matter. In other words, both
-of the following queries work identically::
+of the following queries work identically:
+
+.. code-block:: pycon
>>> Person.objects.raw('SELECT id, first_name, last_name, birth_date FROM myapp_person')
...
@@ -113,7 +117,9 @@ of the following queries work identically::
Matching is done by name. This means that you can use SQL's ``AS`` clauses to
map fields in the query to model fields. So if you had some other table that
-had ``Person`` data in it, you could easily map it into ``Person`` instances::
+had ``Person`` data in it, you could easily map it into ``Person`` instances:
+
+.. code-block:: pycon
>>> Person.objects.raw('''SELECT first AS first_name,
... last AS last_name,
@@ -126,7 +132,9 @@ As long as the names match, the model instances will be created correctly.
Alternatively, you can map fields in the query to model fields using the
``translations`` argument to ``raw()``. This is a dictionary mapping names of
fields in the query to names of fields on the model. For example, the above
-query could also be written::
+query could also be written:
+
+.. code-block:: pycon
>>> name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}
>>> Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)
@@ -135,26 +143,34 @@ Index lookups
-------------
``raw()`` supports indexing, so if you need only the first result you can
-write::
+write:
+
+.. code-block:: pycon
>>> first_person = Person.objects.raw('SELECT * FROM myapp_person')[0]
However, the indexing and slicing are not performed at the database level. If
you have a large number of ``Person`` objects in your database, it is more
-efficient to limit the query at the SQL level::
+efficient to limit the query at the SQL level:
+
+.. code-block:: pycon
>>> first_person = Person.objects.raw('SELECT * FROM myapp_person LIMIT 1')[0]
Deferring model fields
----------------------
-Fields may also be left out::
+Fields may also be left out:
+
+.. code-block:: pycon
>>> people = Person.objects.raw('SELECT id, first_name FROM myapp_person')
The ``Person`` objects returned by this query will be deferred model instances
(see :meth:`~django.db.models.query.QuerySet.defer()`). This means that the
-fields that are omitted from the query will be loaded on demand. For example::
+fields that are omitted from the query will be loaded on demand. For example:
+
+.. code-block:: pycon
>>> for p in Person.objects.raw('SELECT id, first_name FROM myapp_person'):
... print(p.first_name, # This will be retrieved by the original query
@@ -179,7 +195,9 @@ Adding annotations
You can also execute queries containing fields that aren't defined on the
model. For example, we could use `PostgreSQL's age() function`__ to get a list
-of people with their ages calculated by the database::
+of people with their ages calculated by the database:
+
+.. code-block:: pycon
>>> people = Person.objects.raw('SELECT *, age(birth_date) AS age FROM myapp_person')
>>> for p in people:
@@ -197,7 +215,9 @@ Passing parameters into ``raw()``
---------------------------------
If you need to perform parameterized queries, you can use the ``params``
-argument to ``raw()``::
+argument to ``raw()``:
+
+.. code-block:: pycon
>>> lname = 'Doe'
>>> Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname])
@@ -218,13 +238,17 @@ replaced with parameters from the ``params`` argument.
**Do not use string formatting on raw queries or quote placeholders in your
SQL strings!**
- It's tempting to write the above query as::
+ It's tempting to write the above query as:
+
+ .. code-block:: pycon
>>> query = 'SELECT * FROM myapp_person WHERE last_name = %s' % lname
>>> Person.objects.raw(query)
You might also think you should write your query like this (with quotes
- around ``%s``)::
+ around ``%s``):
+
+ .. code-block:: pycon
>>> query = "SELECT * FROM myapp_person WHERE last_name = '%s'"
@@ -313,7 +337,9 @@ immutable and accessible by field names or indices, which might be useful::
nt_result = namedtuple('Result', [col[0] for col in desc])
return [nt_result(*row) for row in cursor.fetchall()]
-Here is an example of the difference between the three::
+Here is an example of the difference between the three:
+
+.. code-block:: pycon
>>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2")
>>> cursor.fetchall()