From 76fc58ab9609934e9cea1a6e0bce92adf79478d4 Mon Sep 17 00:00:00 2001 From: Joseph Victor Zammit Date: Sun, 13 Nov 2022 11:42:26 +0100 Subject: [PATCH] Apply "code-block" directive to unmarked code snippets under "ref/models". Manual process. Re-run blacken-docs. --- docs/ref/models/conditional-expressions.txt | 17 +- docs/ref/models/constraints.txt | 20 +- docs/ref/models/database-functions.txt | 28 +- docs/ref/models/expressions.txt | 203 ++++--- docs/ref/models/fields.txt | 147 +++-- docs/ref/models/indexes.txt | 18 +- docs/ref/models/instances.txt | 144 +++-- docs/ref/models/lookups.txt | 18 +- docs/ref/models/options.txt | 94 ++- docs/ref/models/querysets.txt | 617 +++++++++++++------- 10 files changed, 874 insertions(+), 432 deletions(-) diff --git a/docs/ref/models/conditional-expressions.txt b/docs/ref/models/conditional-expressions.txt index a2be2d77d4fa9..598c58f7712e9 100644 --- a/docs/ref/models/conditional-expressions.txt +++ b/docs/ref/models/conditional-expressions.txt @@ -13,18 +13,21 @@ also be combined and nested like other :doc:`expressions `. The conditional expression classes ================================== -We'll be using the following model in the subsequent examples:: +We'll be using the following model in the subsequent examples: + +.. code-block:: python from django.db import models + class Client(models.Model): - REGULAR = 'R' - GOLD = 'G' - PLATINUM = 'P' + REGULAR = "R" + GOLD = "G" + PLATINUM = "P" ACCOUNT_TYPE_CHOICES = [ - (REGULAR, 'Regular'), - (GOLD, 'Gold'), - (PLATINUM, 'Platinum'), + (REGULAR, "Regular"), + (GOLD, "Gold"), + (PLATINUM, "Platinum"), ] name = models.CharField(max_length=50) registered_on = models.DateField() diff --git a/docs/ref/models/constraints.txt b/docs/ref/models/constraints.txt index c8a3eac013f5d..66c993e4ec520 100644 --- a/docs/ref/models/constraints.txt +++ b/docs/ref/models/constraints.txt @@ -110,7 +110,7 @@ This method must be implemented by a subclass. A :class:`Q` object or boolean :class:`~django.db.models.Expression` that specifies the check you want the constraint to enforce. -For example, ``CheckConstraint(check=Q(age__gte=18), name='age_gte_18')`` +For example, ``CheckConstraint(check=Q(age__gte=18), name="age_gte_18")`` ensures the age field is never less than 18. .. admonition:: Oracle @@ -118,9 +118,11 @@ ensures the age field is never less than 18. Checks with nullable fields on Oracle must include a condition allowing for ``NULL`` values in order for :meth:`validate() ` to behave the same as check constraints validation. For example, if ``age`` - is a nullable field:: + is a nullable field: + + .. code-block:: python - CheckConstraint(check=Q(age__gte=18) | Q(age__isnull=True), name='age_gte_18') + CheckConstraint(check=Q(age__gte=18) | Q(age__isnull=True), name="age_gte_18") .. versionchanged:: 4.1 @@ -141,9 +143,11 @@ ensures the age field is never less than 18. Positional argument ``*expressions`` allows creating functional unique constraints on expressions and database functions. -For example:: +For example: + +.. code-block:: python - UniqueConstraint(Lower('name').desc(), 'category', name='unique_lower_name_category') + UniqueConstraint(Lower("name").desc(), "category", name="unique_lower_name_category") creates a unique constraint on the lowercased value of the ``name`` field in descending order and the ``category`` field in the default ascending order. @@ -171,9 +175,11 @@ date. A :class:`Q` object that specifies the condition you want the constraint to enforce. -For example:: +For example: + +.. code-block:: python - UniqueConstraint(fields=['user'], condition=Q(status='DRAFT'), name='unique_draft_user') + UniqueConstraint(fields=["user"], condition=Q(status="DRAFT"), name="unique_draft_user") ensures that each user only has one draft. diff --git a/docs/ref/models/database-functions.txt b/docs/ref/models/database-functions.txt index 3608c2c1e5b3b..6eec666807c7b 100644 --- a/docs/ref/models/database-functions.txt +++ b/docs/ref/models/database-functions.txt @@ -125,21 +125,25 @@ Accepts a list of at least two field names or expressions and returns the greatest value. Each argument must be of a similar type, so mixing text and numbers will result in a database error. -Usage example:: +Usage example: - class Blog(models.Model): - body = models.TextField() - modified = models.DateTimeField(auto_now=True) +.. code-block:: pycon - class Comment(models.Model): - body = models.TextField() - modified = models.DateTimeField(auto_now=True) - blog = models.ForeignKey(Blog, on_delete=models.CASCADE) + >>> class Blog(models.Model): + ... body = models.TextField() + ... modified = models.DateTimeField(auto_now=True) + ... + + >>> class Comment(models.Model): + ... body = models.TextField() + ... modified = models.DateTimeField(auto_now=True) + ... blog = models.ForeignKey(Blog, on_delete=models.CASCADE) + ... >>> from django.db.models.functions import Greatest - >>> blog = Blog.objects.create(body='Greatest is the best.') - >>> comment = Comment.objects.create(body='No, Least is better.', blog=blog) - >>> comments = Comment.objects.annotate(last_updated=Greatest('modified', 'blog__modified')) + >>> blog = Blog.objects.create(body="Greatest is the best.") + >>> comment = Comment.objects.create(body="No, Least is better.", blog=blog) + >>> comments = Comment.objects.annotate(last_updated=Greatest("modified", "blog__modified")) >>> annotated_comment = comments.get() ``annotated_comment.last_updated`` will be the most recent of ``blog.modified`` @@ -301,7 +305,7 @@ returned when this timezone is active will be the same as above except for: Each ``lookup_name`` above has a corresponding ``Extract`` subclass (listed below) that should typically be used instead of the more verbose equivalent, -e.g. use ``ExtractYear(...)`` rather than ``Extract(..., lookup_name='year')``. +e.g. use ``ExtractYear(...)`` rather than ``Extract(..., lookup_name="year")``. Usage example: diff --git a/docs/ref/models/expressions.txt b/docs/ref/models/expressions.txt index 6662622422ddf..446022d5885f9 100644 --- a/docs/ref/models/expressions.txt +++ b/docs/ref/models/expressions.txt @@ -109,24 +109,28 @@ pull them out of the database into Python memory. Instead, Django uses the ``F()`` object to generate an SQL expression that describes the required operation at the database level. -Let's try this with an example. Normally, one might do something like this:: +Let's try this with an example. Normally, one might do something like this: + +.. code-block:: python # Tintin filed a news story! - reporter = Reporters.objects.get(name='Tintin') + reporter = Reporters.objects.get(name="Tintin") reporter.stories_filed += 1 reporter.save() Here, we have pulled the value of ``reporter.stories_filed`` from the database into memory and manipulated it using familiar Python operators, and then saved -the object back to the database. But instead we could also have done:: +the object back to the database. But instead we could also have done: + +.. code-block:: python from django.db.models import F - reporter = Reporters.objects.get(name='Tintin') - reporter.stories_filed = F('stories_filed') + 1 + reporter = Reporters.objects.get(name="Tintin") + reporter.stories_filed = F("stories_filed") + 1 reporter.save() -Although ``reporter.stories_filed = F('stories_filed') + 1`` looks like a +Although ``reporter.stories_filed = F("stories_filed") + 1`` looks like a normal Python assignment of value to an instance attribute, in fact it's an SQL construct describing an operation on the database. @@ -140,7 +144,9 @@ know about it - it is dealt with entirely by the database. All Python does, through Django's ``F()`` class, is create the SQL syntax to refer to the field and describe the operation. -To access the new value saved this way, the object must be reloaded:: +To access the new value saved this way, the object must be reloaded: + +.. code-block:: python reporter = Reporters.objects.get(pk=reporter.pk) # Or, more succinctly: @@ -149,17 +155,21 @@ To access the new value saved this way, the object must be reloaded:: As well as being used in operations on single instances as above, ``F()`` can be used on ``QuerySets`` of object instances, with ``update()``. This reduces the two queries we were using above - the ``get()`` and the -:meth:`~Model.save()` - to just one:: +:meth:`~Model.save()` - to just one: - reporter = Reporters.objects.filter(name='Tintin') - reporter.update(stories_filed=F('stories_filed') + 1) +.. code-block:: python + + reporter = Reporters.objects.filter(name="Tintin") + reporter.update(stories_filed=F("stories_filed") + 1) We can also use :meth:`~django.db.models.query.QuerySet.update()` to increment the field value on multiple objects - which could be very much faster than pulling them all into Python from the database, looping over them, incrementing -the field value of each one, and saving each one back to the database:: +the field value of each one, and saving each one back to the database: + +.. code-block:: python - Reporter.objects.update(stories_filed=F('stories_filed') + 1) + Reporter.objects.update(stories_filed=F("stories_filed") + 1) ``F()`` therefore can offer performance advantages by: @@ -188,13 +198,15 @@ than based on its value when the instance was retrieved. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``F()`` objects assigned to model fields persist after saving the model -instance and will be applied on each :meth:`~Model.save()`. For example:: +instance and will be applied on each :meth:`~Model.save()`. For example: - reporter = Reporters.objects.get(name='Tintin') - reporter.stories_filed = F('stories_filed') + 1 +.. code-block:: python + + reporter = Reporters.objects.get(name="Tintin") + reporter.stories_filed = F("stories_filed") + 1 reporter.save() - reporter.name = 'Tintin Jr.' + reporter.name = "Tintin Jr." reporter.save() ``stories_filed`` will be updated twice in this case. If it's initially ``1``, @@ -218,26 +230,33 @@ Using ``F()`` with annotations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``F()`` can be used to create dynamic fields on your models by combining -different fields with arithmetic:: +different fields with arithmetic: + +.. code-block:: python - company = Company.objects.annotate( - chairs_needed=F('num_employees') - F('num_chairs')) + company = Company.objects.annotate(chairs_needed=F("num_employees") - F("num_chairs")) If the fields that you're combining are of different types you'll need to tell Django what kind of field will be returned. Since ``F()`` does not directly support ``output_field`` you will need to wrap the expression with -:class:`ExpressionWrapper`:: +:class:`ExpressionWrapper`: + +.. code-block:: python from django.db.models import DateTimeField, ExpressionWrapper, F Ticket.objects.annotate( expires=ExpressionWrapper( - F('active_at') + F('duration'), output_field=DateTimeField())) + F("active_at") + F("duration"), output_field=DateTimeField() + ) + ) When referencing relational fields such as ``ForeignKey``, ``F()`` returns the -primary key value rather than a model instance:: +primary key value rather than a model instance: + +.. code-block:: pycon - >> car = Company.objects.annotate(built_by=F('manufacturer'))[0] + >> car = Company.objects.annotate(built_by=F("manufacturer"))[0] >> car.manufacturer >> car.built_by @@ -253,10 +272,13 @@ Use ``F()`` and the ``nulls_first`` or ``nulls_last`` keyword argument to a field's null values. By default, the ordering depends on your database. For example, to sort companies that haven't been contacted (``last_contacted`` -is null) after companies that have been contacted:: +is null) after companies that have been contacted: + +.. code-block:: python from django.db.models import F - Company.objects.order_by(F('last_contacted').desc(nulls_last=True)) + + Company.objects.order_by(F("last_contacted").desc(nulls_last=True)) Using ``F()`` with logical operations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -265,11 +287,13 @@ Using ``F()`` with logical operations ``F()`` expressions that output ``BooleanField`` can be logically negated with the inversion operator ``~F()``. For example, to swap the activation status of -companies:: +companies: + +.. code-block:: python from django.db.models import F - Company.objects.update(is_active=~F('is_active')) + Company.objects.update(is_active=~F("is_active")) .. _func-expressions: @@ -278,18 +302,23 @@ companies:: ``Func()`` expressions are the base type of all expressions that involve database functions like ``COALESCE`` and ``LOWER``, or aggregates like ``SUM``. -They can be used directly:: +They can be used directly: + +.. code-block:: python from django.db.models import F, Func - queryset.annotate(field_lower=Func(F('field'), function='LOWER')) + queryset.annotate(field_lower=Func(F("field"), function="LOWER")) -or they can be used to build a library of database functions:: +or they can be used to build a library of database functions: + +.. code-block:: python class Lower(Func): - function = 'LOWER' + function = "LOWER" + - queryset.annotate(field_lower=Lower('field')) + queryset.annotate(field_lower=Lower("field")) But both cases will result in a queryset where each model is annotated with an extra attribute ``field_lower`` produced, roughly, from the following SQL: @@ -318,7 +347,7 @@ The ``Func`` API is as follows: generated for this function. Defaults to ``'%(function)s(%(expressions)s)'``. - If you're constructing SQL like ``strftime('%W', 'date')`` and need a + If you're constructing SQL like ``strftime("%W", "date")`` and need a literal ``%`` character in the query, quadruple it (``%%%%``) in the ``template`` attribute because the string is interpolated twice: once during the template interpolation in ``as_sql()`` and once in the SQL @@ -397,12 +426,15 @@ is required. All of the :ref:`aggregate functions `, like ``Sum()`` and ``Count()``, inherit from ``Aggregate()``. Since ``Aggregate``\s are expressions and wrap expressions, you can represent -some complex computations:: +some complex computations: + +.. code-block:: python from django.db.models import Count Company.objects.annotate( - managers_required=(Count('num_employees') / 4) + Count('num_managers')) + managers_required=(Count("num_employees") / 4) + Count("num_managers") + ) The ``Aggregate`` API is as follows: @@ -475,22 +507,21 @@ Creating your own Aggregate Functions You can create your own aggregate functions, too. At a minimum, you need to define ``function``, but you can also completely customize the SQL that is -generated. Here's a brief example:: +generated. Here's a brief example: + +.. code-block:: python from django.db.models import Aggregate + class Sum(Aggregate): # Supports SUM(ALL field). - function = 'SUM' - template = '%(function)s(%(all_values)s%(expressions)s)' + function = "SUM" + template = "%(function)s(%(all_values)s%(expressions)s)" allow_distinct = False def __init__(self, expression, all_values=False, **extra): - super().__init__( - expression, - all_values='ALL ' if all_values else '', - **extra - ) + super().__init__(expression, all_values="ALL " if all_values else "", **extra) ``Value()`` expressions ----------------------- @@ -504,11 +535,11 @@ boolean, or string within an expression, you can wrap that value within a ``Value()``. You will rarely need to use ``Value()`` directly. When you write the expression -``F('field') + 1``, Django implicitly wraps the ``1`` in a ``Value()``, +``F("field") + 1``, Django implicitly wraps the ``1`` in a ``Value()``, allowing simple values to be used in more complex expressions. You will need to use ``Value()`` when you want to pass a string to an expression. Most expressions interpret a string argument as the name of a field, like -``Lower('name')``. +``Lower("name")``. The ``value`` argument describes the value to be included in the expression, such as ``1``, ``True``, or ``None``. Django knows how to convert these Python @@ -711,10 +742,10 @@ length is greater than the total length of all combined comments: The initial ``filter(...)`` limits the subquery to the relevant parameters. ``order_by()`` removes the default :attr:`~django.db.models.Options.ordering` -(if any) on the ``Comment`` model. ``values('post')`` aggregates comments by +(if any) on the ``Comment`` model. ``values("post")`` aggregates comments by ``Post``. Finally, ``annotate(...)`` performs the aggregation. The order in which these queryset methods are applied is important. In this case, since the -subquery must be limited to a single column, ``values('total')`` is required. +subquery must be limited to a single column, ``values("total")`` is required. This is the only way to perform an aggregation within a ``Subquery``, as using :meth:`~.QuerySet.aggregate` attempts to evaluate the queryset (and if @@ -1047,9 +1078,11 @@ calling the appropriate methods on the wrapped expression. .. method:: get_source_expressions() - Returns an ordered list of inner expressions. For example:: + Returns an ordered list of inner expressions. For example: + + .. code-block:: pycon - >>> Sum(F('foo')).get_source_expressions() + >>> Sum(F("foo")).get_source_expressions() [F('foo')] .. method:: set_source_expressions(expressions) @@ -1068,6 +1101,8 @@ calling the appropriate methods on the wrapped expression. Example:: + .. code-block:: python + def relabeled_clone(self, change_map): clone = copy.copy(self) clone.expression = self.expression.relabeled_clone(change_map) @@ -1147,22 +1182,25 @@ The ``COALESCE`` SQL function is defined as taking a list of columns or values. It will return the first column or value that isn't ``NULL``. We'll start by defining the template to be used for SQL generation and -an ``__init__()`` method to set some attributes:: +an ``__init__()`` method to set some attributes: + +.. code-block:: python import copy from django.db.models import Expression + class Coalesce(Expression): - template = 'COALESCE( %(expressions)s )' + template = "COALESCE( %(expressions)s )" def __init__(self, expressions, output_field): - super().__init__(output_field=output_field) - if len(expressions) < 2: - raise ValueError('expressions must have at least 2 elements') - for expression in expressions: - if not hasattr(expression, 'resolve_expression'): - raise TypeError('%r is not an Expression' % expression) - self.expressions = expressions + super().__init__(output_field=output_field) + if len(expressions) < 2: + raise ValueError("expressions must have at least 2 elements") + for expression in expressions: + if not hasattr(expression, "resolve_expression"): + raise TypeError("%r is not an Expression" % expression) + self.expressions = expressions We do some basic validation on the parameters, including requiring at least 2 columns or values, and ensuring they are expressions. We are requiring @@ -1171,16 +1209,24 @@ the eventual result to. Now we implement the preprocessing and validation. Since we do not have any of our own validation at this point, we delegate to the nested -expressions:: +expressions: + +.. code-block:: python - def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): + def resolve_expression( + self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False + ): c = self.copy() c.is_summary = summarize for pos, expression in enumerate(self.expressions): - c.expressions[pos] = expression.resolve_expression(query, allow_joins, reuse, summarize, for_save) + c.expressions[pos] = expression.resolve_expression( + query, allow_joins, reuse, summarize, for_save + ) return c -Next, we write the method responsible for generating the SQL:: +Next, we write the method responsible for generating the SQL: + +.. code-block:: python def as_sql(self, compiler, connection, template=None): sql_expressions, sql_params = [], [] @@ -1189,15 +1235,16 @@ Next, we write the method responsible for generating the SQL:: sql_expressions.append(sql) sql_params.extend(params) template = template or self.template - data = {'expressions': ','.join(sql_expressions)} + data = {"expressions": ",".join(sql_expressions)} return template % data, sql_params + def as_oracle(self, compiler, connection): """ Example of vendor specific handling (Oracle in this case). Let's make the function name lowercase. """ - return self.as_sql(compiler, connection, template='coalesce( %(expressions)s )') + return self.as_sql(compiler, connection, template="coalesce( %(expressions)s )") ``as_sql()`` methods can support custom keyword arguments, allowing ``as_vendorname()`` methods to override data used to generate the SQL string. @@ -1217,11 +1264,14 @@ backend. The ``as_oracle()`` function will be called instead of ``as_sql()`` if the Oracle backend is in use. Finally, we implement the rest of the methods that allow our query expression -to play nice with other query expressions:: +to play nice with other query expressions: + +.. code-block:: python def get_source_expressions(self): return self.expressions + def set_source_expressions(self, expressions): self.expressions = expressions @@ -1255,12 +1305,15 @@ than passed as query parameters (where the database driver would escape them), they must not contain untrusted user input. For example, if ``substring`` is user-provided, this function is vulnerable to -SQL injection:: +SQL injection: + +.. code-block:: python from django.db.models import Func + class Position(Func): - function = 'POSITION' + function = "POSITION" template = "%(function)s('%(substring)s' in %(expressions)s)" def __init__(self, expression, substring): @@ -1271,11 +1324,13 @@ This function generates an SQL string without any parameters. Since ``substring`` is passed to ``super().__init__()`` as a keyword argument, it's interpolated into the SQL string before the query is sent to the database. -Here's a corrected rewrite:: +Here's a corrected rewrite: + +.. code-block:: python class Position(Func): - function = 'POSITION' - arg_joiner = ' IN ' + function = "POSITION" + arg_joiner = " IN " def __init__(self, expression, substring): super().__init__(substring, expression) @@ -1293,12 +1348,16 @@ onto the function's class. Let's say we're writing a backend for Microsoft's SQL Server which uses the SQL ``LEN`` instead of ``LENGTH`` for the :class:`~functions.Length` function. We'll monkey patch a new method called ``as_sqlserver()`` onto the ``Length`` -class:: +class: + +.. code-block:: python from django.db.models.functions import Length + def sqlserver_length(self, compiler, connection): - return self.as_sql(compiler, connection, function='LEN') + return self.as_sql(compiler, connection, function="LEN") + Length.as_sqlserver = sqlserver_length diff --git a/docs/ref/models/fields.txt b/docs/ref/models/fields.txt index ae9af535ba06b..f52c26819dc0c 100644 --- a/docs/ref/models/fields.txt +++ b/docs/ref/models/fields.txt @@ -93,33 +93,38 @@ default form widget will be a select box with these choices instead of the standard text field. The first element in each tuple is the actual value to be set on the model, -and the second element is the human-readable name. For example:: +and the second element is the human-readable name. For example: + +.. code-block:: python YEAR_IN_SCHOOL_CHOICES = [ - ('FR', 'Freshman'), - ('SO', 'Sophomore'), - ('JR', 'Junior'), - ('SR', 'Senior'), - ('GR', 'Graduate'), + ("FR", "Freshman"), + ("SO", "Sophomore"), + ("JR", "Junior"), + ("SR", "Senior"), + ("GR", "Graduate"), ] Generally, it's best to define choices inside a model class, and to -define a suitably-named constant for each value:: +define a suitably-named constant for each value: + +.. code-block:: python from django.db import models + class Student(models.Model): - FRESHMAN = 'FR' - SOPHOMORE = 'SO' - JUNIOR = 'JR' - SENIOR = 'SR' - GRADUATE = 'GR' + FRESHMAN = "FR" + SOPHOMORE = "SO" + JUNIOR = "JR" + SENIOR = "SR" + GRADUATE = "GR" YEAR_IN_SCHOOL_CHOICES = [ - (FRESHMAN, 'Freshman'), - (SOPHOMORE, 'Sophomore'), - (JUNIOR, 'Junior'), - (SENIOR, 'Senior'), - (GRADUATE, 'Graduate'), + (FRESHMAN, "Freshman"), + (SOPHOMORE, "Sophomore"), + (JUNIOR, "Junior"), + (SENIOR, "Senior"), + (GRADUATE, "Graduate"), ] year_in_school = models.CharField( max_length=2, @@ -139,20 +144,26 @@ will work anywhere that the ``Student`` model has been imported). .. _field-choices-named-groups: You can also collect your available choices into named groups that can -be used for organizational purposes:: +be used for organizational purposes: + +.. code-block:: python MEDIA_CHOICES = [ - ('Audio', ( - ('vinyl', 'Vinyl'), - ('cd', 'CD'), - ) + ( + "Audio", + ( + ("vinyl", "Vinyl"), + ("cd", "CD"), + ), ), - ('Video', ( - ('vhs', 'VHS Tape'), - ('dvd', 'DVD'), - ) + ( + "Video", + ( + ("vhs", "VHS Tape"), + ("dvd", "DVD"), + ), ), - ('unknown', 'Unknown'), + ("unknown", "Unknown"), ] The first element in each tuple is the name to apply to the group. The @@ -180,7 +191,7 @@ meant for static data that doesn't change much, if ever. Unless :attr:`blank=False` is set on the field along with a :attr:`~Field.default` then a label containing ``"---------"`` will be rendered with the select box. To override this behavior, add a tuple to ``choices`` -containing ``None``; e.g. ``(None, 'Your String For Display')``. +containing ``None``; e.g. ``(None, "Your String For Display")``. Alternatively, you can use an empty string instead of ``None`` where this makes sense - such as on a :class:`~django.db.models.CharField`. @@ -190,18 +201,20 @@ Enumeration types ~~~~~~~~~~~~~~~~~ In addition, Django provides enumeration types that you can subclass to define -choices in a concise way:: +choices in a concise way: + +.. code-block:: python from django.utils.translation import gettext_lazy as _ - class Student(models.Model): + class Student(models.Model): class YearInSchool(models.TextChoices): - FRESHMAN = 'FR', _('Freshman') - SOPHOMORE = 'SO', _('Sophomore') - JUNIOR = 'JR', _('Junior') - SENIOR = 'SR', _('Senior') - GRADUATE = 'GR', _('Graduate') + FRESHMAN = "FR", _("Freshman") + SOPHOMORE = "SO", _("Sophomore") + JUNIOR = "JR", _("Junior") + SENIOR = "SR", _("Senior") + GRADUATE = "GR", _("Graduate") year_in_school = models.CharField( max_length=2, @@ -242,7 +255,7 @@ modifications: field. Note that using ``YearInSchool.SENIOR``, ``YearInSchool['SENIOR']``, or -``YearInSchool('SR')`` to access or lookup enum members work as expected, as do +``YearInSchool("SR")`` to access or lookup enum members work as expected, as do the ``.name`` and ``.value`` properties on the members. .. _field-choices-enum-auto-label: @@ -308,13 +321,15 @@ There are some additional caveats to be aware of: - Because an enumeration with a concrete data type requires all values to match the type, overriding the :ref:`blank label ` cannot be achieved by creating a member with a value of ``None``. Instead, - set the ``__empty__`` attribute on the class:: + set the ``__empty__`` attribute on the class: + +.. code-block:: python class Answer(models.IntegerChoices): - NO = 0, _('No') - YES = 1, _('Yes') + NO = 0, _("No") + YES = 1, _("Yes") - __empty__ = _('(Unknown)') + __empty__ = _("(Unknown)") ``db_column`` ------------- @@ -787,14 +802,16 @@ Has the following optional arguments: If you specify a string value or a :class:`~pathlib.Path`, it may contain :func:`~time.strftime` formatting, which will be replaced by the date/time of the file upload (so that uploaded files don't fill up the given - directory). For example:: + directory). For example: + + .. code-block:: python class MyModel(models.Model): # file will be uploaded to MEDIA_ROOT/uploads - upload = models.FileField(upload_to='uploads/') + upload = models.FileField(upload_to="uploads/") # or... # file will be saved to MEDIA_ROOT/uploads/2015/01/30 - upload = models.FileField(upload_to='uploads/%Y/%m/%d/') + upload = models.FileField(upload_to="uploads/%Y/%m/%d/") If you are using the default :class:`~django.core.files.storage.FileSystemStorage`, the string value @@ -957,7 +974,7 @@ A read-only property to access the file's relative URL by calling the :meth:`~django.core.files.storage.Storage.url` method of the underlying :class:`~django.core.files.storage.Storage` class. -.. method:: FieldFile.open(mode='rb') +.. method:: FieldFile.open(mode="rb") Opens or reopens the file associated with this instance in the specified ``mode``. Unlike the standard Python ``open()`` method, it doesn't return a @@ -989,11 +1006,14 @@ saved after the file associated with this field has been altered. Defaults to Note that the ``content`` argument should be an instance of :class:`django.core.files.File`, not Python's built-in file object. You can construct a :class:`~django.core.files.File` from an existing -Python file object like this:: +Python file object like this: + +.. code-block:: python from django.core.files import File + # Open an existing file using Python's built-in open() - f = open('/path/to/hello.world') + f = open("/path/to/hello.world") myfile = File(f) Or you can construct one from a Python string like this:: @@ -1035,14 +1055,18 @@ directory on the filesystem. Has some special arguments, of which the first is :class:`FilePathField` should get its choices. Example: ``"/home/images"``. ``path`` may also be a callable, such as a function to dynamically set the - path at runtime. Example:: + path at runtime. Example: + + .. code-block:: python import os from django.conf import settings from django.db import models + def images_path(): - return os.path.join(settings.LOCAL_FILE_DIR, 'images') + return os.path.join(settings.LOCAL_FILE_DIR, "images") + class MyModel(models.Model): file = models.FilePathField(path=images_path) @@ -1581,10 +1605,12 @@ The possible values for :attr:`~ForeignKey.on_delete` are found in ``Artist`` can be deleted even if that implies deleting an ``Album`` which is referenced by a ``Song``, because ``Song`` also references - ``Artist`` itself through a cascading relationship. For example:: + ``Artist`` itself through a cascading relationship. For example: + + .. code-block:: pycon - >>> artist_one = Artist.objects.create(name='artist one') - >>> artist_two = Artist.objects.create(name='artist two') + >>> artist_one = Artist.objects.create(name="artist one") + >>> artist_two = Artist.objects.create(name="artist two") >>> album_one = Album.objects.create(artist=artist_one) >>> album_two = Album.objects.create(artist=artist_two) >>> song_one = Song.objects.create(artist=artist_one, album=album_one) @@ -1612,14 +1638,18 @@ The possible values for :attr:`~ForeignKey.on_delete` are found in :func:`~django.db.models.SET()`, or if a callable is passed in, the result of calling it. In most cases, passing a callable will be necessary to avoid executing queries at the time your ``models.py`` is - imported:: + imported: + + .. code-block:: python from django.conf import settings from django.contrib.auth import get_user_model from django.db import models + def get_sentinel_user(): - return get_user_model().objects.get_or_create(username='deleted')[0] + return get_user_model().objects.get_or_create(username="deleted")[0] + class MyModel(models.Model): user = models.ForeignKey( @@ -1885,21 +1915,26 @@ that control how the relationship functions. Only used when a custom intermediary model is specified. Django will normally determine which fields of the intermediary model to use in order to establish a many-to-many relationship automatically. However, - consider the following models:: + consider the following models: + + .. code-block:: python from django.db import models + class Person(models.Model): name = models.CharField(max_length=50) + class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField( Person, - through='Membership', - through_fields=('group', 'person'), + through="Membership", + through_fields=("group", "person"), ) + class Membership(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) diff --git a/docs/ref/models/indexes.txt b/docs/ref/models/indexes.txt index c6633d69985e1..81b42799ad95f 100644 --- a/docs/ref/models/indexes.txt +++ b/docs/ref/models/indexes.txt @@ -33,16 +33,20 @@ options`_. Positional argument ``*expressions`` allows creating functional indexes on expressions and database functions. -For example:: +For example: - Index(Lower('title').desc(), 'pub_date', name='lower_title_date_idx') +.. code-block:: python + + Index(Lower("title").desc(), "pub_date", name="lower_title_date_idx") creates an index on the lowercased value of the ``title`` field in descending order and the ``pub_date`` field in the default ascending order. -Another example:: +Another example: + +.. code-block:: python - Index(F('height') * F('weight'), Round('weight'), name='calc_idx') + Index(F("height") * F("weight"), Round("weight"), name="calc_idx") creates an index on the result of multiplying fields ``height`` and ``weight`` and the ``weight`` rounded to the nearest integer. @@ -195,9 +199,11 @@ as non-key columns. This allows index-only scans to be used for queries that select only included fields (:attr:`~Index.include`) and filter only by indexed fields (:attr:`~Index.fields`). -For example:: +For example: + +.. code-block:: python - Index(name='covering_index', fields=['headline'], include=['pub_date']) + Index(name="covering_index", fields=["headline"], include=["pub_date"]) will allow filtering on ``headline``, also selecting ``pub_date``, while fetching data only from the index. diff --git a/docs/ref/models/instances.txt b/docs/ref/models/instances.txt index 53fa6c387d83e..bf2251fd86370 100644 --- a/docs/ref/models/instances.txt +++ b/docs/ref/models/instances.txt @@ -32,10 +32,13 @@ need to :meth:`~Model.save()`. signature as any change may prevent the model instance from being saved. Rather than overriding ``__init__``, try using one of these approaches: - #. Add a classmethod on the model class:: + #. Add a classmethod on the model class: + + .. code-block:: python from django.db import models + class Book(models.Model): title = models.CharField(max_length=100) @@ -45,9 +48,12 @@ need to :meth:`~Model.save()`. # do something with the book return book + book = Book.create("Pride and Prejudice") - #. Add a method on a custom manager (usually preferred):: + #. Add a method on a custom manager (usually preferred): + + .. code-block:: python class BookManager(models.Manager): def create_book(self, title): @@ -55,11 +61,13 @@ need to :meth:`~Model.save()`. # do something with the book return book + class Book(models.Model): title = models.CharField(max_length=100) objects = BookManager() + book = Book.objects.create_book("Pride and Prejudice") Customizing model loading @@ -84,10 +92,13 @@ In addition to creating the new model, the ``from_db()`` method must set the ``adding`` and ``db`` flags in the new instance's :attr:`~Model._state` attribute. Below is an example showing how to record the initial values of fields that -are loaded from the database:: +are loaded from the database: + +.. code-block:: python from django.db.models import DEFERRED + @classmethod def from_db(cls, db, field_names, values): # Default implementation of from_db() (subject to change and could @@ -108,12 +119,14 @@ are loaded from the database:: ) return instance + def save(self, *args, **kwargs): # Check how the current values differ from ._loaded_values. For example, # prevent changing the creator_id of the model. (This example doesn't # support cases where 'creator_id' is deferred). if not self._state.adding and ( - self.creator_id != self._loaded_values['creator_id']): + self.creator_id != self._loaded_values["creator_id"] + ): raise ValueError("Updating the value of creator isn't allowed") super().save(*args, **kwargs) @@ -159,11 +172,13 @@ It is possible to force the set of fields to be loaded by using the ``fields`` argument. For example, to test that an ``update()`` call resulted in the expected -update, you could write a test similar to this:: +update, you could write a test similar to this: + +.. code-block:: python def test_update_result(self): obj = MyModel.objects.create(val=1) - MyModel.objects.filter(pk=obj.pk).update(val=F('val') + 1) + MyModel.objects.filter(pk=obj.pk).update(val=F("val") + 1) # At this point obj.val is still 1, but the value in the database # was updated to 2. The object's updated value needs to be reloaded # from the database. @@ -173,7 +188,9 @@ update, you could write a test similar to this:: Note that when deferred fields are accessed, the loading of the deferred field's value happens through this method. Thus it is possible to customize the way deferred loading happens. The example below shows how one can reload -all of the instance's fields when a deferred field is reloaded:: +all of the instance's fields when a deferred field is reloaded: + +.. code-block:: python class ExampleModel(models.Model): def refresh_from_db(self, using=None, fields=None, **kwargs): @@ -253,9 +270,12 @@ not be corrected by the user. Note that ``full_clean()`` will *not* be called automatically when you call your model's :meth:`~Model.save()` method. You'll need to call it manually when you want to run one-step model validation for your own manually created -models. For example:: +models. For example: + +.. code-block:: python from django.core.exceptions import ValidationError + try: article.full_clean() except ValidationError as e: @@ -288,21 +308,25 @@ This method should be overridden to perform custom validation on your model. This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires -access to more than a single field:: +access to more than a single field: + +.. code-block:: python import datetime from django.core.exceptions import ValidationError from django.db import models from django.utils.translation import gettext_lazy as _ + class Article(models.Model): ... + def clean(self): # Don't allow draft entries to have a pub_date. - if self.status == 'draft' and self.pub_date is not None: - raise ValidationError(_('Draft entries may not have a publication date.')) + if self.status == "draft" and self.pub_date is not None: + raise ValidationError(_("Draft entries may not have a publication date.")) # Set the pub_date for published items if it hasn't been set already. - if self.status == 'published' and self.pub_date is None: + if self.status == "published" and self.pub_date is None: self.pub_date = datetime.date.today() Note, however, that like :meth:`Model.full_clean()`, a model's ``clean()`` @@ -312,9 +336,12 @@ In the above example, the :exc:`~django.core.exceptions.ValidationError` exception raised by ``Model.clean()`` was instantiated with a string, so it will be stored in a special error dictionary key, :data:`~django.core.exceptions.NON_FIELD_ERRORS`. This key is used for errors -that are tied to the entire model instead of to a specific field:: +that are tied to the entire model instead of to a specific field: + +.. code-block:: python from django.core.exceptions import NON_FIELD_ERRORS, ValidationError + try: article.full_clean() except ValidationError as e: @@ -323,23 +350,32 @@ that are tied to the entire model instead of to a specific field:: To assign exceptions to a specific field, instantiate the :exc:`~django.core.exceptions.ValidationError` with a dictionary, where the keys are the field names. We could update the previous example to assign the -error to the ``pub_date`` field:: +error to the ``pub_date`` field: + +.. code-block:: python class Article(models.Model): ... + def clean(self): # Don't allow draft entries to have a pub_date. - if self.status == 'draft' and self.pub_date is not None: - raise ValidationError({'pub_date': _('Draft entries may not have a publication date.')}) + if self.status == "draft" and self.pub_date is not None: + raise ValidationError( + {"pub_date": _("Draft entries may not have a publication date.")} + ) ... If you detect errors in multiple fields during ``Model.clean()``, you can also -pass a dictionary mapping field names to errors:: +pass a dictionary mapping field names to errors: + +.. code-block:: python - raise ValidationError({ - 'title': ValidationError(_('Missing title.'), code='required'), - 'pub_date': ValidationError(_('Invalid date.'), code='invalid'), - }) + raise ValidationError( + { + "title": ValidationError(_("Missing title."), code="required"), + "pub_date": ValidationError(_("Invalid date."), code="invalid"), + } + ) Then, ``full_clean()`` will check unique constraints on your model. @@ -353,24 +389,28 @@ Then, ``full_clean()`` will check unique constraints on your model. To work around this dilemma, instead override :meth:`Model.clean_fields() ` as it receives the list of fields - that are excluded from validation. For example:: + that are excluded from validation. For example: + + .. code-block:: python class Article(models.Model): ... + def clean_fields(self, exclude=None): super().clean_fields(exclude=exclude) - if self.status == 'draft' and self.pub_date is not None: - if exclude and 'status' in exclude: + if self.status == "draft" and self.pub_date is not None: + if exclude and "status" in exclude: raise ValidationError( - _('Draft entries may not have a publication date.') + _("Draft entries may not have a publication date.") ) else: - raise ValidationError({ - 'status': _( - 'Set status to draft if there is not a ' - 'publication date.' - ), - }) + raise ValidationError( + { + "status": _( + "Set status to draft if there is not a " "publication date." + ), + } + ) .. method:: Model.validate_unique(exclude=None) @@ -486,9 +526,11 @@ primary-key value that already exists in the database, Django will assume you're changing the existing record rather than creating a new one. Given the above ``'Cheddar Talk'`` blog example, this example would override the -previous record in the database:: +previous record in the database: - b4 = Blog(id=3, name='Not Cheddar', tagline='Anything but cheese.') +.. code-block:: python + + b4 = Blog(id=3, name="Not Cheddar", tagline="Anything but cheese.") b4.save() # Overrides the previous blog with ID=3! See `How Django knows to UPDATE vs. INSERT`_, below, for the reason this @@ -751,20 +793,26 @@ instances with a primary key value of ``None`` aren't equal to anything except themselves. For proxy models, concrete class is defined as the model's first non-proxy parent; for all other models it's simply the model's class. -For example:: +For example: + +.. code-block:: python from django.db import models + class MyModel(models.Model): id = models.AutoField(primary_key=True) + class MyProxyModel(MyModel): class Meta: proxy = True + class MultitableInherited(MyModel): pass + # Primary keys compared MyModel(id=1) == MyModel(id=1) MyModel(id=1) != MyModel(id=2) @@ -799,7 +847,9 @@ Define a ``get_absolute_url()`` method to tell Django how to calculate the canonical URL for an object. To callers, this method should appear to return a string that can be used to refer to the object over HTTP. -For example:: +For example: + +.. code-block:: python def get_absolute_url(self): return "/people/%i/" % self.id @@ -808,11 +858,14 @@ While this code is correct and simple, it may not be the most portable way to to write this kind of method. The :func:`~django.urls.reverse` function is usually the best approach. -For example:: +For example: + +.. code-block:: python def get_absolute_url(self): from django.urls import reverse - return reverse('people-detail', kwargs={'pk' : self.pk}) + + return reverse("people-detail", kwargs={"pk": self.pk}) One place Django uses ``get_absolute_url()`` is in the admin app. If an object defines this method, the object-editing page will have a "View on site" link @@ -827,10 +880,12 @@ URL, you should define ``get_absolute_url()``. .. warning:: You should avoid building the URL from unvalidated user input, in order to - reduce possibilities of link or redirect poisoning:: + reduce possibilities of link or redirect poisoning: + + .. code-block:: python def get_absolute_url(self): - return '/%s/' % self.name + return "/%s/" % self.name If ``self.name`` is ``'/example.com'`` this returns ``'//example.com/'`` which, in turn, is a valid schema relative URL but not the expected @@ -878,15 +933,18 @@ For every field that has :attr:`~django.db.models.Field.choices` set, the object will have a ``get_FOO_display()`` method, where ``FOO`` is the name of the field. This method returns the "human-readable" value of the field. -For example:: +For example: + +.. code-block:: python from django.db import models + class Person(models.Model): SHIRT_SIZES = [ - ('S', 'Small'), - ('M', 'Medium'), - ('L', 'Large'), + ("S", "Small"), + ("M", "Medium"), + ("L", "Large"), ] name = models.CharField(max_length=60) shirt_size = models.CharField(max_length=2, choices=SHIRT_SIZES) diff --git a/docs/ref/models/lookups.txt b/docs/ref/models/lookups.txt index d71424c9061ae..1e28a1f8baf95 100644 --- a/docs/ref/models/lookups.txt +++ b/docs/ref/models/lookups.txt @@ -44,10 +44,12 @@ register lookups on itself or its instances. The two prominent examples are .. classmethod:: register_lookup(lookup, lookup_name=None) - Registers a new lookup in the class or class instance. For example:: + Registers a new lookup in the class or class instance. For example: + + .. code-block:: python DateField.register_lookup(YearExact) - User._meta.get_field('date_joined').register_lookup(MonthExact) + User._meta.get_field("date_joined").register_lookup(MonthExact) will register ``YearExact`` lookup on ``DateField`` and ``MonthExact`` lookup on the ``User.date_joined`` (you can use :ref:`Field Access API @@ -193,13 +195,17 @@ following methods: The primary notation to use a lookup in an expression is ``__=``. Lookups can also be used directly in - ``QuerySet`` filters:: + ``QuerySet`` filters: + + .. code-block:: python - Book.objects.filter(LessThan(F('word_count'), 7500)) + Book.objects.filter(LessThan(F("word_count"), 7500)) - …or annotations:: + …or annotations: + + .. code-block:: python - Book.objects.annotate(is_short_story=LessThan(F('word_count'), 7500)) + Book.objects.annotate(is_short_story=LessThan(F("word_count"), 7500)) .. attribute:: lhs diff --git a/docs/ref/models/options.txt b/docs/ref/models/options.txt index a1629168af189..9dbd5efdd0fa4 100644 --- a/docs/ref/models/options.txt +++ b/docs/ref/models/options.txt @@ -137,13 +137,15 @@ Django quotes column and table names behind the scenes. :meth:`~django.db.models.query.QuerySet.latest` and :meth:`~django.db.models.query.QuerySet.earliest` methods. - Example:: + Example: + + .. code-block:: python # Latest by ascending order_date. get_latest_by = "order_date" # Latest by priority descending, order_date ascending. - get_latest_by = ['-priority', 'order_date'] + get_latest_by = ["-priority", "order_date"] See the :meth:`~django.db.models.query.QuerySet.latest` docs for more. @@ -196,40 +198,50 @@ Django quotes column and table names behind the scenes. ``ForeignKey``. This can be used to make related objects orderable with respect to a parent object. For example, if an ``Answer`` relates to a ``Question`` object, and a question has more than one answer, and the order - of answers matters, you'd do this:: + of answers matters, you'd do this: + + .. code-block:: python from django.db import models + class Question(models.Model): text = models.TextField() # ... + class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) # ... class Meta: - order_with_respect_to = 'question' + order_with_respect_to = "question" When ``order_with_respect_to`` is set, two additional methods are provided to retrieve and to set the order of the related objects: ``get_RELATED_order()`` and ``set_RELATED_order()``, where ``RELATED`` is the lowercased model name. For example, assuming that a ``Question`` object has multiple related ``Answer`` objects, the list returned contains the primary keys of the related ``Answer`` - objects:: + objects: + + .. code-block:: pycon >>> question = Question.objects.get(id=1) >>> question.get_answer_order() [1, 2, 3] The order of a ``Question`` object's related ``Answer`` objects can be set by - passing in a list of ``Answer`` primary keys:: + passing in a list of ``Answer`` primary keys: + + .. code-block:: pycon >>> question.set_answer_order([3, 1, 2]) The related objects also get two methods, ``get_next_in_order()`` and ``get_previous_in_order()``, which can be used to access those objects in their - proper order. Assuming the ``Answer`` objects are ordered by ``id``:: + proper order. Assuming the ``Answer`` objects are ordered by ``id``: + + .. code-block:: pycon >>> answer = Answer.objects.get(id=2) >>> answer.get_next_in_order() @@ -257,33 +269,43 @@ Django quotes column and table names behind the scenes. .. attribute:: Options.ordering - The default ordering for the object, for use when obtaining lists of objects:: + The default ordering for the object, for use when obtaining lists of objects: + + .. code-block:: python - ordering = ['-order_date'] + ordering = ["-order_date"] This is a tuple or list of strings and/or query expressions. Each string is a field name with an optional "-" prefix, which indicates descending order. Fields without a leading "-" will be ordered ascending. Use the string "?" to order randomly. - For example, to order by a ``pub_date`` field ascending, use this:: + For example, to order by a ``pub_date`` field ascending, use this: + + .. code-block:: python - ordering = ['pub_date'] + ordering = ["pub_date"] - To order by ``pub_date`` descending, use this:: + To order by ``pub_date`` descending, use this: + + .. code-block:: python - ordering = ['-pub_date'] + ordering = ["-pub_date"] - To order by ``pub_date`` descending, then by ``author`` ascending, use this:: + To order by ``pub_date`` descending, then by ``author`` ascending, use this: + + .. code-block:: python - ordering = ['-pub_date', 'author'] + ordering = ["-pub_date", "author"] You can also use :doc:`query expressions `. To - order by ``author`` ascending and make null values sort last, use this:: + order by ``author`` ascending and make null values sort last, use this: + + .. code-block:: python from django.db.models import F - ordering = [F('author').asc(nulls_last=True)] + ordering = [F("author").asc(nulls_last=True)] .. warning:: @@ -304,9 +326,11 @@ Django quotes column and table names behind the scenes. Extra permissions to enter into the permissions table when creating this object. Add, change, delete, and view permissions are automatically created for each - model. This example specifies an extra permission, ``can_deliver_pizzas``:: + model. This example specifies an extra permission, ``can_deliver_pizzas``: + + .. code-block:: python - permissions = [('can_deliver_pizzas', 'Can deliver pizzas')] + permissions = [("can_deliver_pizzas", "Can deliver pizzas")] This is a list or tuple of 2-tuples in the format ``(permission_code, human_readable_permission_name)``. @@ -378,18 +402,21 @@ Django quotes column and table names behind the scenes. .. attribute:: Options.indexes A list of :doc:`indexes ` that you want to define on - the model:: + the model: + + .. code-block:: python from django.db import models + class Customer(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Meta: indexes = [ - models.Index(fields=['last_name', 'first_name']), - models.Index(fields=['first_name'], name='first_name_idx'), + models.Index(fields=["last_name", "first_name"]), + models.Index(fields=["first_name"], name="first_name_idx"), ] ``unique_together`` @@ -431,7 +458,9 @@ Django quotes column and table names behind the scenes. .. attribute:: Options.index_together - Sets of field names that, taken together, are indexed:: + Sets of field names that, taken together, are indexed: + + .. code-block:: python index_together = [ ["pub_date", "deadline"], @@ -441,7 +470,9 @@ Django quotes column and table names behind the scenes. ``CREATE INDEX`` statement will be issued.) For convenience, ``index_together`` can be a single list when dealing with a single - set of fields:: + set of fields: + + .. code-block:: python index_together = ["pub_date", "deadline"] @@ -455,16 +486,19 @@ Django quotes column and table names behind the scenes. .. attribute:: Options.constraints A list of :doc:`constraints ` that you want to - define on the model:: + define on the model: + + .. code-block:: python from django.db import models + class Customer(models.Model): age = models.IntegerField() class Meta: constraints = [ - models.CheckConstraint(check=models.Q(age__gte=18), name='age_gte_18'), + models.CheckConstraint(check=models.Q(age__gte=18), name="age_gte_18"), ] ``verbose_name`` @@ -472,7 +506,9 @@ Django quotes column and table names behind the scenes. .. attribute:: Options.verbose_name - A human-readable name for the object, singular:: + A human-readable name for the object, singular: + + .. code-block:: python verbose_name = "pizza" @@ -484,7 +520,9 @@ Django quotes column and table names behind the scenes. .. attribute:: Options.verbose_name_plural - The plural name for the object:: + The plural name for the object: + + .. code-block:: python verbose_name_plural = "stories" diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt index 59dc8354cb468..a926c90bb592e 100644 --- a/docs/ref/models/querysets.txt +++ b/docs/ref/models/querysets.txt @@ -124,10 +124,12 @@ described here. .. admonition:: Restrictions on ``QuerySet.values_list()`` If you recreate :meth:`QuerySet.values_list` using the pickled ``query`` - attribute, it will be converted to :meth:`QuerySet.values`:: + attribute, it will be converted to :meth:`QuerySet.values`: + + .. code-block:: pycon >>> import pickle - >>> qs = Blog.objects.values_list('id', 'name') + >>> qs = Blog.objects.values_list("id", "name") >>> qs >>> reloaded_qs = Blog.objects.all() @@ -225,9 +227,11 @@ The lookup parameters (``**kwargs``) should be in the format described in underlying SQL statement, and the whole thing is enclosed in a ``NOT()``. This example excludes all entries whose ``pub_date`` is later than 2005-1-3 -AND whose ``headline`` is "Hello":: +AND whose ``headline`` is "Hello": - Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3), headline='Hello') +.. code-block:: python + + Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3), headline="Hello") In SQL terms, that evaluates to: @@ -237,9 +241,11 @@ In SQL terms, that evaluates to: WHERE NOT (pub_date > '2005-1-3' AND headline = 'Hello') This example excludes all entries whose ``pub_date`` is later than 2005-1-3 -OR whose headline is "Hello":: +OR whose headline is "Hello": + +.. code-block:: python - Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3)).exclude(headline='Hello') + Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3)).exclude(headline="Hello") In SQL terms, that evaluates to: @@ -329,11 +335,13 @@ interested in the exact number of entries, you could do this: ``alias()`` can be used in conjunction with :meth:`annotate`, :meth:`exclude`, :meth:`filter`, :meth:`order_by`, and :meth:`update`. To use aliased expression with other methods (e.g. :meth:`aggregate`), you must promote it to an -annotation:: +annotation: + +.. code-block:: python - Blog.objects.alias(entries=Count('entry')).annotate( - entries=F('entries'), - ).aggregate(Sum('entries')) + Blog.objects.alias(entries=Count("entry")).annotate( + entries=F("entries"), + ).aggregate(Sum("entries")) :meth:`filter` and :meth:`order_by` can take expressions directly, but expression construction and usage often does not happen in the same place (for @@ -351,16 +359,20 @@ By default, results returned by a ``QuerySet`` are ordered by the ordering tuple given by the ``ordering`` option in the model's ``Meta``. You can override this on a per-``QuerySet`` basis by using the ``order_by`` method. -Example:: +Example: + +.. code-block:: python - Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline') + Entry.objects.filter(pub_date__year=2005).order_by("-pub_date", "headline") The result above will be ordered by ``pub_date`` descending, then by ``headline`` ascending. The negative sign in front of ``"-pub_date"`` indicates *descending* order. Ascending order is implied. To order randomly, use ``"?"``, -like so:: +like so: - Entry.objects.order_by('?') +.. code-block:: python + + Entry.objects.order_by("?") Note: ``order_by('?')`` queries may be expensive and slow, depending on the database backend you're using. @@ -368,32 +380,42 @@ database backend you're using. To order by a field in a different model, use the same syntax as when you are querying across model relations. That is, the name of the field, followed by a double underscore (``__``), followed by the name of the field in the new model, -and so on for as many models as you want to join. For example:: +and so on for as many models as you want to join. For example: + +.. code-block:: python - Entry.objects.order_by('blog__name', 'headline') + Entry.objects.order_by("blog__name", "headline") If you try to order by a field that is a relation to another model, Django will use the default ordering on the related model, or order by the related model's primary key if there is no :attr:`Meta.ordering ` specified. For example, since the ``Blog`` -model has no default ordering specified:: +model has no default ordering specified: + +.. code-block:: python - Entry.objects.order_by('blog') + Entry.objects.order_by("blog") -...is identical to:: +...is identical to: - Entry.objects.order_by('blog__id') +.. code-block:: python + + Entry.objects.order_by("blog__id") If ``Blog`` had ``ordering = ['name']``, then the first queryset would be -identical to:: +identical to: + +.. code-block:: python - Entry.objects.order_by('blog__name') + Entry.objects.order_by("blog__name") You can also order by :doc:`query expressions ` by calling :meth:`~.Expression.asc` or :meth:`~.Expression.desc` on the -expression:: +expression: - Entry.objects.order_by(Coalesce('summary', 'headline').desc()) +.. code-block:: python + + Entry.objects.order_by(Coalesce("summary", "headline").desc()) :meth:`~.Expression.asc` and :meth:`~.Expression.desc` have arguments (``nulls_first`` and ``nulls_last``) that control how null values are sorted. @@ -407,17 +429,20 @@ related model ordering can change the expected results. (for example, a :class:`~django.db.models.ManyToManyField` field, or the reverse relation of a :class:`~django.db.models.ForeignKey` field). - Consider this case:: + Consider this case: + + .. code-block:: python class Event(Model): - parent = models.ForeignKey( - 'self', - on_delete=models.CASCADE, - related_name='children', - ) - date = models.DateField() + parent = models.ForeignKey( + "self", + on_delete=models.CASCADE, + related_name="children", + ) + date = models.DateField() + - Event.objects.order_by('children__date') + Event.objects.order_by("children__date") Here, there could potentially be multiple ordering data for each ``Event``; each ``Event`` with multiple ``children`` will be returned multiple times @@ -437,9 +462,11 @@ backend normally orders them. You can order by a field converted to lowercase with :class:`~django.db.models.functions.Lower` which will achieve case-consistent -ordering:: +ordering: - Entry.objects.order_by(Lower('headline').desc()) +.. code-block:: python + + Entry.objects.order_by(Lower("headline").desc()) If you don't want any ordering to be applied to a query, not even the default ordering, call :meth:`order_by()` with no parameters. @@ -449,9 +476,11 @@ You can tell if a query is ordered or not by checking the ``QuerySet`` has been ordered in any way. Each ``order_by()`` call will clear any previous ordering. For example, this -query will be ordered by ``pub_date`` and not ``headline``:: +query will be ordered by ``pub_date`` and not ``headline``: + +.. code-block:: python - Entry.objects.order_by('headline').order_by('pub_date') + Entry.objects.order_by("headline").order_by("pub_date") .. warning:: @@ -568,9 +597,11 @@ Examples (those after the first will only work on PostgreSQL): ``_id`` or referenced field to make sure the ``DISTINCT ON`` expressions match those at the beginning of the ``ORDER BY`` clause. For example, if the ``Blog`` model defined an :attr:`~django.db.models.Options.ordering` by - ``name``:: + ``name``: + + .. code-block:: python - Entry.objects.order_by('blog').distinct('blog') + Entry.objects.order_by("blog").distinct("blog") ...wouldn't work because the query would be ordered by ``blog__name`` thus mismatching the ``DISTINCT ON`` expression. You'd have to explicitly order @@ -589,14 +620,16 @@ Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects. This example compares the dictionaries of ``values()`` with the normal model -objects:: +objects: + +.. code-block:: pycon # This list contains a Blog object. - >>> Blog.objects.filter(name__startswith='Beatles') + >>> Blog.objects.filter(name__startswith="Beatles") ]> # This list contains a dictionary. - >>> Blog.objects.filter(name__startswith='Beatles').values() + >>> Blog.objects.filter(name__startswith="Beatles").values() The ``values()`` method takes optional positional arguments, ``*fields``, which @@ -709,7 +742,9 @@ of the available fields and you won't need the functionality of a model instance object. It's more efficient to select only the fields you need to use. Finally, note that you can call ``filter()``, ``order_by()``, etc. after the -``values()`` call, that means that these two calls are identical:: +``values()`` call, that means that these two calls are identical: + +.. code-block:: pycon Blog.objects.values().order_by('id') Blog.objects.order_by('id').values() @@ -837,7 +872,7 @@ not having any author: ``dates()`` ~~~~~~~~~~~ -.. method:: dates(field, kind, order='ASC') +.. method:: dates(field, kind, order="ASC") Returns a ``QuerySet`` that evaluates to a list of :class:`datetime.date` objects representing all available dates of a particular kind within the @@ -1041,10 +1076,12 @@ The following examples illustrate the difference between plain lookups and # Hits the database again to get the related Blog object. b = e.blog -And here's ``select_related`` lookup:: +And here's ``select_related`` lookup: + +.. code-block:: python # Hits the database. - e = Entry.objects.select_related('blog').get(id=5) + e = Entry.objects.select_related("blog").get(id=5) # Doesn't hit the database, because e.blog has been prepopulated # in the previous query. @@ -1052,31 +1089,39 @@ And here's ``select_related`` lookup:: You can use ``select_related()`` with any queryset of objects:: +.. code-block:: python + from django.utils import timezone # Find all the blogs with entries scheduled to be published in the future. blogs = set() - for e in Entry.objects.filter(pub_date__gt=timezone.now()).select_related('blog'): + for e in Entry.objects.filter(pub_date__gt=timezone.now()).select_related("blog"): # Without select_related(), this would make a database query for each # loop iteration in order to fetch the related blog for each entry. blogs.add(e.blog) The order of ``filter()`` and ``select_related()`` chaining isn't important. -These querysets are equivalent:: +These querysets are equivalent: - Entry.objects.filter(pub_date__gt=timezone.now()).select_related('blog') - Entry.objects.select_related('blog').filter(pub_date__gt=timezone.now()) +.. code-block:: python + + Entry.objects.filter(pub_date__gt=timezone.now()).select_related("blog") + Entry.objects.select_related("blog").filter(pub_date__gt=timezone.now()) You can follow foreign keys in a similar way to querying them. If you have the -following models:: +following models: + +.. code-block:: python from django.db import models + class City(models.Model): # ... pass + class Person(models.Model): # ... hometown = models.ForeignKey( @@ -1086,22 +1131,25 @@ following models:: null=True, ) + class Book(models.Model): # ... author = models.ForeignKey(Person, on_delete=models.CASCADE) -... then a call to ``Book.objects.select_related('author__hometown').get(id=4)`` -will cache the related ``Person`` *and* the related ``City``:: +... then a call to ``Book.objects.select_related("author__hometown").get(id=4)`` +will cache the related ``Person`` *and* the related ``City``: + +.. code-block:: python # Hits the database with joins to the author and hometown tables. - b = Book.objects.select_related('author__hometown').get(id=4) - p = b.author # Doesn't hit the database. - c = p.hometown # Doesn't hit the database. + b = Book.objects.select_related("author__hometown").get(id=4) + p = b.author # Doesn't hit the database. + c = p.hometown # Doesn't hit the database. # Without select_related()... b = Book.objects.get(id=4) # Hits the database. - p = b.author # Hits the database. - c = p.hometown # Hits the database. + p = b.author # Hits the database. + c = p.hometown # Hits the database. You can refer to any :class:`~django.db.models.ForeignKey` or :class:`~django.db.models.OneToOneField` relation in the list of fields @@ -1191,7 +1239,9 @@ item in the Pizza ``QuerySet``. We can reduce to just two queries using ``prefetch_related``: - >>> Pizza.objects.prefetch_related('toppings') +.. code-block:: pycon + + >>> Pizza.objects.prefetch_related("toppings") This implies a ``self.toppings.all()`` for each ``Pizza``; now each time ``self.toppings.all()`` is called, instead of having to go to the database for @@ -1222,7 +1272,9 @@ database. results, and retrieve data using a fresh database query. So, if you write the following: - >>> pizzas = Pizza.objects.prefetch_related('toppings') + .. code-block:: pycon + + >>> pizzas = Pizza.objects.prefetch_related("toppings") >>> [list(pizza.toppings.filter(spicy=True)) for pizza in pizzas] ...then the fact that ``pizza.toppings.all()`` has been prefetched will not @@ -1241,21 +1293,29 @@ database. any prefetched cache for the relation will be cleared. You can also use the normal join syntax to do related fields of related -fields. Suppose we have an additional model to the example above:: +fields. Suppose we have an additional model to the example above: + +.. code-block:: python class Restaurant(models.Model): - pizzas = models.ManyToManyField(Pizza, related_name='restaurants') - best_pizza = models.ForeignKey(Pizza, related_name='championed_by', on_delete=models.CASCADE) + pizzas = models.ManyToManyField(Pizza, related_name="restaurants") + best_pizza = models.ForeignKey( + Pizza, related_name="championed_by", on_delete=models.CASCADE + ) The following are all legal: - >>> Restaurant.objects.prefetch_related('pizzas__toppings') +.. code-block:: pycon + + >>> Restaurant.objects.prefetch_related("pizzas__toppings") This will prefetch all pizzas belonging to restaurants, and all toppings belonging to those pizzas. This will result in a total of 3 database queries - one for the restaurants, one for the pizzas, and one for the toppings. - >>> Restaurant.objects.prefetch_related('best_pizza__toppings') +.. code-block:: pycon + + >>> Restaurant.objects.prefetch_related("best_pizza__toppings") This will fetch the best pizza and all the toppings for the best pizza for each restaurant. This will be done in 3 database queries - one for the restaurants, @@ -1309,20 +1369,28 @@ the prefetch operation. In its simplest form ``Prefetch`` is equivalent to the traditional string based lookups: +.. code-block:: pycon + >>> from django.db.models import Prefetch - >>> Restaurant.objects.prefetch_related(Prefetch('pizzas__toppings')) + >>> Restaurant.objects.prefetch_related(Prefetch("pizzas__toppings")) You can provide a custom queryset with the optional ``queryset`` argument. This can be used to change the default ordering of the queryset: +.. code-block:: pycon + >>> Restaurant.objects.prefetch_related( - ... Prefetch('pizzas__toppings', queryset=Toppings.objects.order_by('name'))) + ... Prefetch("pizzas__toppings", queryset=Toppings.objects.order_by("name")) + ... ) Or to call :meth:`~django.db.models.query.QuerySet.select_related()` when applicable to reduce the number of queries even further: +.. code-block:: pycon + >>> Pizza.objects.prefetch_related( - ... Prefetch('restaurants', queryset=Restaurant.objects.select_related('best_pizza'))) + ... Prefetch("restaurants", queryset=Restaurant.objects.select_related("best_pizza")) + ... ) You can also assign the prefetched result to a custom attribute with the optional ``to_attr`` argument. The result will be stored directly in a list. @@ -1330,32 +1398,40 @@ You can also assign the prefetched result to a custom attribute with the optiona This allows prefetching the same relation multiple times with a different ``QuerySet``; for instance: +.. code-block:: pycon + >>> vegetarian_pizzas = Pizza.objects.filter(vegetarian=True) >>> Restaurant.objects.prefetch_related( - ... Prefetch('pizzas', to_attr='menu'), - ... Prefetch('pizzas', queryset=vegetarian_pizzas, to_attr='vegetarian_menu')) + ... Prefetch("pizzas", to_attr="menu"), + ... Prefetch("pizzas", queryset=vegetarian_pizzas, to_attr="vegetarian_menu"), + ... ) Lookups created with custom ``to_attr`` can still be traversed as usual by other lookups: +.. code-block:: pycon + >>> vegetarian_pizzas = Pizza.objects.filter(vegetarian=True) >>> Restaurant.objects.prefetch_related( - ... Prefetch('pizzas', queryset=vegetarian_pizzas, to_attr='vegetarian_menu'), - ... 'vegetarian_menu__toppings') + ... Prefetch("pizzas", queryset=vegetarian_pizzas, to_attr="vegetarian_menu"), + ... "vegetarian_menu__toppings", + ... ) Using ``to_attr`` is recommended when filtering down the prefetch result as it is less ambiguous than storing a filtered result in the related manager's cache: +.. code-block:: pycon + >>> queryset = Pizza.objects.filter(vegetarian=True) >>> >>> # Recommended: >>> restaurants = Restaurant.objects.prefetch_related( - ... Prefetch('pizzas', queryset=queryset, to_attr='vegetarian_pizzas')) + ... Prefetch("pizzas", queryset=queryset, to_attr="vegetarian_pizzas") + ... ) >>> vegetarian_pizzas = restaurants[0].vegetarian_pizzas >>> >>> # Not recommended: - >>> restaurants = Restaurant.objects.prefetch_related( - ... Prefetch('pizzas', queryset=queryset)) + >>> restaurants = Restaurant.objects.prefetch_related(Prefetch("pizzas", queryset=queryset)) >>> vegetarian_pizzas = restaurants[0].pizzas.all() Custom prefetching also works with single related relations like @@ -1371,10 +1447,13 @@ where prefetching with a custom ``QuerySet`` is useful: * You want to use performance optimization techniques like :meth:`deferred fields `: - >>> queryset = Pizza.objects.only('name') + .. code-block:: pycon + + >>> queryset = Pizza.objects.only("name") >>> >>> restaurants = Restaurant.objects.prefetch_related( - ... Prefetch('best_pizza', queryset=queryset)) + ... Prefetch("best_pizza", queryset=queryset) + ... ) When using multiple databases, ``Prefetch`` will respect your choice of database. If the inner query does not specify a database, it will use the @@ -1404,7 +1483,9 @@ database selected by the outer query. All of the following are valid: Take the following examples: - >>> prefetch_related('pizzas__toppings', 'pizzas') + .. code-block:: pycon + + >>> prefetch_related("pizzas__toppings", "pizzas") This works even though it's unordered because ``'pizzas__toppings'`` already contains all the needed information, therefore the second argument @@ -1417,7 +1498,9 @@ database selected by the outer query. All of the following are valid: created to traverse ``'pizzas'`` as part of the ``'pizzas__toppings'`` lookup. - >>> prefetch_related('pizza_list__toppings', Prefetch('pizzas', to_attr='pizza_list')) + .. code-block:: pycon + + >>> prefetch_related("pizza_list__toppings", Prefetch("pizzas", to_attr="pizza_list")) This will trigger an ``AttributeError`` because ``'pizza_list'`` doesn't exist yet when ``'pizza_list__toppings'`` is being processed. @@ -1448,14 +1531,18 @@ generated by a ``QuerySet``. that we can enhance the QuerySet API to allow removing ``extra()``. We are no longer improving or fixing bugs for this method. - For example, this use of ``extra()``:: + For example, this use of ``extra()``: + + .. code-block:: pycon >>> qs.extra( - ... select={'val': "select col from sometable where othercol = %s"}, + ... select={"val": "select col from sometable where othercol = %s"}, ... select_params=(someparam,), ... ) - is equivalent to:: + is equivalent to: + + .. code-block:: pycon >>> qs.annotate(val=RawSQL("select col from sometable where othercol = %s", (someparam,))) @@ -1540,11 +1627,13 @@ of the arguments is required, but you should use at least one of them. fragments in ``extra(select=...)``. For this purpose, use the ``select_params`` parameter. - This will work, for example:: + This will work, for example: + + .. code-block:: python Blog.objects.extra( - select={'a': '%s', 'b': '%s'}, - select_params=('one', 'two'), + select={"a": "%s", "b": "%s"}, + select_params=("one", "two"), ) If you need to use a literal ``%s`` inside your select string, use @@ -1722,25 +1811,29 @@ one, doing so will result in an error. reader, is slightly faster and consumes a little less memory in the Python process. - For example, both of these models use the same underlying database table:: + For example, both of these models use the same underlying database table: + + .. code-block:: python class CommonlyUsedModel(models.Model): f1 = models.CharField(max_length=10) class Meta: managed = False - db_table = 'app_largetable' + db_table = "app_largetable" + class ManagedModel(models.Model): f1 = models.CharField(max_length=10) f2 = models.CharField(max_length=10) class Meta: - db_table = 'app_largetable' + db_table = "app_largetable" + # Two equivalent QuerySets: CommonlyUsedModel.objects.all() - ManagedModel.objects.defer('f2') + ManagedModel.objects.defer("f2") If many fields need to be duplicated in the unmanaged model, it may be best to create an abstract model with the shared fields and then have the @@ -1818,11 +1911,13 @@ this method takes is the alias of a database, as defined in For example:: +.. code-block:: pycon + # queries the database with the 'default' alias. >>> Entry.objects.all() # queries the database with the 'backup' alias - >>> Entry.objects.using('backup') + >>> Entry.objects.using("backup") ``select_for_update()`` ~~~~~~~~~~~~~~~~~~~~~~~ @@ -1832,7 +1927,9 @@ For example:: Returns a queryset that will lock rows until the end of the transaction, generating a ``SELECT ... FOR UPDATE`` SQL statement on supported databases. -For example:: +For example: + +.. code-block:: python from django.db import transaction @@ -1868,9 +1965,11 @@ to refer to the queryset's model. If you want to lock parents models when using :ref:`multi-table inheritance `, you must specify parent link fields (by default - ``_ptr``) in the ``of`` argument. For example:: + ``_ptr``) in the ``of`` argument. For example: + + .. code-block:: python - Restaurant.objects.select_for_update(of=('self', 'place_ptr')) + Restaurant.objects.select_for_update(of=("self", "place_ptr")) .. admonition:: Using ``select_for_update(of=(...))`` with specified fields @@ -1967,11 +2066,14 @@ AND (``&``) Combines two ``QuerySet``\s using the SQL ``AND`` operator. -The following are equivalent:: +The following are equivalent: + +.. code-block:: python Model.objects.filter(x=1) & Model.objects.filter(y=2) Model.objects.filter(x=1, y=2) from django.db.models import Q + Model.objects.filter(Q(x=1) & Q(y=2)) SQL equivalent: @@ -1985,10 +2087,13 @@ OR (``|``) Combines two ``QuerySet``\s using the SQL ``OR`` operator. -The following are equivalent:: +The following are equivalent: + +.. code-block:: python Model.objects.filter(x=1) | Model.objects.filter(y=2) from django.db.models import Q + Model.objects.filter(Q(x=1) | Q(y=2)) SQL equivalent: @@ -2007,10 +2112,13 @@ XOR (``^``) Combines two ``QuerySet``\s using the SQL ``XOR`` operator. -The following are equivalent:: +The following are equivalent: + +.. code-block:: python Model.objects.filter(x=1) ^ Model.objects.filter(y=2) from django.db.models import Q + Model.objects.filter(Q(x=1) ^ Q(y=2)) SQL equivalent: @@ -2066,32 +2174,42 @@ nature, but any differences are noted below next to each method. Returns the object matching the given lookup parameters, which should be in the format described in `Field lookups`_. You should use lookups that are guaranteed unique, such as the primary key or fields in a unique constraint. -For example:: +For example: + +.. code-block:: python Entry.objects.get(id=1) Entry.objects.get(Q(blog=blog) & Q(entry_number=1)) If you expect a queryset to already return one row, you can use ``get()`` -without any arguments to return the object for that row:: +without any arguments to return the object for that row: + +.. code-block:: python Entry.objects.filter(pk=1).get() If ``get()`` doesn't find any object, it raises a :exc:`Model.DoesNotExist -` exception:: +` exception: - Entry.objects.get(id=-999) # raises Entry.DoesNotExist +.. code-block:: python + + Entry.objects.get(id=-999) # raises Entry.DoesNotExist If ``get()`` finds more than one object, it raises a :exc:`Model.MultipleObjectsReturned -` exception:: +` exception: + +.. code-block:: python - Entry.objects.get(name='A Duplicated Name') # raises Entry.MultipleObjectsReturned + Entry.objects.get(name="A Duplicated Name") # raises Entry.MultipleObjectsReturned Both these exception classes are attributes of the model class, and specific to that model. If you want to handle such exceptions from several ``get()`` calls for different models, you can use their generic base classes. For example, you can use :exc:`django.core.exceptions.ObjectDoesNotExist` to handle -:exc:`~django.db.models.Model.DoesNotExist` exceptions from multiple models:: +:exc:`~django.db.models.Model.DoesNotExist` exceptions from multiple models: + +.. code-block:: python from django.core.exceptions import ObjectDoesNotExist @@ -2113,11 +2231,15 @@ can use :exc:`django.core.exceptions.ObjectDoesNotExist` to handle *Asynchronous version*: ``acreate()`` -A convenience method for creating an object and saving it all in one step. Thus:: +A convenience method for creating an object and saving it all in one step. Thus: + +.. code-block:: python p = Person.objects.create(first_name="Bruce", last_name="Springsteen") -and:: +and: + +.. code-block:: python p = Person(first_name="Bruce", last_name="Springsteen") p.save(force_insert=True) @@ -2152,22 +2274,26 @@ created object and ``created`` is a boolean specifying whether a new object was created. This is meant to prevent duplicate objects from being created when requests are -made in parallel, and as a shortcut to boilerplatish code. For example:: +made in parallel, and as a shortcut to boilerplatish code. For example: + +.. code-block:: python try: - obj = Person.objects.get(first_name='John', last_name='Lennon') + obj = Person.objects.get(first_name="John", last_name="Lennon") except Person.DoesNotExist: - obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9)) + obj = Person(first_name="John", last_name="Lennon", birthday=date(1940, 10, 9)) obj.save() Here, with concurrent requests, multiple attempts to save a ``Person`` with the same parameters may be made. To avoid this race condition, the above -example can be rewritten using ``get_or_create()`` like so:: +example can be rewritten using ``get_or_create()`` like so: + +.. code-block:: python obj, created = Person.objects.get_or_create( - first_name='John', - last_name='Lennon', - defaults={'birthday': date(1940, 10, 9)}, + first_name="John", + last_name="Lennon", + defaults={"birthday": date(1940, 10, 9)}, ) Any keyword arguments passed to ``get_or_create()`` — *except* an optional one @@ -2186,21 +2312,25 @@ found, ``get_or_create()`` returns a tuple of that object and ``False``. You can specify more complex conditions for the retrieved object by chaining ``get_or_create()`` with ``filter()`` and using :class:`Q objects `. For example, to retrieve Robert or Bob Marley if either -exists, and create the latter otherwise:: +exists, and create the latter otherwise: + +.. code-block:: python from django.db.models import Q obj, created = Person.objects.filter( - Q(first_name='Bob') | Q(first_name='Robert'), - ).get_or_create(last_name='Marley', defaults={'first_name': 'Bob'}) + Q(first_name="Bob") | Q(first_name="Robert"), + ).get_or_create(last_name="Marley", defaults={"first_name": "Bob"}) If multiple objects are found, ``get_or_create()`` raises :exc:`~django.core.exceptions.MultipleObjectsReturned`. If an object is *not* found, ``get_or_create()`` will instantiate and save a new object, returning a tuple of the new object and ``True``. The new object will be created roughly -according to this algorithm:: +according to this algorithm: - params = {k: v for k, v in kwargs.items() if '__' not in k} +.. code-block:: python + + params = {k: v for k, v in kwargs.items() if "__" not in k} params.update({k: v() if callable(v) else v for k, v in defaults.items()}) obj = self.model(**params) obj.save() @@ -2215,9 +2345,11 @@ details. The internal implementation has some more error-checking than this and handles some extra edge-conditions; if you're interested, read the code. If you have a field named ``defaults`` and want to use it as an exact lookup in -``get_or_create()``, use ``'defaults__exact'``, like so:: +``get_or_create()``, use ``'defaults__exact'``, like so: + +.. code-block:: python - Foo.objects.get_or_create(defaults__exact='bar', defaults={'defaults': 'baz'}) + Foo.objects.get_or_create(defaults__exact="bar", defaults={"defaults": "baz"}) The ``get_or_create()`` method has similar error behavior to :meth:`create()` when you're using manually specified primary keys. If an object needs to be @@ -2237,17 +2369,22 @@ whenever a request to a page has a side effect on your data. For more, see inside the context of that relation. That could lead you to some integrity problems if you don't use it consistently. - Being the following models:: + Being the following models: + + .. code-block:: python class Chapter(models.Model): title = models.CharField(max_length=255, unique=True) + class Book(models.Model): title = models.CharField(max_length=256) chapters = models.ManyToManyField(Chapter) You can use ``get_or_create()`` through Book's chapters field, but it only - fetches inside the context of that book:: + fetches inside the context of that book: + + .. code-block:: pycon >>> book = Book.objects.create(title="Ulysses") >>> book.chapters.get_or_create(title="Telemachus") @@ -2288,26 +2425,31 @@ The ``update_or_create`` method tries to fetch an object from database based on the given ``kwargs``. If a match is found, it updates the fields passed in the ``defaults`` dictionary. -This is meant as a shortcut to boilerplatish code. For example:: +This is meant as a shortcut to boilerplatish code. For example: + +.. code-block:: python - defaults = {'first_name': 'Bob'} + defaults = {"first_name": "Bob"} try: - obj = Person.objects.get(first_name='John', last_name='Lennon') + obj = Person.objects.get(first_name="John", last_name="Lennon") for key, value in defaults.items(): setattr(obj, key, value) obj.save() except Person.DoesNotExist: - new_values = {'first_name': 'John', 'last_name': 'Lennon'} + new_values = {"first_name": "John", "last_name": "Lennon"} new_values.update(defaults) obj = Person(**new_values) obj.save() This pattern gets quite unwieldy as the number of fields in a model goes up. -The above example can be rewritten using ``update_or_create()`` like so:: +The above example can be rewritten using ``update_or_create()`` like so: + +.. code-block:: python obj, created = Person.objects.update_or_create( - first_name='John', last_name='Lennon', - defaults={'first_name': 'Bob'}, + first_name="John", + last_name="Lennon", + defaults={"first_name": "Bob"}, ) For a detailed description of how names passed in ``kwargs`` are resolved, see @@ -2360,12 +2502,14 @@ This has a number of caveats though: generator. The cast allows inspecting all objects so that any objects with a manually set primary key can be inserted first. If you want to insert objects in batches without evaluating the entire generator at once, you can use this - technique as long as the objects don't have any manually set primary keys:: + technique as long as the objects don't have any manually set primary keys: + + .. code-block:: python from itertools import islice batch_size = 100 - objs = (Entry(headline='Test %s' % i) for i in range(1000)) + objs = (Entry(headline="Test %s" % i) for i in range(1000)) while True: batch = list(islice(objs, batch_size)) if not batch: @@ -2473,11 +2617,13 @@ the ``QuerySet``. Example:: +.. code-block:: python + # Returns the total number of entries in the database. Entry.objects.count() # Returns the number of entries whose headline contains 'Lennon' - Entry.objects.filter(headline__contains='Lennon').count() + Entry.objects.filter(headline__contains="Lennon").count() A ``count()`` call performs a ``SELECT COUNT(*)`` behind the scenes, so you should always use ``count()`` rather than loading all of the record into Python @@ -2654,15 +2800,19 @@ value for ``chunk_size`` will result in Django using an implicit default of Returns the latest object in the table based on the given field(s). This example returns the latest ``Entry`` in the table, according to the -``pub_date`` field:: +``pub_date`` field: + +.. code-block:: python - Entry.objects.latest('pub_date') + Entry.objects.latest("pub_date") You can also choose the latest based on several fields. For example, to select the ``Entry`` with the earliest ``expire_date`` when two entries have the same -``pub_date``:: +``pub_date``: + +.. code-block:: python - Entry.objects.latest('pub_date', '-expire_date') + Entry.objects.latest("pub_date", "-expire_date") The negative sign in ``'-expire_date'`` means to sort ``expire_date`` in *descending* order. Since ``latest()`` gets the last result, the ``Entry`` with @@ -2687,9 +2837,11 @@ readability. example, PostgreSQL and MySQL sort null values as if they are higher than non-null values, while SQLite does the opposite. - You may want to filter out null values:: + You may want to filter out null values: + + .. code-block:: python - Entry.objects.filter(pub_date__isnull=False).latest('pub_date') + Entry.objects.filter(pub_date__isnull=False).latest("pub_date") .. versionchanged:: 4.1 @@ -2723,15 +2875,19 @@ is no matching object. If the ``QuerySet`` has no ordering defined, then the queryset is automatically ordered by the primary key. This can affect aggregation results as described in :ref:`aggregation-ordering-interaction`. -Example:: +Example: + +.. code-block:: python - p = Article.objects.order_by('title', 'pub_date').first() + p = Article.objects.order_by("title", "pub_date").first() Note that ``first()`` is a convenience method, the following code sample is -equivalent to the above example:: +equivalent to the above example: + +.. code-block:: python try: - p = Article.objects.order_by('title', 'pub_date')[0] + p = Article.objects.order_by("title", "pub_date")[0] except IndexError: p = None @@ -2817,12 +2973,16 @@ possible, but it *does* execute nearly the same query as a normal any objects in a :class:`.QuerySet`, particularly in the context of a large :class:`.QuerySet`. -To find whether a queryset contains any items:: +To find whether a queryset contains any items: + +.. code-block:: python if some_queryset.exists(): print("There is at least one object in some_queryset") -Which will be faster than:: +Which will be faster than: + +.. code-block:: python if some_queryset: print("There is at least one object in some_queryset") @@ -2854,16 +3014,20 @@ not. This tries to perform the query in the simplest and fastest way possible. :meth:`contains` is useful for checking an object membership in a :class:`.QuerySet`, particularly in the context of a large :class:`.QuerySet`. -To check whether a queryset contains a specific item:: +To check whether a queryset contains a specific item: + +.. code-block:: python if some_queryset.contains(obj): - print('Entry contained in queryset') + print("Entry contained in queryset") This will be faster than the following which requires evaluating and iterating -through the entire queryset:: +through the entire queryset: + +.. code-block:: python if obj in some_queryset: - print('Entry contained in queryset') + print("Entry contained in queryset") Like :meth:`exists`, if ``some_queryset`` has not yet been evaluated, but you know that it will be at some point, then using ``some_queryset.contains(obj)`` @@ -2936,13 +3100,17 @@ The ``update()`` method returns the number of affected rows: If you're just updating a record and don't need to do anything with the model object, the most efficient approach is to call ``update()``, rather than -loading the model object into memory. For example, instead of doing this:: +loading the model object into memory. For example, instead of doing this: + +.. code-block:: python e = Entry.objects.get(id=10) e.comments_on = False e.save() -...do this:: +...do this: + +.. code-block:: python Entry.objects.filter(id=10).update(comments_on=False) @@ -2957,7 +3125,9 @@ does not call any ``save()`` methods on your models, nor does it emit the calling :meth:`Model.save() `). If you want to update a bunch of records for a model that has a custom :meth:`~django.db.models.Model.save()` method, loop over them and call -:meth:`~django.db.models.Model.save()`, like this:: +:meth:`~django.db.models.Model.save()`, like this: + +.. code-block:: python for e in Entry.objects.filter(pub_date__year=2010): e.comments_on = False @@ -2972,9 +3142,11 @@ Ordered queryset Chaining ``order_by()`` with ``update()`` is supported only on MariaDB and MySQL, and is ignored for different databases. This is useful for updating a -unique field in the order that is specified without conflicts. For example:: +unique field in the order that is specified without conflicts. For example: - Entry.objects.order_by('-number').update(number=F('number') + 1) +.. code-block:: python + + Entry.objects.order_by("-number").update(number=F("number") + 1) .. note:: @@ -3138,7 +3310,9 @@ As a convenience when no lookup type is provided (like in Exact match. If the value provided for comparison is ``None``, it will be interpreted as an SQL ``NULL`` (see :lookup:`isnull` for more details). -Examples:: +Examples: + +.. code-block:: python Entry.objects.get(id__exact=14) Entry.objects.get(id__exact=None) @@ -3168,9 +3342,11 @@ Case-insensitive exact match. If the value provided for comparison is ``None``, it will be interpreted as an SQL ``NULL`` (see :lookup:`isnull` for more details). -Example:: +Example: - Blog.objects.get(name__iexact='beatles blog') +.. code-block:: python + + Blog.objects.get(name__iexact="beatles blog") Blog.objects.get(name__iexact=None) SQL equivalents: @@ -3196,9 +3372,11 @@ Note the first query will match ``'Beatles Blog'``, ``'beatles blog'``, Case-sensitive containment test. -Example:: +Example: - Entry.objects.get(headline__contains='Lennon') +.. code-block:: python + + Entry.objects.get(headline__contains="Lennon") SQL equivalent: @@ -3223,9 +3401,11 @@ honored today'``. Case-insensitive containment test. -Example:: +Example: - Entry.objects.get(headline__icontains='Lennon') +.. code-block:: python + + Entry.objects.get(headline__icontains="Lennon") SQL equivalent: @@ -3246,10 +3426,12 @@ SQL equivalent: In a given iterable; often a list, tuple, or queryset. It's not a common use case, but strings (being iterables) are accepted. -Examples:: +Examples: + +.. code-block:: python Entry.objects.filter(id__in=[1, 3, 4]) - Entry.objects.filter(headline__in='abc') + Entry.objects.filter(headline__in="abc") SQL equivalents: @@ -3259,9 +3441,11 @@ SQL equivalents: SELECT ... WHERE headline IN ('a', 'b', 'c'); You can also use a queryset to dynamically evaluate the list of values -instead of providing a list of literal values:: +instead of providing a list of literal values: - inner_qs = Blog.objects.filter(name__contains='Cheddar') +.. code-block:: python + + inner_qs = Blog.objects.filter(name__contains="Cheddar") entries = Entry.objects.filter(blog__in=inner_qs) This queryset will be evaluated as subselect statement: @@ -3273,16 +3457,20 @@ This queryset will be evaluated as subselect statement: If you pass in a ``QuerySet`` resulting from ``values()`` or ``values_list()`` as the value to an ``__in`` lookup, you need to ensure you are only extracting one field in the result. For example, this will work (filtering on the blog -names):: +names): + +.. code-block:: python - inner_qs = Blog.objects.filter(name__contains='Ch').values('name') + inner_qs = Blog.objects.filter(name__contains="Ch").values("name") entries = Entry.objects.filter(blog__name__in=inner_qs) This example will raise an exception, since the inner query is trying to -extract two field values, where only one is expected:: +extract two field values, where only one is expected: + +.. code-block:: python # Bad code! Will raise a TypeError. - inner_qs = Blog.objects.filter(name__contains='Ch').values('name', 'id') + inner_qs = Blog.objects.filter(name__contains="Ch").values("name", "id") entries = Entry.objects.filter(blog__name__in=inner_qs) .. _nested-queries-performance: @@ -3294,10 +3482,11 @@ extract two field values, where only one is expected:: database backends, most notably MySQL, don't optimize nested queries very well. It is more efficient, in those cases, to extract a list of values and then pass that into the second query. That is, execute two queries - instead of one:: + instead of one: + + .. code-block:: python - values = Blog.objects.filter( - name__contains='Cheddar').values_list('pk', flat=True) + values = Blog.objects.filter(name__contains="Cheddar").values_list("pk", flat=True) entries = Entry.objects.filter(blog__in=list(values)) Note the ``list()`` call around the Blog ``QuerySet`` to force execution of @@ -3349,9 +3538,11 @@ Less than or equal to. Case-sensitive starts-with. -Example:: +Example: - Entry.objects.filter(headline__startswith='Lennon') +.. code-block:: python + + Entry.objects.filter(headline__startswith="Lennon") SQL equivalent: @@ -3369,9 +3560,11 @@ like ``istartswith`` for SQLite. Case-insensitive starts-with. -Example:: +Example: + +.. code-block:: python - Entry.objects.filter(headline__istartswith='Lennon') + Entry.objects.filter(headline__istartswith="Lennon") SQL equivalent: @@ -3391,9 +3584,11 @@ SQL equivalent: Case-sensitive ends-with. -Example:: +Example: + +.. code-block:: python - Entry.objects.filter(headline__endswith='Lennon') + Entry.objects.filter(headline__endswith="Lennon") SQL equivalent: @@ -3414,9 +3609,11 @@ SQL equivalent: Case-insensitive ends-with. -Example:: +Example: + +.. code-block:: python - Entry.objects.filter(headline__iendswith='Lennon') + Entry.objects.filter(headline__iendswith="Lennon") SQL equivalent: @@ -3473,7 +3670,9 @@ numbers and even characters. For datetime fields, casts the value as date. Allows chaining additional field lookups. Takes a date value. -Example:: +Example: + +.. code-block:: python Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1)) Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1)) @@ -3493,7 +3692,9 @@ database `. For date and datetime fields, an exact year match. Allows chaining additional field lookups. Takes an integer year. -Example:: +Example: + +.. code-block:: python Entry.objects.filter(pub_date__year=2005) Entry.objects.filter(pub_date__year__gte=2005) @@ -3538,7 +3739,9 @@ in the database `. For date and datetime fields, an exact month match. Allows chaining additional field lookups. Takes an integer 1 (January) through 12 (December). -Example:: +Example: + +.. code-block:: python Entry.objects.filter(pub_date__month=12) Entry.objects.filter(pub_date__month__gte=6) @@ -3617,7 +3820,9 @@ additional field lookups. Takes an integer value representing the day of week from 1 (Sunday) to 7 (Saturday). -Example:: +Example: + +.. code-block:: python Entry.objects.filter(pub_date__week_day=2) Entry.objects.filter(pub_date__week_day__gte=2) @@ -3644,7 +3849,9 @@ chaining additional field lookups. Takes an integer value representing the day of the week from 1 (Monday) to 7 (Sunday). -Example:: +Example: + +.. code-block:: python Entry.objects.filter(pub_date__iso_week_day=1) Entry.objects.filter(pub_date__iso_week_day__gte=1) @@ -3669,7 +3876,9 @@ For date and datetime fields, a 'quarter of the year' match. Allows chaining additional field lookups. Takes an integer value between 1 and 4 representing the quarter of the year. -Example to retrieve entries in the second quarter (April 1 to June 30):: +Example to retrieve entries in the second quarter (April 1 to June 30): + +.. code-block:: python Entry.objects.filter(pub_date__quarter=2) @@ -3688,7 +3897,9 @@ in the database `. For datetime fields, casts the value as time. Allows chaining additional field lookups. Takes a :class:`datetime.time` value. -Example:: +Example: + +.. code-block:: python Entry.objects.filter(pub_date__time=datetime.time(14, 30)) Entry.objects.filter(pub_date__time__range=(datetime.time(8), datetime.time(17))) @@ -3708,7 +3919,9 @@ database `. For datetime and time fields, an exact hour match. Allows chaining additional field lookups. Takes an integer between 0 and 23. -Example:: +Example: + +.. code-block:: python Event.objects.filter(timestamp__hour=23) Event.objects.filter(time__hour=5) @@ -3736,7 +3949,9 @@ in the database `. For datetime and time fields, an exact minute match. Allows chaining additional field lookups. Takes an integer between 0 and 59. -Example:: +Example: + +.. code-block:: python Event.objects.filter(timestamp__minute=29) Event.objects.filter(time__minute=46) @@ -3764,7 +3979,9 @@ in the database `. For datetime and time fields, an exact second match. Allows chaining additional field lookups. Takes an integer between 0 and 59. -Example:: +Example: + +.. code-block:: python Event.objects.filter(timestamp__second=31) Event.objects.filter(time__second=2) @@ -3814,9 +4031,11 @@ In the case of SQLite, which has no built in regular expression support, this feature is provided by a (Python) user-defined REGEXP function, and the regular expression syntax is therefore that of Python's ``re`` module. -Example:: +Example: - Entry.objects.get(title__regex=r'^(An?|The) +') +.. code-block:: python + + Entry.objects.get(title__regex=r"^(An?|The) +") SQL equivalents: @@ -3840,9 +4059,11 @@ regular expression syntax is recommended. Case-insensitive regular expression match. -Example:: +Example: - Entry.objects.get(title__iregex=r'^(an?|the) +') +.. code-block:: python + + Entry.objects.get(title__iregex=r"^(an?|the) +") SQL equivalents: @@ -4073,12 +4294,14 @@ The ``lookup`` argument describes the relations to follow and works the same as the string based lookups passed to :meth:`~django.db.models.query.QuerySet.prefetch_related()`. For example: +.. code-block:: pycon + >>> from django.db.models import Prefetch - >>> Question.objects.prefetch_related(Prefetch('choice_set')).get().choice_set.all() + >>> Question.objects.prefetch_related(Prefetch("choice_set")).get().choice_set.all() , , ]> # This will only execute two queries regardless of the number of Question # and Choice objects. - >>> Question.objects.prefetch_related(Prefetch('choice_set')) + >>> Question.objects.prefetch_related(Prefetch("choice_set")) ]> The ``queryset`` argument supplies a base ``QuerySet`` for the given lookup. @@ -4086,17 +4309,21 @@ This is useful to further filter down the prefetch operation, or to call :meth:`~django.db.models.query.QuerySet.select_related()` from the prefetched relation, hence reducing the number of queries even further: +.. code-block:: pycon + >>> voted_choices = Choice.objects.filter(votes__gt=0) >>> voted_choices ]> - >>> prefetch = Prefetch('choice_set', queryset=voted_choices) + >>> prefetch = Prefetch("choice_set", queryset=voted_choices) >>> Question.objects.prefetch_related(prefetch).get().choice_set.all() ]> The ``to_attr`` argument sets the result of the prefetch operation to a custom attribute: - >>> prefetch = Prefetch('choice_set', queryset=voted_choices, to_attr='voted_choices') +.. code-block:: pycon + + >>> prefetch = Prefetch("choice_set", queryset=voted_choices, to_attr="voted_choices") >>> Question.objects.prefetch_related(prefetch).get().voted_choices [] >>> Question.objects.prefetch_related(prefetch).get().choice_set.all()