mirror of
https://github.com/django/django.git
synced 2025-10-23 21:59:11 +00:00
Refs #36485 -- Rewrapped docs to 79 columns line length.
Lines in the docs files were manually adjusted to conform to the 79 columns limit per line (plus newline), improving readability and consistency across the content.
This commit is contained in:
@@ -77,5 +77,5 @@ Attributes
|
||||
# Add manager with another name
|
||||
people = models.Manager()
|
||||
|
||||
For more details on model managers see :doc:`Managers </topics/db/managers>`
|
||||
and :ref:`Retrieving objects <retrieving-objects>`.
|
||||
For more details on model managers see :doc:`Managers
|
||||
</topics/db/managers>` and :ref:`Retrieving objects <retrieving-objects>`.
|
||||
|
||||
@@ -288,10 +288,10 @@ Defaults to :attr:`.BaseConstraint.violation_error_code`, when either
|
||||
is not set.
|
||||
|
||||
If :attr:`.UniqueConstraint.fields` is set without a
|
||||
:attr:`.UniqueConstraint.condition`, defaults to the :attr:`Meta.unique_together
|
||||
<django.db.models.Options.unique_together>` error code when there are multiple
|
||||
fields, and to the :attr:`.Field.unique` error code when there is a single
|
||||
field.
|
||||
:attr:`.UniqueConstraint.condition`, defaults to the
|
||||
:attr:`Meta.unique_together <django.db.models.Options.unique_together>` error
|
||||
code when there are multiple fields, and to the :attr:`.Field.unique` error
|
||||
code when there is a single field.
|
||||
|
||||
.. versionchanged:: 5.2
|
||||
|
||||
@@ -313,10 +313,10 @@ Defaults to :attr:`.BaseConstraint.violation_error_message`, when either
|
||||
is not set.
|
||||
|
||||
If :attr:`.UniqueConstraint.fields` is set without a
|
||||
:attr:`.UniqueConstraint.condition`, defaults to the :attr:`Meta.unique_together
|
||||
<django.db.models.Options.unique_together>` error message when there are
|
||||
multiple fields, and to the :attr:`.Field.unique` error message when there is a
|
||||
single field.
|
||||
:attr:`.UniqueConstraint.condition`, defaults to the
|
||||
:attr:`Meta.unique_together <django.db.models.Options.unique_together>` error
|
||||
message when there are multiple fields, and to the :attr:`.Field.unique` error
|
||||
message when there is a single field.
|
||||
|
||||
.. versionchanged:: 5.2
|
||||
|
||||
|
||||
@@ -168,9 +168,9 @@ and ``comment.modified``.
|
||||
|
||||
.. class:: Least(*expressions, **extra)
|
||||
|
||||
Accepts a list of at least two field names or expressions and returns the
|
||||
least value. Each argument must be of a similar type, so mixing text and numbers
|
||||
will result in a database error.
|
||||
Accepts a list of at least two field names or expressions and returns the least
|
||||
value. Each argument must be of a similar type, so mixing text and numbers will
|
||||
result in a database error.
|
||||
|
||||
.. warning::
|
||||
|
||||
@@ -565,8 +565,8 @@ value. If ``output_field`` is omitted, it will default to the ``output_field``
|
||||
of ``expression``. A ``tzinfo`` subclass, usually provided by :mod:`zoneinfo`,
|
||||
can be passed to truncate a value in a specific timezone.
|
||||
|
||||
Given the datetime ``2015-06-15 14:30:50.000321+00:00``, the built-in ``kind``\s
|
||||
return:
|
||||
Given the datetime ``2015-06-15 14:30:50.000321+00:00``, the built-in
|
||||
``kind``\s return:
|
||||
|
||||
* "year": 2015-01-01 00:00:00+00:00
|
||||
* "quarter": 2015-04-01 00:00:00+00:00
|
||||
@@ -1823,7 +1823,8 @@ Usage example:
|
||||
|
||||
Returns a substring of length ``length`` from the field or expression starting
|
||||
at position ``pos``. The position is 1-indexed, so the position must be greater
|
||||
than 0. If ``length`` is ``None``, then the rest of the string will be returned.
|
||||
than 0. If ``length`` is ``None``, then the rest of the string will be
|
||||
returned.
|
||||
|
||||
Usage example:
|
||||
|
||||
|
||||
@@ -261,8 +261,8 @@ different fields with arithmetic::
|
||||
|
||||
If the fields that you're combining are of different types you'll need to tell
|
||||
Django what kind of field will be returned. Most expressions support
|
||||
:ref:`output_field<output-field>` for this case, but since ``F()`` does not, you
|
||||
will need to wrap the expression with :class:`ExpressionWrapper`::
|
||||
:ref:`output_field<output-field>` for this case, but since ``F()`` does not,
|
||||
you will need to wrap the expression with :class:`ExpressionWrapper`::
|
||||
|
||||
from django.db.models import DateTimeField, ExpressionWrapper, F
|
||||
|
||||
@@ -404,14 +404,15 @@ The ``Func`` API is as follows:
|
||||
)
|
||||
|
||||
To avoid an SQL injection vulnerability, ``extra_context`` :ref:`must
|
||||
not contain untrusted user input <avoiding-sql-injection-in-query-expressions>`
|
||||
as these values are interpolated into the SQL string rather than passed
|
||||
as query parameters, where the database driver would escape them.
|
||||
not contain untrusted user input
|
||||
<avoiding-sql-injection-in-query-expressions>` as these values are
|
||||
interpolated into the SQL string rather than passed as query
|
||||
parameters, where the database driver would escape them.
|
||||
|
||||
The ``*expressions`` argument is a list of positional expressions that the
|
||||
function will be applied to. The expressions will be converted to strings,
|
||||
joined together with ``arg_joiner``, and then interpolated into the ``template``
|
||||
as the ``expressions`` placeholder.
|
||||
joined together with ``arg_joiner``, and then interpolated into the
|
||||
``template`` as the ``expressions`` placeholder.
|
||||
|
||||
Positional arguments can be expressions or Python values. Strings are
|
||||
assumed to be column references and will be wrapped in ``F()`` expressions
|
||||
@@ -1381,14 +1382,17 @@ class::
|
||||
|
||||
Length.as_sqlserver = sqlserver_length
|
||||
|
||||
You can also customize the SQL using the ``template`` parameter of ``as_sql()``.
|
||||
You can also customize the SQL using the ``template`` parameter of
|
||||
``as_sql()``.
|
||||
|
||||
We use ``as_sqlserver()`` because ``django.db.connection.vendor`` returns
|
||||
``sqlserver`` for the backend.
|
||||
|
||||
Third-party backends can register their functions in the top level
|
||||
``__init__.py`` file of the backend package or in a top level ``expressions.py``
|
||||
file (or package) that is imported from the top level ``__init__.py``.
|
||||
``__init__.py`` file of the backend package or in a top level
|
||||
``expressions.py`` file (or package) that is imported from the top level
|
||||
``__init__.py``.
|
||||
|
||||
For user projects wishing to patch the backend that they're using, this code
|
||||
should live in an :meth:`AppConfig.ready()<django.apps.AppConfig.ready>` method.
|
||||
should live in an :meth:`AppConfig.ready()<django.apps.AppConfig.ready>`
|
||||
method.
|
||||
|
||||
@@ -39,17 +39,17 @@ The following arguments are available to all field types. All are optional.
|
||||
|
||||
.. attribute:: Field.null
|
||||
|
||||
If ``True``, Django will store empty values as ``NULL`` in the database. Default
|
||||
is ``False``.
|
||||
If ``True``, Django will store empty values as ``NULL`` in the database.
|
||||
Default is ``False``.
|
||||
|
||||
Avoid using :attr:`~Field.null` on string-based fields such as
|
||||
:class:`CharField` and :class:`TextField`. The Django convention is to use an
|
||||
empty string, not ``NULL``, as the "no data" state for string-based fields. If a
|
||||
string-based field has ``null=False``, empty strings can still be saved for "no
|
||||
data". If a string-based field has ``null=True``, that means it has two possible
|
||||
values for "no data": ``NULL``, and the empty string. In most cases, it's
|
||||
redundant to have two possible values for "no data". One exception is when a
|
||||
:class:`CharField` has both ``unique=True`` and ``blank=True`` set. In this
|
||||
empty string, not ``NULL``, as the "no data" state for string-based fields. If
|
||||
a string-based field has ``null=False``, empty strings can still be saved for
|
||||
"no data". If a string-based field has ``null=True``, that means it has two
|
||||
possible values for "no data": ``NULL``, and the empty string. In most cases,
|
||||
it's redundant to have two possible values for "no data". One exception is when
|
||||
a :class:`CharField` has both ``unique=True`` and ``blank=True`` set. In this
|
||||
situation, ``null=True`` is required to avoid unique constraint violations when
|
||||
saving multiple objects with blank values.
|
||||
|
||||
@@ -60,8 +60,8 @@ set ``blank=True`` if you wish to permit empty values in forms, as the
|
||||
|
||||
.. note::
|
||||
|
||||
When using the Oracle database backend, the value ``NULL`` will be stored to
|
||||
denote the empty string regardless of this attribute.
|
||||
When using the Oracle database backend, the value ``NULL`` will be stored
|
||||
to denote the empty string regardless of this attribute.
|
||||
|
||||
``blank``
|
||||
---------
|
||||
@@ -464,10 +464,10 @@ support tablespaces for indexes, this option is ignored.
|
||||
The default value for the field. This can be a value or a callable object. If
|
||||
callable it will be called every time a new object is created.
|
||||
|
||||
The default can't be a mutable object (model instance, ``list``, ``set``, etc.),
|
||||
as a reference to the same instance of that object would be used as the default
|
||||
value in all new model instances. Instead, wrap the desired default in a
|
||||
callable. For example, if you want to specify a default ``dict`` for
|
||||
The default can't be a mutable object (model instance, ``list``, ``set``,
|
||||
etc.), as a reference to the same instance of that object would be used as the
|
||||
default value in all new model instances. Instead, wrap the desired default in
|
||||
a callable. For example, if you want to specify a default ``dict`` for
|
||||
:class:`~django.db.models.JSONField`, use a function::
|
||||
|
||||
def contact_default():
|
||||
@@ -506,12 +506,12 @@ validation <validating-objects>`. Default is ``True``.
|
||||
.. attribute:: Field.error_messages
|
||||
|
||||
The ``error_messages`` argument lets you override the default messages that the
|
||||
field will raise. Pass in a dictionary with keys matching the error messages you
|
||||
want to override.
|
||||
field will raise. Pass in a dictionary with keys matching the error messages
|
||||
you want to override.
|
||||
|
||||
Error message keys include ``null``, ``blank``, ``invalid``, ``invalid_choice``,
|
||||
``unique``, and ``unique_for_date``. Additional error message keys are
|
||||
specified for each field in the `Field types`_ section below.
|
||||
Error message keys include ``null``, ``blank``, ``invalid``,
|
||||
``invalid_choice``, ``unique``, and ``unique_for_date``. Additional error
|
||||
message keys are specified for each field in the `Field types`_ section below.
|
||||
|
||||
These error messages often don't propagate to forms. See
|
||||
:ref:`considerations-regarding-model-errormessages`.
|
||||
@@ -654,10 +654,10 @@ Field types
|
||||
|
||||
.. class:: AutoField(**options)
|
||||
|
||||
An :class:`IntegerField` that automatically increments
|
||||
according to available IDs. You usually won't need to use this directly; a
|
||||
primary key field will automatically be added to your model if you don't specify
|
||||
otherwise. See :ref:`automatic-primary-key-fields`.
|
||||
An :class:`IntegerField` that automatically increments according to available
|
||||
IDs. You usually won't need to use this directly; a primary key field will
|
||||
automatically be added to your model if you don't specify otherwise. See
|
||||
:ref:`automatic-primary-key-fields`.
|
||||
|
||||
``BigAutoField``
|
||||
----------------
|
||||
@@ -815,8 +815,8 @@ The default form widget for this field is a
|
||||
and a shortcut for "Today". Includes an additional ``invalid_date`` error
|
||||
message key.
|
||||
|
||||
The options ``auto_now_add``, ``auto_now``, and ``default`` are mutually exclusive.
|
||||
Any combination of these options will result in an error.
|
||||
The options ``auto_now_add``, ``auto_now``, and ``default`` are mutually
|
||||
exclusive. Any combination of these options will result in an error.
|
||||
|
||||
.. note::
|
||||
As currently implemented, setting ``auto_now`` or ``auto_now_add`` to
|
||||
@@ -944,8 +944,8 @@ Has the following optional arguments:
|
||||
|
||||
.. attribute:: FileField.upload_to
|
||||
|
||||
This attribute provides a way of setting the upload directory and file name,
|
||||
and can be set in two ways. In both cases, the value is passed to the
|
||||
This attribute provides a way of setting the upload directory and file
|
||||
name, and can be set in two ways. In both cases, the value is passed to the
|
||||
:meth:`Storage.save() <django.core.files.storage.Storage.save>` method.
|
||||
|
||||
If you specify a string value or a :class:`~pathlib.Path`, it may contain
|
||||
@@ -968,9 +968,9 @@ Has the following optional arguments:
|
||||
handles ``upload_to``.
|
||||
|
||||
``upload_to`` may also be a callable, such as a function. This will be
|
||||
called to obtain the upload path, including the filename. This callable must
|
||||
accept two arguments and return a Unix-style path (with forward slashes)
|
||||
to be passed along to the storage system. The two arguments are:
|
||||
called to obtain the upload path, including the filename. This callable
|
||||
must accept two arguments and return a Unix-style path (with forward
|
||||
slashes) to be passed along to the storage system. The two arguments are:
|
||||
|
||||
====================== ===============================================
|
||||
Argument Description
|
||||
@@ -1030,11 +1030,11 @@ takes a few steps:
|
||||
``{{ object.mug_shot.url }}``.
|
||||
|
||||
For example, say your :setting:`MEDIA_ROOT` is set to ``'/home/media'``, and
|
||||
:attr:`~FileField.upload_to` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'``
|
||||
part of :attr:`~FileField.upload_to` is :func:`~time.strftime` formatting;
|
||||
``'%Y'`` is the four-digit year, ``'%m'`` is the two-digit month and ``'%d'`` is
|
||||
the two-digit day. If you upload a file on Jan. 15, 2007, it will be saved in
|
||||
the directory ``/home/media/photos/2007/01/15``.
|
||||
:attr:`~FileField.upload_to` is set to ``'photos/%Y/%m/%d'``. The
|
||||
``'%Y/%m/%d'`` part of :attr:`~FileField.upload_to` is :func:`~time.strftime`
|
||||
formatting; ``'%Y'`` is the four-digit year, ``'%m'`` is the two-digit month
|
||||
and ``'%d'`` is the two-digit day. If you upload a file on Jan. 15, 2007, it
|
||||
will be saved in the directory ``/home/media/photos/2007/01/15``.
|
||||
|
||||
If you wanted to retrieve the uploaded file's on-disk filename, or the file's
|
||||
size, you could use the :attr:`~django.core.files.File.name` and
|
||||
@@ -1044,9 +1044,9 @@ information on the available attributes and methods, see the
|
||||
topic guide.
|
||||
|
||||
.. note::
|
||||
The file is saved as part of saving the model in the database, so the actual
|
||||
file name used on disk cannot be relied on until after the model has been
|
||||
saved.
|
||||
The file is saved as part of saving the model in the database, so the
|
||||
actual file name used on disk cannot be relied on until after the model has
|
||||
been saved.
|
||||
|
||||
The uploaded file's relative URL can be obtained using the
|
||||
:attr:`~django.db.models.fields.files.FieldFile.url` attribute. Internally,
|
||||
@@ -1085,9 +1085,10 @@ file.
|
||||
The API of :class:`FieldFile` mirrors that of :class:`~django.core.files.File`,
|
||||
with one key difference: *The object wrapped by the class is not necessarily a
|
||||
wrapper around Python's built-in file object.* Instead, it is a wrapper around
|
||||
the result of the :attr:`Storage.open()<django.core.files.storage.Storage.open>`
|
||||
method, which may be a :class:`~django.core.files.File` object, or it may be a
|
||||
custom storage's implementation of the :class:`~django.core.files.File` API.
|
||||
the result of the
|
||||
:attr:`Storage.open()<django.core.files.storage.Storage.open>` method, which
|
||||
may be a :class:`~django.core.files.File` object, or it may be a custom
|
||||
storage's implementation of the :class:`~django.core.files.File` API.
|
||||
|
||||
In addition to the API inherited from :class:`~django.core.files.File` such as
|
||||
``read()`` and ``write()``, :class:`FieldFile` includes several methods that
|
||||
@@ -1226,7 +1227,8 @@ directory on the filesystem. Has some special arguments, of which the first is
|
||||
.. attribute:: FilePathField.recursive
|
||||
|
||||
Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
|
||||
whether all subdirectories of :attr:`~FilePathField.path` should be included
|
||||
whether all subdirectories of :attr:`~FilePathField.path` should be
|
||||
included
|
||||
|
||||
.. attribute:: FilePathField.allow_files
|
||||
|
||||
@@ -1269,11 +1271,11 @@ when :attr:`~django.forms.Field.localize` is ``False`` or
|
||||
.. admonition:: ``FloatField`` vs. ``DecimalField``
|
||||
|
||||
The :class:`FloatField` class is sometimes mixed up with the
|
||||
:class:`DecimalField` class. Although they both represent real numbers, they
|
||||
represent those numbers differently. ``FloatField`` uses Python's ``float``
|
||||
type internally, while ``DecimalField`` uses Python's ``Decimal`` type. For
|
||||
information on the difference between the two, see Python's documentation
|
||||
for the :mod:`decimal` module.
|
||||
:class:`DecimalField` class. Although they both represent real numbers,
|
||||
they represent those numbers differently. ``FloatField`` uses Python's
|
||||
``float`` type internally, while ``DecimalField`` uses Python's ``Decimal``
|
||||
type. For information on the difference between the two, see Python's
|
||||
documentation for the :mod:`decimal` module.
|
||||
|
||||
``GeneratedField``
|
||||
------------------
|
||||
@@ -1375,8 +1377,9 @@ values are stored as null.
|
||||
Inherits all attributes and methods from :class:`FileField`, but also
|
||||
validates that the uploaded object is a valid image.
|
||||
|
||||
In addition to the special attributes that are available for :class:`FileField`,
|
||||
an :class:`ImageField` also has ``height`` and ``width`` attributes.
|
||||
In addition to the special attributes that are available for
|
||||
:class:`FileField`, an :class:`ImageField` also has ``height`` and ``width``
|
||||
attributes.
|
||||
|
||||
To facilitate querying on those attributes, :class:`ImageField` has the
|
||||
following optional arguments:
|
||||
@@ -1517,8 +1520,8 @@ all databases supported by Django.
|
||||
.. class:: SlugField(max_length=50, **options)
|
||||
|
||||
:term:`Slug <slug>` is a newspaper term. A slug is a short label for something,
|
||||
containing only letters, numbers, underscores or hyphens. They're generally used
|
||||
in URLs.
|
||||
containing only letters, numbers, underscores or hyphens. They're generally
|
||||
used in URLs.
|
||||
|
||||
Like a CharField, you can specify :attr:`~CharField.max_length` (read the note
|
||||
about database portability and :attr:`~CharField.max_length` in that section,
|
||||
@@ -2014,9 +2017,9 @@ that control how the relationship functions.
|
||||
:class:`ManyToManyField` is assumed to be symmetrical -- that is, if I am
|
||||
your friend, then you are my friend.
|
||||
|
||||
If you do not want symmetry in many-to-many relationships with ``self``, set
|
||||
:attr:`~ManyToManyField.symmetrical` to ``False``. This will force Django to
|
||||
add the descriptor for the reverse relationship, allowing
|
||||
If you do not want symmetry in many-to-many relationships with ``self``,
|
||||
set :attr:`~ManyToManyField.symmetrical` to ``False``. This will force
|
||||
Django to add the descriptor for the reverse relationship, allowing
|
||||
:class:`ManyToManyField` relationships to be non-symmetrical.
|
||||
|
||||
.. attribute:: ManyToManyField.through
|
||||
@@ -2183,12 +2186,12 @@ that control how the relationship functions.
|
||||
|
||||
.. attribute:: ManyToManyField.swappable
|
||||
|
||||
Controls the migration framework's reaction if this :class:`ManyToManyField`
|
||||
is pointing at a swappable model. If it is ``True`` - the default -
|
||||
then if the :class:`ManyToManyField` is pointing at a model which matches
|
||||
the current value of ``settings.AUTH_USER_MODEL`` (or another swappable
|
||||
model setting) the relationship will be stored in the migration using
|
||||
a reference to the setting, not to the model directly.
|
||||
Controls the migration framework's reaction if this
|
||||
:class:`ManyToManyField` is pointing at a swappable model. If it is
|
||||
``True`` - the default - then if the :class:`ManyToManyField` is pointing
|
||||
at a model which matches the current value of ``settings.AUTH_USER_MODEL``
|
||||
(or another swappable model setting) the relationship will be stored in the
|
||||
migration using a reference to the setting, not to the model directly.
|
||||
|
||||
You only want to override this to be ``False`` if you are sure your
|
||||
model should always point toward the swapped-in model - for example,
|
||||
@@ -2476,7 +2479,8 @@ Field API reference
|
||||
value)
|
||||
* when it saves to the database (Python value -> database backend value)
|
||||
|
||||
When querying, :meth:`get_db_prep_value` and :meth:`get_prep_value` are used:
|
||||
When querying, :meth:`get_db_prep_value` and :meth:`get_prep_value` are
|
||||
used:
|
||||
|
||||
.. method:: get_prep_value(value)
|
||||
|
||||
@@ -2572,8 +2576,8 @@ Field API reference
|
||||
Returns the default :class:`django.forms.Field` of this field for
|
||||
:class:`~django.forms.ModelForm`.
|
||||
|
||||
If :meth:`~Field.formfield` is overridden to return ``None``, this field
|
||||
is excluded from the :class:`~django.forms.ModelForm`.
|
||||
If :meth:`~Field.formfield` is overridden to return ``None``, this
|
||||
field is excluded from the :class:`~django.forms.ModelForm`.
|
||||
|
||||
By default, if both ``form_class`` and ``choices_form_class`` are
|
||||
``None``, it uses :class:`~django.forms.CharField`. If the field has
|
||||
@@ -2587,8 +2591,9 @@ Field API reference
|
||||
Returns a 4-tuple with enough information to recreate the field:
|
||||
|
||||
1. The name of the field on the model.
|
||||
2. The import path of the field (e.g. ``"django.db.models.IntegerField"``).
|
||||
This should be the most portable version, so less specific may be better.
|
||||
2. The import path of the field (e.g.
|
||||
``"django.db.models.IntegerField"``). This should be the most
|
||||
portable version, so less specific may be better.
|
||||
3. A list of positional arguments.
|
||||
4. A dict of keyword arguments.
|
||||
|
||||
@@ -2598,9 +2603,10 @@ Field API reference
|
||||
Registering and fetching lookups
|
||||
================================
|
||||
|
||||
``Field`` implements the :ref:`lookup registration API <lookup-registration-api>`.
|
||||
The API can be used to customize which lookups are available for a field class
|
||||
and its instances, and how lookups are fetched from a field.
|
||||
``Field`` implements the :ref:`lookup registration API
|
||||
<lookup-registration-api>`. The API can be used to customize which lookups are
|
||||
available for a field class and its instances, and how lookups are fetched from
|
||||
a field.
|
||||
|
||||
.. _model-field-attributes:
|
||||
|
||||
|
||||
@@ -87,7 +87,8 @@ fields are present, then ``values`` are guaranteed to be in the order
|
||||
to each of the missing fields.
|
||||
|
||||
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.
|
||||
``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::
|
||||
@@ -485,11 +486,11 @@ rather than relying on the auto-assignment of the ID:
|
||||
|
||||
If you assign auto-primary-key values manually, make sure not to use an
|
||||
already-existing primary-key value! If you create a new object with an explicit
|
||||
primary-key value that already exists in the database, Django will assume you're
|
||||
changing the existing record rather than creating a new one.
|
||||
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::
|
||||
Given the above ``'Cheddar Talk'`` blog example, this example would override
|
||||
the previous record in the database::
|
||||
|
||||
b4 = Blog(id=3, name="Not Cheddar", tagline="Anything but cheese.")
|
||||
b4.save() # Overrides the previous blog with ID=3!
|
||||
@@ -563,17 +564,18 @@ exists in the database. Otherwise, Django executes an ``INSERT``.
|
||||
|
||||
The one gotcha here is that you should be careful not to specify a primary-key
|
||||
value explicitly when saving new objects, if you cannot guarantee the
|
||||
primary-key value is unused. For more on this nuance, see `Explicitly specifying
|
||||
auto-primary-key values`_ above and `Forcing an INSERT or UPDATE`_ below.
|
||||
primary-key value is unused. For more on this nuance, see `Explicitly
|
||||
specifying auto-primary-key values`_ above and `Forcing an INSERT or UPDATE`_
|
||||
below.
|
||||
|
||||
In Django 1.5 and earlier, Django did a ``SELECT`` when the primary key
|
||||
attribute was set. If the ``SELECT`` found a row, then Django did an ``UPDATE``,
|
||||
otherwise it did an ``INSERT``. The old algorithm results in one more query in
|
||||
the ``UPDATE`` case. There are some rare cases where the database doesn't
|
||||
report that a row was updated even if the database contains a row for the
|
||||
object's primary key value. An example is the PostgreSQL ``ON UPDATE`` trigger
|
||||
which returns ``NULL``. In such cases it is possible to revert to the old
|
||||
algorithm by setting the :attr:`~django.db.models.Options.select_on_save`
|
||||
attribute was set. If the ``SELECT`` found a row, then Django did an
|
||||
``UPDATE``, otherwise it did an ``INSERT``. The old algorithm results in one
|
||||
more query in the ``UPDATE`` case. There are some rare cases where the database
|
||||
doesn't report that a row was updated even if the database contains a row for
|
||||
the object's primary key value. An example is the PostgreSQL ``ON UPDATE``
|
||||
trigger which returns ``NULL``. In such cases it is possible to revert to the
|
||||
old algorithm by setting the :attr:`~django.db.models.Options.select_on_save`
|
||||
option to ``True``.
|
||||
|
||||
.. _ref-models-force-insert:
|
||||
|
||||
@@ -12,19 +12,22 @@ the ``WHERE`` clause of a database query. To learn how to *use* lookups, see
|
||||
:doc:`/topics/db/queries`; to learn how to *create* new lookups, see
|
||||
:doc:`/howto/custom-lookups`.
|
||||
|
||||
The lookup API has two components: a :class:`~lookups.RegisterLookupMixin` class
|
||||
that registers lookups, and the :ref:`Query Expression API <query-expression>`, a
|
||||
set of methods that a class has to implement to be registrable as a lookup.
|
||||
The lookup API has two components: a :class:`~lookups.RegisterLookupMixin`
|
||||
class that registers lookups, and the :ref:`Query Expression API
|
||||
<query-expression>`, a set of methods that a class has to implement to be
|
||||
registrable as a lookup.
|
||||
|
||||
Django has two base classes that follow the query expression API and from where
|
||||
all Django builtin lookups are derived:
|
||||
|
||||
* :class:`Lookup`: to lookup a field (e.g. the ``exact`` of ``field_name__exact``)
|
||||
* :class:`Lookup`: to lookup a field (e.g. the ``exact`` of
|
||||
``field_name__exact``)
|
||||
* :class:`Transform`: to transform a field
|
||||
|
||||
A lookup expression consists of three parts:
|
||||
|
||||
* Fields part (e.g. ``Book.objects.filter(author__best_friends__first_name...``);
|
||||
* Fields part (e.g.
|
||||
``Book.objects.filter(author__best_friends__first_name...``);
|
||||
* Transforms part (may be omitted) (e.g. ``__lower__first3chars__reversed``);
|
||||
* A lookup (e.g. ``__icontains``) that, if omitted, defaults to ``__exact``.
|
||||
|
||||
@@ -33,8 +36,8 @@ A lookup expression consists of three parts:
|
||||
Registration API
|
||||
================
|
||||
|
||||
Django uses :class:`~lookups.RegisterLookupMixin` to give a class the interface to
|
||||
register lookups on itself or its instances. The two prominent examples are
|
||||
Django uses :class:`~lookups.RegisterLookupMixin` to give a class the interface
|
||||
to register lookups on itself or its instances. The two prominent examples are
|
||||
:class:`~django.db.models.Field`, the base class of all model fields, and
|
||||
:class:`Transform`, the base class of all Django transforms.
|
||||
|
||||
@@ -88,10 +91,10 @@ The Query Expression API
|
||||
========================
|
||||
|
||||
The query expression API is a common set of methods that classes define to be
|
||||
usable in query expressions to translate themselves into SQL expressions. Direct
|
||||
field references, aggregates, and ``Transform`` are examples that follow this
|
||||
API. A class is said to follow the query expression API when it implements the
|
||||
following methods:
|
||||
usable in query expressions to translate themselves into SQL expressions.
|
||||
Direct field references, aggregates, and ``Transform`` are examples that follow
|
||||
this API. A class is said to follow the query expression API when it implements
|
||||
the following methods:
|
||||
|
||||
.. method:: as_sql(compiler, connection)
|
||||
|
||||
@@ -146,18 +149,20 @@ following methods:
|
||||
The notation to use a ``Transform`` in a lookup expression is
|
||||
``<expression>__<transformation>`` (e.g. ``date__year``).
|
||||
|
||||
This class follows the :ref:`Query Expression API <query-expression>`, which
|
||||
implies that you can use ``<expression>__<transform1>__<transform2>``. It's
|
||||
a specialized :ref:`Func() expression <func-expressions>` that only accepts
|
||||
one argument. It can also be used on the right hand side of a filter or
|
||||
directly as an annotation.
|
||||
This class follows the :ref:`Query Expression API <query-expression>`,
|
||||
which implies that you can use
|
||||
``<expression>__<transform1>__<transform2>``. It's a specialized
|
||||
:ref:`Func() expression <func-expressions>` that only accepts one argument.
|
||||
It can also be used on the right hand side of a filter or directly as an
|
||||
annotation.
|
||||
|
||||
.. attribute:: bilateral
|
||||
|
||||
A boolean indicating whether this transformation should apply to both
|
||||
``lhs`` and ``rhs``. Bilateral transformations will be applied to ``rhs`` in
|
||||
the same order as they appear in the lookup expression. By default it is set
|
||||
to ``False``. For example usage, see :doc:`/howto/custom-lookups`.
|
||||
``lhs`` and ``rhs``. Bilateral transformations will be applied to
|
||||
``rhs`` in the same order as they appear in the lookup expression. By
|
||||
default it is set to ``False``. For example usage, see
|
||||
:doc:`/howto/custom-lookups`.
|
||||
|
||||
.. attribute:: lhs
|
||||
|
||||
|
||||
@@ -31,12 +31,12 @@ Retrieving a single field instance of a model by name
|
||||
|
||||
Returns the field instance given a name of a field.
|
||||
|
||||
``field_name`` can be the name of a field on the model, a field
|
||||
on an abstract or inherited model, or a field defined on another
|
||||
model that points to the model. In the latter case, the ``field_name``
|
||||
will be (in order of preference) the :attr:`~.ForeignKey.related_query_name`
|
||||
set by the user, the :attr:`~.ForeignKey.related_name` set by the user, or
|
||||
the name automatically generated by Django.
|
||||
``field_name`` can be the name of a field on the model, a field on an
|
||||
abstract or inherited model, or a field defined on another model that
|
||||
points to the model. In the latter case, the ``field_name`` will be (in
|
||||
order of preference) the :attr:`~.ForeignKey.related_query_name` set by the
|
||||
user, the :attr:`~.ForeignKey.related_name` set by the user, or the name
|
||||
automatically generated by Django.
|
||||
|
||||
:attr:`Hidden fields <django.db.models.Field.hidden>` cannot be retrieved
|
||||
by name.
|
||||
@@ -129,9 +129,9 @@ Retrieving fields composing the primary key of a model
|
||||
|
||||
Returns a list of the fields composing the primary key of a model.
|
||||
|
||||
When a :class:`composite primary key <django.db.models.CompositePrimaryKey>`
|
||||
is defined on a model it will contain all the
|
||||
:class:`fields <django.db.models.Field>` referenced by it.
|
||||
When a :class:`composite primary key
|
||||
<django.db.models.CompositePrimaryKey>` is defined on a model it will
|
||||
contain all the :class:`fields <django.db.models.Field>` referenced by it.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
|
||||
@@ -68,9 +68,9 @@ a database table named ``bookstore_book``.
|
||||
To override the database table name, use the ``db_table`` parameter in
|
||||
``class Meta``.
|
||||
|
||||
If your database table name is an SQL reserved word, or contains characters that
|
||||
aren't allowed in Python variable names -- notably, the hyphen -- that's OK.
|
||||
Django quotes column and table names behind the scenes.
|
||||
If your database table name is an SQL reserved word, or contains characters
|
||||
that aren't allowed in Python variable names -- notably, the hyphen -- that's
|
||||
OK. Django quotes column and table names behind the scenes.
|
||||
|
||||
.. admonition:: Use lowercase table names for MariaDB and MySQL
|
||||
|
||||
@@ -130,8 +130,8 @@ not be looking at your Django code. For example::
|
||||
|
||||
.. attribute:: Options.default_related_name
|
||||
|
||||
The name that will be used by default for the relation from a related object
|
||||
back to this one. The default is ``<model_name>_set``.
|
||||
The name that will be used by default for the relation from a related
|
||||
object back to this one. The default is ``<model_name>_set``.
|
||||
|
||||
This option also sets :attr:`~ForeignKey.related_query_name`.
|
||||
|
||||
@@ -199,9 +199,10 @@ not be looking at your Django code. For example::
|
||||
For tests involving models with ``managed=False``, it's up to you to ensure
|
||||
the correct tables are created as part of the test setup.
|
||||
|
||||
If you're interested in changing the Python-level behavior of a model class,
|
||||
you *could* use ``managed=False`` and create a copy of an existing model.
|
||||
However, there's a better approach for that situation: :ref:`proxy-models`.
|
||||
If you're interested in changing the Python-level behavior of a model
|
||||
class, you *could* use ``managed=False`` and create a copy of an existing
|
||||
model. However, there's a better approach for that situation:
|
||||
:ref:`proxy-models`.
|
||||
|
||||
``order_with_respect_to``
|
||||
-------------------------
|
||||
@@ -229,12 +230,12 @@ not be looking at your Django code. For example::
|
||||
class Meta:
|
||||
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:
|
||||
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:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
@@ -242,16 +243,16 @@ not be looking at your Django code. For example::
|
||||
>>> 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:
|
||||
The order of a ``Question`` object's related ``Answer`` objects can be set
|
||||
by 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``:
|
||||
``get_previous_in_order()``, which can be used to access those objects in
|
||||
their proper order. Assuming the ``Answer`` objects are ordered by ``id``:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
@@ -281,7 +282,8 @@ not be looking at your Django code. For example::
|
||||
|
||||
.. 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::
|
||||
|
||||
ordering = ["-order_date"]
|
||||
|
||||
@@ -298,7 +300,8 @@ not be looking at your Django code. For example::
|
||||
|
||||
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::
|
||||
|
||||
ordering = ["-pub_date", "author"]
|
||||
|
||||
@@ -326,9 +329,10 @@ not be looking at your Django code. For example::
|
||||
|
||||
.. attribute:: Options.permissions
|
||||
|
||||
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``::
|
||||
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``::
|
||||
|
||||
permissions = [("can_deliver_pizzas", "Can deliver pizzas")]
|
||||
|
||||
@@ -351,8 +355,8 @@ not be looking at your Django code. For example::
|
||||
|
||||
.. attribute:: Options.proxy
|
||||
|
||||
If ``proxy = True``, a model which subclasses another model will be treated as
|
||||
a :ref:`proxy model <proxy-models>`.
|
||||
If ``proxy = True``, a model which subclasses another model will be treated
|
||||
as a :ref:`proxy model <proxy-models>`.
|
||||
|
||||
``required_db_features``
|
||||
------------------------
|
||||
@@ -373,8 +377,8 @@ not be looking at your Django code. For example::
|
||||
|
||||
Name of a supported database vendor that this model is specific to. Current
|
||||
built-in vendor names are: ``sqlite``, ``postgresql``, ``mysql``,
|
||||
``oracle``. If this attribute is not empty and the current connection vendor
|
||||
doesn't match it, the model will not be synchronized.
|
||||
``oracle``. If this attribute is not empty and the current connection
|
||||
vendor doesn't match it, the model will not be synchronized.
|
||||
|
||||
``select_on_save``
|
||||
------------------
|
||||
@@ -433,8 +437,8 @@ not be looking at your Django code. For example::
|
||||
unique_together = [["driver", "restaurant"]]
|
||||
|
||||
This is a list of lists that must be unique when considered together.
|
||||
It's used in the Django admin and is enforced at the database level (i.e., the
|
||||
appropriate ``UNIQUE`` statements are included in the ``CREATE TABLE``
|
||||
It's used in the Django admin and is enforced at the database level (i.e.,
|
||||
the appropriate ``UNIQUE`` statements are included in the ``CREATE TABLE``
|
||||
statement).
|
||||
|
||||
For convenience, ``unique_together`` can be a single list when dealing with
|
||||
@@ -491,7 +495,8 @@ not be looking at your Django code. For example::
|
||||
|
||||
verbose_name_plural = "stories"
|
||||
|
||||
If this isn't given, Django will use :attr:`~Options.verbose_name` + ``"s"``.
|
||||
If this isn't given, Django will use :attr:`~Options.verbose_name` +
|
||||
``"s"``.
|
||||
|
||||
Read-only ``Meta`` attributes
|
||||
=============================
|
||||
|
||||
@@ -85,20 +85,21 @@ You can evaluate a ``QuerySet`` in the following ways:
|
||||
print("There is at least one Entry with the headline Test")
|
||||
|
||||
Note: If you only want to determine if at least one result exists (and don't
|
||||
need the actual objects), it's more efficient to use :meth:`~QuerySet.exists`.
|
||||
need the actual objects), it's more efficient to use
|
||||
:meth:`~QuerySet.exists`.
|
||||
|
||||
.. _pickling QuerySets:
|
||||
|
||||
Pickling ``QuerySet``\s
|
||||
-----------------------
|
||||
|
||||
If you :mod:`pickle` a ``QuerySet``, this will force all the results to be loaded
|
||||
into memory prior to pickling. Pickling is usually used as a precursor to
|
||||
caching and when the cached queryset is reloaded, you want the results to
|
||||
If you :mod:`pickle` a ``QuerySet``, this will force all the results to be
|
||||
loaded into memory prior to pickling. Pickling is usually used as a precursor
|
||||
to caching and when the cached queryset is reloaded, you want the results to
|
||||
already be present and ready for use (reading from the database can take some
|
||||
time, defeating the purpose of caching). This means that when you unpickle a
|
||||
``QuerySet``, it contains the results at the moment it was pickled, rather
|
||||
than the results that are currently in the database.
|
||||
``QuerySet``, it contains the results at the moment it was pickled, rather than
|
||||
the results that are currently in the database.
|
||||
|
||||
If you only want to pickle the necessary information to recreate the
|
||||
``QuerySet`` from the database at a later time, pickle the ``query`` attribute
|
||||
@@ -207,8 +208,8 @@ The lookup parameters (``**kwargs``) should be in the format described in
|
||||
`Field lookups`_ below. Multiple parameters are joined via ``AND`` in the
|
||||
underlying SQL statement.
|
||||
|
||||
If you need to execute more complex queries (for example, queries with ``OR`` statements),
|
||||
you can use :class:`Q objects <django.db.models.Q>` (``*args``).
|
||||
If you need to execute more complex queries (for example, queries with ``OR``
|
||||
statements), you can use :class:`Q objects <django.db.models.Q>` (``*args``).
|
||||
|
||||
``exclude()``
|
||||
~~~~~~~~~~~~~
|
||||
@@ -249,8 +250,8 @@ In SQL terms, that evaluates to:
|
||||
|
||||
Note the second example is more restrictive.
|
||||
|
||||
If you need to execute more complex queries (for example, queries with ``OR`` statements),
|
||||
you can use :class:`Q objects <django.db.models.Q>` (``*args``).
|
||||
If you need to execute more complex queries (for example, queries with ``OR``
|
||||
statements), you can use :class:`Q objects <django.db.models.Q>` (``*args``).
|
||||
|
||||
``annotate()``
|
||||
~~~~~~~~~~~~~~
|
||||
@@ -536,8 +537,8 @@ field names, the database will only compare the specified field names.
|
||||
|
||||
.. note::
|
||||
When you specify field names, you *must* provide an ``order_by()`` in the
|
||||
``QuerySet``, and the fields in ``order_by()`` must start with the fields in
|
||||
``distinct()``, in the same order.
|
||||
``QuerySet``, and the fields in ``order_by()`` must start with the fields
|
||||
in ``distinct()``, in the same order.
|
||||
|
||||
For example, ``SELECT DISTINCT ON (a)`` gives you the first row for each
|
||||
value in column ``a``. If you don't specify an order, you'll get some
|
||||
@@ -1102,7 +1103,7 @@ following models::
|
||||
# ...
|
||||
author = models.ForeignKey(Person, on_delete=models.CASCADE)
|
||||
|
||||
... then a call to ``Book.objects.select_related('author__hometown').get(id=4)``
|
||||
Then a call to ``Book.objects.select_related('author__hometown').get(id=4)``
|
||||
will cache the related ``Person`` *and* the related ``City``::
|
||||
|
||||
# Hits the database with joins to the author and hometown tables.
|
||||
@@ -1124,7 +1125,8 @@ You can also refer to the reverse direction of a
|
||||
``select_related`` — that is, you can traverse a
|
||||
:class:`~django.db.models.OneToOneField` back to the object on which the field
|
||||
is defined. Instead of specifying the field name, use the :attr:`related_name
|
||||
<django.db.models.ForeignKey.related_name>` for the field on the related object.
|
||||
<django.db.models.ForeignKey.related_name>` for the field on the related
|
||||
object.
|
||||
|
||||
There may be some situations where you wish to call ``select_related()`` with a
|
||||
lot of related objects, or where you don't know all of the relations. In these
|
||||
@@ -1153,15 +1155,15 @@ Returns a ``QuerySet`` that will automatically retrieve, in a single batch,
|
||||
related objects for each of the specified lookups.
|
||||
|
||||
This has a similar purpose to ``select_related``, in that both are designed to
|
||||
stop the deluge of database queries that is caused by accessing related objects,
|
||||
but the strategy is quite different.
|
||||
stop the deluge of database queries that is caused by accessing related
|
||||
objects, but the strategy is quite different.
|
||||
|
||||
``select_related`` works by creating an SQL join and including the fields of the
|
||||
related object in the ``SELECT`` statement. For this reason, ``select_related``
|
||||
gets the related objects in the same database query. However, to avoid the much
|
||||
larger result set that would result from joining across a 'many' relationship,
|
||||
``select_related`` is limited to single-valued relationships - foreign key and
|
||||
one-to-one.
|
||||
``select_related`` works by creating an SQL join and including the fields of
|
||||
the related object in the ``SELECT`` statement. For this reason,
|
||||
``select_related`` gets the related objects in the same database query.
|
||||
However, to avoid the much larger result set that would result from joining
|
||||
across a 'many' relationship, ``select_related`` is limited to single-valued
|
||||
relationships - foreign key and one-to-one.
|
||||
|
||||
``prefetch_related``, on the other hand, does a separate lookup for each
|
||||
relationship, and does the 'joining' in Python. This allows it to prefetch
|
||||
@@ -1240,8 +1242,8 @@ If you have an iterable of model instances, you can prefetch related attributes
|
||||
on those instances using the :func:`~django.db.models.prefetch_related_objects`
|
||||
function.
|
||||
|
||||
Note that the result cache of the primary ``QuerySet`` and all specified related
|
||||
objects will then be fully loaded into memory. This changes the typical
|
||||
Note that the result cache of the primary ``QuerySet`` and all specified
|
||||
related objects will then be fully loaded into memory. This changes the typical
|
||||
behavior of a ``QuerySet``, which normally tries to avoid loading all objects
|
||||
into memory before they are needed, even after a query has been executed in the
|
||||
database.
|
||||
@@ -1329,16 +1331,16 @@ save both memory and CPU time.
|
||||
|
||||
While ``prefetch_related`` supports prefetching ``GenericForeignKey``
|
||||
relationships, the number of queries will depend on the data. Since a
|
||||
``GenericForeignKey`` can reference data in multiple tables, one query per table
|
||||
referenced is needed, rather than one query for all the items. There could be
|
||||
additional queries on the ``ContentType`` table if the relevant rows have not
|
||||
already been fetched.
|
||||
``GenericForeignKey`` can reference data in multiple tables, one query per
|
||||
table referenced is needed, rather than one query for all the items. There
|
||||
could be additional queries on the ``ContentType`` table if the relevant rows
|
||||
have not already been fetched.
|
||||
|
||||
``prefetch_related`` in most cases will be implemented using an SQL query that
|
||||
uses the 'IN' operator. This means that for a large ``QuerySet`` a large 'IN' clause
|
||||
could be generated, which, depending on the database, might have performance
|
||||
problems of its own when it comes to parsing or executing the SQL query. Always
|
||||
profile for your use case!
|
||||
uses the 'IN' operator. This means that for a large ``QuerySet`` a large 'IN'
|
||||
clause could be generated, which, depending on the database, might have
|
||||
performance problems of its own when it comes to parsing or executing the SQL
|
||||
query. Always profile for your use case!
|
||||
|
||||
If you use ``iterator()`` to run the query, ``prefetch_related()`` calls will
|
||||
only be observed if a value for ``chunk_size`` is provided.
|
||||
@@ -1372,8 +1374,8 @@ applicable to reduce the number of queries even further:
|
||||
... 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.
|
||||
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.
|
||||
|
||||
This allows prefetching the same relation multiple times with a different
|
||||
``QuerySet``; for instance:
|
||||
@@ -1386,8 +1388,8 @@ This allows prefetching the same relation multiple times with a different
|
||||
... Prefetch("pizzas", queryset=vegetarian_pizzas, to_attr="vegetarian_menu"),
|
||||
... )
|
||||
|
||||
Lookups created with custom ``to_attr`` can still be traversed as usual by other
|
||||
lookups:
|
||||
Lookups created with custom ``to_attr`` can still be traversed as usual by
|
||||
other lookups:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
@@ -1397,8 +1399,9 @@ lookups:
|
||||
... "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:
|
||||
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
|
||||
|
||||
@@ -1486,8 +1489,8 @@ database selected by the outer query. All of the following are valid:
|
||||
|
||||
>>> 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.
|
||||
This will trigger an ``AttributeError`` because ``'pizza_list'`` doesn't
|
||||
exist yet when ``'pizza_list__toppings'`` is being processed.
|
||||
|
||||
This consideration is not limited to the use of ``Prefetch`` objects. Some
|
||||
advanced techniques may require that the lookups be performed in a
|
||||
@@ -1510,7 +1513,7 @@ generated by a ``QuerySet``.
|
||||
Use it only if you cannot express your query using other queryset methods.
|
||||
If you do need to use it, please `file a ticket
|
||||
<https://code.djangoproject.com/newticket>`_ using the `QuerySet.extra
|
||||
keyword <https://code.djangoproject.com/query?status=assigned&status=new&keywords=~QuerySet.extra>`_
|
||||
keyword <https://code.djangoproject.com/query?keywords=~QuerySet.extra>`_
|
||||
with your use case (please check the list of existing tickets first) so
|
||||
that we can enhance the QuerySet API to allow removing ``extra()``. We are
|
||||
no longer improving or fixing bugs for this method.
|
||||
@@ -1707,13 +1710,13 @@ of the arguments is required, but you should use at least one of them.
|
||||
|
||||
.. warning::
|
||||
|
||||
If you are performing queries on MySQL, note that MySQL's silent type coercion
|
||||
may cause unexpected results when mixing types. If you query on a string
|
||||
type column, but with an integer value, MySQL will coerce the types of all values
|
||||
in the table to an integer before performing the comparison. For example, if your
|
||||
table contains the values ``'abc'``, ``'def'`` and you query for ``WHERE mycolumn=0``,
|
||||
both rows will match. To prevent this, perform the correct typecasting
|
||||
before using the value in a query.
|
||||
If you are performing queries on MySQL, note that MySQL's silent type
|
||||
coercion may cause unexpected results when mixing types. If you query on a
|
||||
string type column, but with an integer value, MySQL will coerce the types
|
||||
of all values in the table to an integer before performing the comparison.
|
||||
For example, if your table contains the values ``'abc'``, ``'def'`` and you
|
||||
query for ``WHERE mycolumn=0``, both rows will match. To prevent this,
|
||||
perform the correct typecasting before using the value in a query.
|
||||
|
||||
``defer()``
|
||||
~~~~~~~~~~~
|
||||
@@ -1946,8 +1949,8 @@ By default, ``select_for_update()`` locks all rows that are selected by the
|
||||
query. For example, rows of related objects specified in :meth:`select_related`
|
||||
are locked in addition to rows of the queryset's model. If this isn't desired,
|
||||
specify the related objects you want to lock in ``select_for_update(of=(...))``
|
||||
using the same fields syntax as :meth:`select_related`. Use the value ``'self'``
|
||||
to refer to the queryset's model.
|
||||
using the same fields syntax as :meth:`select_related`. Use the value
|
||||
``'self'`` to refer to the queryset's model.
|
||||
|
||||
.. admonition:: Lock parents models in ``select_for_update(of=(...))``
|
||||
|
||||
@@ -2191,7 +2194,8 @@ 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::
|
||||
|
||||
p = Person.objects.create(first_name="Bruce", last_name="Springsteen")
|
||||
|
||||
@@ -2252,9 +2256,9 @@ found, ``get_or_create()`` returns a tuple of that object and ``False``.
|
||||
|
||||
This method is atomic assuming that the database enforces uniqueness of the
|
||||
keyword arguments (see :attr:`~django.db.models.Field.unique` or
|
||||
:attr:`~django.db.models.Options.unique_together`). If the fields used in the
|
||||
keyword arguments do not have a uniqueness constraint, concurrent calls to
|
||||
this method may result in multiple rows with the same parameters being
|
||||
:attr:`~django.db.models.Options.unique_together`). If the fields used in
|
||||
the keyword arguments do not have a uniqueness constraint, concurrent calls
|
||||
to this method may result in multiple rows with the same parameters being
|
||||
inserted.
|
||||
|
||||
You can specify more complex conditions for the retrieved object by chaining
|
||||
@@ -2306,10 +2310,11 @@ whenever a request to a page has a side effect on your data. For more, see
|
||||
|
||||
.. warning::
|
||||
|
||||
You can use ``get_or_create()`` through :class:`~django.db.models.ManyToManyField`
|
||||
attributes and reverse relations. In that case you will restrict the queries
|
||||
inside the context of that relation. That could lead you to some integrity
|
||||
problems if you don't use it consistently.
|
||||
You can use ``get_or_create()`` through
|
||||
:class:`~django.db.models.ManyToManyField` attributes and reverse relations.
|
||||
In that case you will restrict the queries 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::
|
||||
|
||||
@@ -2336,10 +2341,10 @@ whenever a request to a page has a side effect on your data. For more, see
|
||||
>>> book.chapters.get_or_create(title="Chapter 1")
|
||||
# Raises IntegrityError
|
||||
|
||||
This is happening because it's trying to get or create "Chapter 1" through the
|
||||
book "Ulysses", but it can't do either: the relation can't fetch that chapter
|
||||
because it isn't related to that book, but it can't create it either because
|
||||
``title`` field should be unique.
|
||||
This is happening because it's trying to get or create "Chapter 1" through
|
||||
the book "Ulysses", but it can't do either: the relation can't fetch that
|
||||
chapter because it isn't related to that book, but it can't create it either
|
||||
because ``title`` field should be unique.
|
||||
|
||||
``update_or_create()``
|
||||
~~~~~~~~~~~~~~~~~~~~~~
|
||||
@@ -2904,7 +2909,8 @@ you could do this:
|
||||
|
||||
>>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False)
|
||||
|
||||
(This assumes your ``Entry`` model has fields ``pub_date`` and ``comments_on``.)
|
||||
(This assumes your ``Entry`` model has fields ``pub_date`` and
|
||||
``comments_on``.)
|
||||
|
||||
You can update multiple fields — there's no limit on how many. For example,
|
||||
here we update the ``comments_on`` and ``headline`` fields:
|
||||
@@ -3909,8 +3915,8 @@ Strings that reference fields on the model, transforms of the field, or
|
||||
``output_field``
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
An optional argument that represents the :doc:`model field </ref/models/fields>`
|
||||
of the return value
|
||||
An optional argument that represents the :doc:`model field
|
||||
</ref/models/fields>` of the return value
|
||||
|
||||
.. note::
|
||||
|
||||
|
||||
Reference in New Issue
Block a user