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:
@@ -4,12 +4,12 @@ Aggregation
|
||||
|
||||
.. currentmodule:: django.db.models
|
||||
|
||||
The topic guide on :doc:`Django's database-abstraction API </topics/db/queries>`
|
||||
described the way that you can use Django queries that create,
|
||||
retrieve, update and delete individual objects. However, sometimes you will
|
||||
need to retrieve values that are derived by summarizing or *aggregating* a
|
||||
collection of objects. This topic guide describes the ways that aggregate values
|
||||
can be generated and returned using Django queries.
|
||||
The topic guide on :doc:`Django's database-abstraction API
|
||||
</topics/db/queries>` described the way that you can use Django queries that
|
||||
create, retrieve, update and delete individual objects. However, sometimes you
|
||||
will need to retrieve values that are derived by summarizing or *aggregating* a
|
||||
collection of objects. This topic guide describes the ways that aggregate
|
||||
values can be generated and returned using Django queries.
|
||||
|
||||
Throughout this guide, we'll refer to the following models. These models are
|
||||
used to track the inventory for a series of online bookstores:
|
||||
@@ -322,12 +322,14 @@ We can also ask for the oldest book of any of those managed by every publisher:
|
||||
>>> Publisher.objects.aggregate(oldest_pubdate=Min("book__pubdate"))
|
||||
|
||||
(The resulting dictionary will have a key called ``'oldest_pubdate'``. If no
|
||||
such alias were specified, it would be the rather long ``'book__pubdate__min'``.)
|
||||
such alias were specified, it would be the rather long
|
||||
``'book__pubdate__min'``.)
|
||||
|
||||
This doesn't apply just to foreign keys. It also works with many-to-many
|
||||
relations. For example, we can ask for every author, annotated with the total
|
||||
number of pages considering all the books the author has (co-)authored (note how we
|
||||
use ``'book'`` to specify the ``Author`` -> ``Book`` reverse many-to-many hop):
|
||||
number of pages considering all the books the author has (co-)authored (note
|
||||
how we use ``'book'`` to specify the ``Author`` -> ``Book`` reverse
|
||||
many-to-many hop):
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
@@ -345,7 +347,8 @@ file:
|
||||
>>> Author.objects.aggregate(average_rating=Avg("book__rating"))
|
||||
|
||||
(The resulting dictionary will have a key called ``'average_rating'``. If no
|
||||
such alias were specified, it would be the rather long ``'book__rating__avg'``.)
|
||||
such alias were specified, it would be the rather long
|
||||
``'book__rating__avg'``.)
|
||||
|
||||
Aggregations and other ``QuerySet`` clauses
|
||||
===========================================
|
||||
@@ -527,7 +530,8 @@ rating of books written by each author:
|
||||
This will return one result for each author in the database, annotated with
|
||||
their average book rating.
|
||||
|
||||
However, the result will be slightly different if you use a ``values()`` clause:
|
||||
However, the result will be slightly different if you use a ``values()``
|
||||
clause:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
|
||||
@@ -161,8 +161,8 @@ The :meth:`~django.db.models.query.QuerySet.count` function respects
|
||||
>>> Article.objects.filter(publications__in=[p1, p2]).distinct()
|
||||
<QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
|
||||
|
||||
Reverse m2m queries are supported (i.e., starting at the table that doesn't have
|
||||
a :class:`~django.db.models.ManyToManyField`):
|
||||
Reverse m2m queries are supported (i.e., starting at the table that doesn't
|
||||
have a :class:`~django.db.models.ManyToManyField`):
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
Many-to-one relationships
|
||||
=========================
|
||||
|
||||
To define a many-to-one relationship, use :class:`~django.db.models.ForeignKey`.
|
||||
To define a many-to-one relationship, use
|
||||
:class:`~django.db.models.ForeignKey`.
|
||||
|
||||
In this example, a ``Reporter`` can be associated with many ``Article``
|
||||
objects, but an ``Article`` can only have one ``Reporter`` object::
|
||||
@@ -229,8 +230,8 @@ Queries can go round in circles:
|
||||
<QuerySet [<Reporter: John Smith>]>
|
||||
|
||||
If you delete a reporter, their articles will be deleted (assuming that the
|
||||
ForeignKey was defined with :attr:`django.db.models.ForeignKey.on_delete` set to
|
||||
``CASCADE``, which is the default):
|
||||
ForeignKey was defined with :attr:`django.db.models.ForeignKey.on_delete` set
|
||||
to ``CASCADE``, which is the default):
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
|
||||
@@ -139,7 +139,8 @@ Restaurants:
|
||||
>>> Place.objects.order_by("name")
|
||||
<QuerySet [<Place: Ace Hardware the place>, <Place: Demon Dogs the place>]>
|
||||
|
||||
You can query the models using :ref:`lookups across relationships <lookups-that-span-relationships>`:
|
||||
You can query the models using :ref:`lookups across relationships
|
||||
<lookups-that-span-relationships>`:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@ The wrappers are modeled after :doc:`middleware </topics/http/middleware>` --
|
||||
they are callables which take another callable as one of their arguments. They
|
||||
call that callable to invoke the (possibly wrapped) database query, and they
|
||||
can do what they want around that call. They are, however, created and
|
||||
installed by user code, and so don't need a separate factory like middleware do.
|
||||
installed by user code, and so don't need a separate factory like middleware
|
||||
do.
|
||||
|
||||
Installing a wrapper is done in a context manager -- so the wrappers are
|
||||
temporary and specific to some flow in your code.
|
||||
|
||||
@@ -159,8 +159,9 @@ For example::
|
||||
authors = AuthorManager()
|
||||
editors = EditorManager()
|
||||
|
||||
This example allows you to request ``Person.authors.all()``, ``Person.editors.all()``,
|
||||
and ``Person.people.all()``, yielding predictable results.
|
||||
This example allows you to request ``Person.authors.all()``,
|
||||
``Person.editors.all()``, and ``Person.people.all()``, yielding predictable
|
||||
results.
|
||||
|
||||
.. _default-managers:
|
||||
|
||||
@@ -260,8 +261,8 @@ custom ``QuerySet`` if you also implement them on the ``Manager``::
|
||||
role = models.CharField(max_length=1, choices={"A": _("Author"), "E": _("Editor")})
|
||||
people = PersonManager()
|
||||
|
||||
This example allows you to call both ``authors()`` and ``editors()`` directly from
|
||||
the manager ``Person.people``.
|
||||
This example allows you to call both ``authors()`` and ``editors()`` directly
|
||||
from the manager ``Person.people``.
|
||||
|
||||
.. _create-manager-with-queryset-methods:
|
||||
|
||||
@@ -290,7 +291,8 @@ Methods are copied according to the following rules:
|
||||
|
||||
- Public methods are copied by default.
|
||||
- Private methods (starting with an underscore) are not copied by default.
|
||||
- Methods with a ``queryset_only`` attribute set to ``False`` are always copied.
|
||||
- Methods with a ``queryset_only`` attribute set to ``False`` are always
|
||||
copied.
|
||||
- Methods with a ``queryset_only`` attribute set to ``True`` are never copied.
|
||||
|
||||
For example::
|
||||
@@ -401,10 +403,10 @@ still available, since it's inherited, but isn't used as the default.
|
||||
|
||||
Finally for this example, suppose you want to add extra managers to the child
|
||||
class, but still use the default from ``AbstractBase``. You can't add the new
|
||||
manager directly in the child class, as that would override the default and you would
|
||||
have to also explicitly include all the managers from the abstract base class.
|
||||
The solution is to put the extra managers in another base class and introduce
|
||||
it into the inheritance hierarchy *after* the defaults::
|
||||
manager directly in the child class, as that would override the default and you
|
||||
would have to also explicitly include all the managers from the abstract base
|
||||
class. The solution is to put the extra managers in another base class and
|
||||
introduce it into the inheritance hierarchy *after* the defaults::
|
||||
|
||||
class ExtraManager(models.Model):
|
||||
extra_manager = OtherManager()
|
||||
@@ -431,8 +433,8 @@ is legal, but::
|
||||
will raise an exception. This is because managers are intended to encapsulate
|
||||
logic for managing collections of objects. Since you can't have a collection of
|
||||
abstract objects, it doesn't make sense to be managing them. If you have
|
||||
functionality that applies to the abstract model, you should put that functionality
|
||||
in a ``staticmethod`` or ``classmethod`` on the abstract model.
|
||||
functionality that applies to the abstract model, you should put that
|
||||
functionality in a ``staticmethod`` or ``classmethod`` on the abstract model.
|
||||
|
||||
Implementation concerns
|
||||
-----------------------
|
||||
|
||||
@@ -61,8 +61,8 @@ Some technical notes:
|
||||
Using models
|
||||
============
|
||||
|
||||
Once you have defined your models, you need to tell Django you're going to *use*
|
||||
those models. Do this by editing your settings file and changing the
|
||||
Once you have defined your models, you need to tell Django you're going to
|
||||
*use* those models. Do this by editing your settings file and changing the
|
||||
:setting:`INSTALLED_APPS` setting to add the name of the module that contains
|
||||
your ``models.py``.
|
||||
|
||||
@@ -117,15 +117,15 @@ determine a few things:
|
||||
* The column type, which tells the database what kind of data to store (e.g.
|
||||
``INTEGER``, ``VARCHAR``, ``TEXT``).
|
||||
|
||||
* The default HTML :doc:`widget </ref/forms/widgets>` to use when rendering a form
|
||||
field (e.g. ``<input type="text">``, ``<select>``).
|
||||
* The default HTML :doc:`widget </ref/forms/widgets>` to use when rendering a
|
||||
form field (e.g. ``<input type="text">``, ``<select>``).
|
||||
|
||||
* The minimal validation requirements, used in Django's admin and in
|
||||
automatically-generated forms.
|
||||
|
||||
Django ships with dozens of built-in field types; you can find the complete list
|
||||
in the :ref:`model field reference <model-field-types>`. You can easily write
|
||||
your own fields if Django's built-in ones don't do the trick; see
|
||||
Django ships with dozens of built-in field types; you can find the complete
|
||||
list in the :ref:`model field reference <model-field-types>`. You can easily
|
||||
write your own fields if Django's built-in ones don't do the trick; see
|
||||
:doc:`/howto/custom-model-fields`.
|
||||
|
||||
Field options
|
||||
@@ -134,13 +134,13 @@ Field options
|
||||
Each field takes a certain set of field-specific arguments (documented in the
|
||||
:ref:`model field reference <model-field-types>`). For example,
|
||||
:class:`~django.db.models.CharField` (and its subclasses) require a
|
||||
:attr:`~django.db.models.CharField.max_length` argument which specifies the size
|
||||
of the ``VARCHAR`` database field used to store the data.
|
||||
:attr:`~django.db.models.CharField.max_length` argument which specifies the
|
||||
size of the ``VARCHAR`` database field used to store the data.
|
||||
|
||||
There's also a set of common arguments available to all field types. All are
|
||||
optional. They're fully explained in the :ref:`reference
|
||||
<common-model-field-options>`, but here's a quick summary of the most often-used
|
||||
ones:
|
||||
<common-model-field-options>`, but here's a quick summary of the most
|
||||
often-used ones:
|
||||
|
||||
:attr:`~Field.null`
|
||||
If ``True``, Django will store empty values as ``NULL`` in the database.
|
||||
@@ -284,10 +284,9 @@ type specified per app in :attr:`AppConfig.default_auto_field
|
||||
|
||||
id = models.BigAutoField(primary_key=True)
|
||||
|
||||
If you'd like to specify a custom primary key, specify
|
||||
:attr:`primary_key=True <Field.primary_key>` on one of your fields. If Django
|
||||
sees you've explicitly set :attr:`Field.primary_key`, it won't add the automatic
|
||||
``id`` column.
|
||||
If you'd like to specify a custom primary key, specify :attr:`primary_key=True
|
||||
<Field.primary_key>` on one of your fields. If Django sees you've explicitly
|
||||
set :attr:`Field.primary_key`, it won't add the automatic ``id`` column.
|
||||
|
||||
Each model requires exactly one field to have :attr:`primary_key=True
|
||||
<Field.primary_key>` (either explicitly declared or automatically added).
|
||||
@@ -301,8 +300,8 @@ Each field type, except for :class:`~django.db.models.ForeignKey`,
|
||||
:class:`~django.db.models.ManyToManyField` and
|
||||
:class:`~django.db.models.OneToOneField`, takes an optional first positional
|
||||
argument -- a verbose name. If the verbose name isn't given, Django will
|
||||
automatically create it using the field's attribute name, converting underscores
|
||||
to spaces.
|
||||
automatically create it using the field's attribute name, converting
|
||||
underscores to spaces.
|
||||
|
||||
In this example, the verbose name is ``"person's first name"``::
|
||||
|
||||
@@ -366,9 +365,9 @@ For example, if a ``Car`` model has a ``Manufacturer`` -- that is, a
|
||||
manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
|
||||
# ...
|
||||
|
||||
You can also create :ref:`recursive relationships <recursive-relationships>` (an
|
||||
object with a many-to-one relationship to itself) and :ref:`relationships to
|
||||
models not yet defined <lazy-relationships>`; see :ref:`the model field
|
||||
You can also create :ref:`recursive relationships <recursive-relationships>`
|
||||
(an object with a many-to-one relationship to itself) and :ref:`relationships
|
||||
to models not yet defined <lazy-relationships>`; see :ref:`the model field
|
||||
reference <ref-foreignkey>` for details.
|
||||
|
||||
It's suggested, but not required, that the name of a
|
||||
@@ -390,8 +389,8 @@ want. For example::
|
||||
<foreign-key-arguments>`. These options help define how the relationship
|
||||
should work; all are optional.
|
||||
|
||||
For details on accessing backwards-related objects, see the
|
||||
:ref:`Following relationships backward example <backwards-related-objects>`.
|
||||
For details on accessing backwards-related objects, see the :ref:`Following
|
||||
relationships backward example <backwards-related-objects>`.
|
||||
|
||||
For sample code, see the :doc:`Many-to-one relationship model example
|
||||
</topics/db/examples/many_to_one>`.
|
||||
@@ -465,8 +464,8 @@ matching pizzas and toppings, a standard
|
||||
you may need to associate data with the relationship between two models.
|
||||
|
||||
For example, consider the case of an application tracking the musical groups
|
||||
which musicians belong to. There is a many-to-many relationship between a person
|
||||
and the groups of which they are a member, so you could use a
|
||||
which musicians belong to. There is a many-to-many relationship between a
|
||||
person and the groups of which they are a member, so you could use a
|
||||
:class:`~django.db.models.ManyToManyField` to represent this relationship.
|
||||
However, there is a lot of detail about the membership that you might want to
|
||||
collect, such as the date at which the person joined the group.
|
||||
@@ -524,11 +523,11 @@ There are a few restrictions on the intermediate model:
|
||||
* Your intermediate model must contain one - and *only* one - foreign key
|
||||
to the source model (this would be ``Group`` in our example), or you must
|
||||
explicitly specify the foreign keys Django should use for the relationship
|
||||
using :attr:`ManyToManyField.through_fields <ManyToManyField.through_fields>`.
|
||||
If you have more than one foreign key and ``through_fields`` is not
|
||||
specified, a validation error will be raised. A similar restriction applies
|
||||
to the foreign key to the target model (this would be ``Person`` in our
|
||||
example).
|
||||
using :attr:`ManyToManyField.through_fields
|
||||
<ManyToManyField.through_fields>`. If you have more than one foreign key and
|
||||
``through_fields`` is not specified, a validation error will be raised. A
|
||||
similar restriction applies to the foreign key to the target model (this
|
||||
would be ``Person`` in our example).
|
||||
|
||||
* For a model which has a many-to-many relationship to itself through an
|
||||
intermediary model, two foreign keys to the same model are permitted, but
|
||||
@@ -800,13 +799,13 @@ Give your model metadata by using an inner ``class Meta``, like so::
|
||||
verbose_name_plural = "oxen"
|
||||
|
||||
Model metadata is "anything that's not a field", such as ordering options
|
||||
(:attr:`~Options.ordering`), database table name (:attr:`~Options.db_table`), or
|
||||
human-readable singular and plural names (:attr:`~Options.verbose_name` and
|
||||
(:attr:`~Options.ordering`), database table name (:attr:`~Options.db_table`),
|
||||
or human-readable singular and plural names (:attr:`~Options.verbose_name` and
|
||||
:attr:`~Options.verbose_name_plural`). None are required, and adding ``class
|
||||
Meta`` to a model is completely optional.
|
||||
|
||||
A complete list of all possible ``Meta`` options can be found in the :doc:`model
|
||||
option reference </ref/models/options>`.
|
||||
A complete list of all possible ``Meta`` options can be found in the
|
||||
:doc:`model option reference </ref/models/options>`.
|
||||
|
||||
.. _model-attributes:
|
||||
|
||||
@@ -827,9 +826,10 @@ Model attributes
|
||||
Model methods
|
||||
=============
|
||||
|
||||
Define custom methods on a model to add custom "row-level" functionality to your
|
||||
objects. Whereas :class:`~django.db.models.Manager` methods are intended to do
|
||||
"table-wide" things, model methods should act on a particular model instance.
|
||||
Define custom methods on a model to add custom "row-level" functionality to
|
||||
your objects. Whereas :class:`~django.db.models.Manager` methods are intended
|
||||
to do "table-wide" things, model methods should act on a particular model
|
||||
instance.
|
||||
|
||||
This is a valuable technique for keeping business logic in one place -- the
|
||||
model.
|
||||
@@ -1059,11 +1059,12 @@ still only creating one database table per child model at the database level.
|
||||
``Meta`` inheritance
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
When an abstract base class is created, Django makes any :ref:`Meta <meta-options>`
|
||||
inner class you declared in the base class available as an
|
||||
attribute. If a child class does not declare its own :ref:`Meta <meta-options>`
|
||||
class, it will inherit the parent's :ref:`Meta <meta-options>`. If the child wants to
|
||||
extend the parent's :ref:`Meta <meta-options>` class, it can subclass it. For example::
|
||||
When an abstract base class is created, Django makes any
|
||||
:ref:`Meta <meta-options>` inner class you declared in the base class available
|
||||
as an attribute. If a child class does not declare its own
|
||||
:ref:`Meta <meta-options>` class, it will inherit the parent's
|
||||
:ref:`Meta <meta-options>`. If the child wants to extend the parent's
|
||||
:ref:`Meta <meta-options>` class, it can subclass it. For example::
|
||||
|
||||
from django.db import models
|
||||
|
||||
@@ -1087,10 +1088,11 @@ base classes don't automatically become abstract classes themselves. To make
|
||||
an abstract base class that inherits from another abstract base class, you need
|
||||
to explicitly set ``abstract=True`` on the child.
|
||||
|
||||
Some attributes won't make sense to include in the :ref:`Meta <meta-options>` class of an
|
||||
abstract base class. For example, including ``db_table`` would mean that all
|
||||
the child classes (the ones that don't specify their own :ref:`Meta <meta-options>`) would use
|
||||
the same database table, which is almost certainly not what you want.
|
||||
Some attributes won't make sense to include in the :ref:`Meta <meta-options>`
|
||||
class of an abstract base class. For example, including ``db_table`` would mean
|
||||
that all the child classes (the ones that don't specify their own
|
||||
:ref:`Meta <meta-options>`) would use the same database table, which is almost
|
||||
certainly not what you want.
|
||||
|
||||
Due to the way Python inheritance works, if a child class inherits from
|
||||
multiple abstract base classes, only the :ref:`Meta <meta-options>` options
|
||||
@@ -1181,15 +1183,15 @@ Along with another app ``rare/models.py``::
|
||||
pass
|
||||
|
||||
The reverse name of the ``common.ChildA.m2m`` field will be
|
||||
``common_childa_related`` and the reverse query name will be ``common_childas``.
|
||||
The reverse name of the ``common.ChildB.m2m`` field will be
|
||||
``common_childa_related`` and the reverse query name will be
|
||||
``common_childas``. The reverse name of the ``common.ChildB.m2m`` field will be
|
||||
``common_childb_related`` and the reverse query name will be
|
||||
``common_childbs``. Finally, the reverse name of the ``rare.ChildB.m2m`` field
|
||||
will be ``rare_childb_related`` and the reverse query name will be
|
||||
``rare_childbs``. It's up to you how you use the ``'%(class)s'`` and
|
||||
``'%(app_label)s'`` portion to construct your related name or related query name
|
||||
but if you forget to use it, Django will raise errors when you perform system
|
||||
checks (or run :djadmin:`migrate`).
|
||||
``'%(app_label)s'`` portion to construct your related name or related query
|
||||
name but if you forget to use it, Django will raise errors when you perform
|
||||
system checks (or run :djadmin:`migrate`).
|
||||
|
||||
If you don't specify a :attr:`~django.db.models.ForeignKey.related_name`
|
||||
attribute for a field in an abstract base class, the default reverse name will
|
||||
@@ -1269,11 +1271,11 @@ You can override that field by declaring your own
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
In the multi-table inheritance situation, it doesn't make sense for a child
|
||||
class to inherit from its parent's :ref:`Meta <meta-options>` class. All the :ref:`Meta <meta-options>` options
|
||||
have already been applied to the parent class and applying them again would
|
||||
normally only lead to contradictory behavior (this is in contrast with the
|
||||
abstract base class case, where the base class doesn't exist in its own
|
||||
right).
|
||||
class to inherit from its parent's :ref:`Meta <meta-options>` class. All the
|
||||
:ref:`Meta <meta-options>` options have already been applied to the parent
|
||||
class and applying them again would normally only lead to contradictory
|
||||
behavior (this is in contrast with the abstract base class case, where the base
|
||||
class doesn't exist in its own right).
|
||||
|
||||
So a child model does not have access to its parent's :ref:`Meta
|
||||
<meta-options>` class. However, there are a few limited cases where the child
|
||||
@@ -1359,7 +1361,8 @@ Proxy models are declared like normal models. You tell Django that it's a
|
||||
proxy model by setting the :attr:`~django.db.models.Options.proxy` attribute of
|
||||
the ``Meta`` class to ``True``.
|
||||
|
||||
For example, suppose you want to add a method to the ``Person`` model. You can do it like this::
|
||||
For example, suppose you want to add a method to the ``Person`` model. You can
|
||||
do it like this::
|
||||
|
||||
from django.db import models
|
||||
|
||||
|
||||
@@ -587,7 +587,8 @@ solution is to use ``db_manager()``, like this::
|
||||
|
||||
User.objects.db_manager("new_users").create_user(...)
|
||||
|
||||
``db_manager()`` returns a copy of the manager bound to the database you specify.
|
||||
``db_manager()`` returns a copy of the manager bound to the database you
|
||||
specify.
|
||||
|
||||
Using ``get_queryset()`` with multiple databases
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
@@ -21,8 +21,8 @@ your requirements. Sometimes optimizing for one will be detrimental to the
|
||||
other, but sometimes they will help each other. Also, work that is done by the
|
||||
database process might not have the same cost (to you) as the same amount of
|
||||
work done in your Python process. It is up to you to decide what your
|
||||
priorities are, where the balance must lie, and profile all of these as required
|
||||
since this will depend on your application and server.
|
||||
priorities are, where the balance must lie, and profile all of these as
|
||||
required since this will depend on your application and server.
|
||||
|
||||
With everything that follows, remember to profile after every change to ensure
|
||||
that the change is a benefit, and a big enough benefit given the decrease in
|
||||
@@ -202,8 +202,8 @@ Retrieve everything at once if you know you will need it
|
||||
Hitting the database multiple times for different parts of a single 'set' of
|
||||
data that you will need all parts of is, in general, less efficient than
|
||||
retrieving it all in one query. This is particularly important if you have a
|
||||
query that is executed in a loop, and could therefore end up doing many database
|
||||
queries, when only one was needed. So:
|
||||
query that is executed in a loop, and could therefore end up doing many
|
||||
database queries, when only one was needed. So:
|
||||
|
||||
Use ``QuerySet.select_related()`` and ``prefetch_related()``
|
||||
------------------------------------------------------------
|
||||
@@ -332,9 +332,9 @@ anything driven from the normal database object :doc:`signals </ref/signals>`.
|
||||
Use foreign key values directly
|
||||
-------------------------------
|
||||
|
||||
If you only need a foreign key value, use the foreign key value that is already on
|
||||
the object you've got, rather than getting the whole related object and taking
|
||||
its primary key. i.e. do::
|
||||
If you only need a foreign key value, use the foreign key value that is already
|
||||
on the object you've got, rather than getting the whole related object and
|
||||
taking its primary key. i.e. do::
|
||||
|
||||
entry.blog_id
|
||||
|
||||
|
||||
@@ -518,8 +518,8 @@ probably use:
|
||||
case-insensitive versions called :lookup:`istartswith` and
|
||||
:lookup:`iendswith`.
|
||||
|
||||
Again, this only scratches the surface. A complete reference can be found in the
|
||||
:ref:`field lookup reference <field-lookups>`.
|
||||
Again, this only scratches the surface. A complete reference can be found in
|
||||
the :ref:`field lookup reference <field-lookups>`.
|
||||
|
||||
.. _lookups-that-span-relationships:
|
||||
|
||||
@@ -706,10 +706,10 @@ and use that ``F()`` object in the query:
|
||||
>>> from django.db.models import F
|
||||
>>> Entry.objects.filter(number_of_comments__gt=F("number_of_pingbacks"))
|
||||
|
||||
Django supports the use of addition, subtraction, multiplication,
|
||||
division, modulo, and power arithmetic with ``F()`` objects, both with constants
|
||||
and with other ``F()`` objects. To find all the blog entries with more than
|
||||
*twice* as many comments as pingbacks, we modify the query:
|
||||
Django supports the use of addition, subtraction, multiplication, division,
|
||||
modulo, and power arithmetic with ``F()`` objects, both with constants and with
|
||||
other ``F()`` objects. To find all the blog entries with more than *twice* as
|
||||
many comments as pingbacks, we modify the query:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
@@ -1370,7 +1370,8 @@ Complex lookups with ``Q`` objects
|
||||
|
||||
Keyword argument queries -- in :meth:`~django.db.models.query.QuerySet.filter`,
|
||||
etc. -- are "AND"ed together. If you need to execute more complex queries (for
|
||||
example, queries with ``OR`` statements), you can use :class:`Q objects <django.db.models.Q>`.
|
||||
example, queries with ``OR`` statements), you can use
|
||||
:class:`Q objects <django.db.models.Q>`.
|
||||
|
||||
A :class:`Q object <django.db.models.Q>` (``django.db.models.Q``) is an object
|
||||
used to encapsulate a collection of keyword arguments. These keyword arguments
|
||||
@@ -1688,9 +1689,9 @@ When you define a relationship in a model (i.e., a
|
||||
:class:`~django.db.models.ManyToManyField`), instances of that model will have
|
||||
a convenient API to access the related object(s).
|
||||
|
||||
Using the models at the top of this page, for example, an ``Entry`` object ``e``
|
||||
can get its associated ``Blog`` object by accessing the ``blog`` attribute:
|
||||
``e.blog``.
|
||||
Using the models at the top of this page, for example, an ``Entry`` object
|
||||
``e`` can get its associated ``Blog`` object by accessing the ``blog``
|
||||
attribute: ``e.blog``.
|
||||
|
||||
(Behind the scenes, this functionality is implemented by Python
|
||||
:doc:`descriptors <python:howto/descriptor>`. This shouldn't really matter to
|
||||
@@ -1805,9 +1806,9 @@ Using a custom reverse manager
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
By default the :class:`~django.db.models.fields.related.RelatedManager` used
|
||||
for reverse relations is a subclass of the :ref:`default manager <manager-names>`
|
||||
for that model. If you would like to specify a different manager for a given
|
||||
query you can use the following syntax::
|
||||
for reverse relations is a subclass of the :ref:`default manager
|
||||
<manager-names>` for that model. If you would like to specify a different
|
||||
manager for a given query you can use the following syntax::
|
||||
|
||||
from django.db import models
|
||||
|
||||
@@ -1941,9 +1942,9 @@ For example::
|
||||
ed.entry # Returns the related Entry object.
|
||||
|
||||
The difference comes in "reverse" queries. The related model in a one-to-one
|
||||
relationship also has access to a :class:`~django.db.models.Manager` object, but
|
||||
that :class:`~django.db.models.Manager` represents a single object, rather than
|
||||
a collection of objects::
|
||||
relationship also has access to a :class:`~django.db.models.Manager` object,
|
||||
but that :class:`~django.db.models.Manager` represents a single object, rather
|
||||
than a collection of objects::
|
||||
|
||||
e = Entry.objects.get(id=2)
|
||||
e.entrydetail # returns the related EntryDetail object
|
||||
|
||||
@@ -49,7 +49,8 @@ This method takes a raw SQL query, executes it, and returns a
|
||||
can be iterated over like a normal :class:`~django.db.models.query.QuerySet` to
|
||||
provide object instances.
|
||||
|
||||
This is best illustrated with an example. Suppose you have the following model::
|
||||
This is best illustrated with an example. Suppose you have the following
|
||||
model::
|
||||
|
||||
class Person(models.Model):
|
||||
first_name = models.CharField(...)
|
||||
@@ -93,13 +94,13 @@ make it very powerful.
|
||||
|
||||
.. 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.
|
||||
|
||||
Mapping query fields to model fields
|
||||
------------------------------------
|
||||
@@ -302,8 +303,8 @@ For example::
|
||||
To protect against SQL injection, you must not include quotes around the ``%s``
|
||||
placeholders in the SQL string.
|
||||
|
||||
Note that if you want to include literal percent signs in the query, you have to
|
||||
double them in the case you are passing parameters::
|
||||
Note that if you want to include literal percent signs in the query, you have
|
||||
to double them in the case you are passing parameters::
|
||||
|
||||
cursor.execute("SELECT foo FROM bar WHERE baz = '30%'")
|
||||
cursor.execute("SELECT foo FROM bar WHERE baz = '30%%' AND id = %s", [self.id])
|
||||
|
||||
@@ -21,10 +21,10 @@ the :attr:`~django.db.models.Options.db_tablespace` option inside the model's
|
||||
``class Meta``. This option also affects tables automatically created for
|
||||
:class:`~django.db.models.ManyToManyField`\ s in the model.
|
||||
|
||||
You can use the :setting:`DEFAULT_TABLESPACE` setting to specify a default value
|
||||
for :attr:`~django.db.models.Options.db_tablespace`. This is useful for setting
|
||||
a tablespace for the built-in Django apps and other applications whose code you
|
||||
cannot control.
|
||||
You can use the :setting:`DEFAULT_TABLESPACE` setting to specify a default
|
||||
value for :attr:`~django.db.models.Options.db_tablespace`. This is useful for
|
||||
setting a tablespace for the built-in Django apps and other applications whose
|
||||
code you cannot control.
|
||||
|
||||
Declaring tablespaces for indexes
|
||||
=================================
|
||||
|
||||
@@ -45,10 +45,10 @@ either all or none of the changes will be committed.
|
||||
|
||||
.. warning::
|
||||
|
||||
While the simplicity of this transaction model is appealing, it also makes it
|
||||
inefficient when traffic increases. Opening a transaction for every view has
|
||||
some overhead. The impact on performance depends on the query patterns of your
|
||||
application and on how well your database handles locking.
|
||||
While the simplicity of this transaction model is appealing, it also makes
|
||||
it inefficient when traffic increases. Opening a transaction for every view
|
||||
has some overhead. The impact on performance depends on the query patterns
|
||||
of your application and on how well your database handles locking.
|
||||
|
||||
.. admonition:: Per-request transactions and streaming responses
|
||||
|
||||
|
||||
Reference in New Issue
Block a user