394
401
:meth:`values()` together, be careful when ordering by fields not in the
395
402
:meth:`values()` call.
397
.. versionadded:: 1.4
399
As of Django 1.4, you can pass positional arguments (``*fields``) in order to
404
On PostgreSQL only, you can pass positional arguments (``*fields``) in order to
400
405
specify the names of fields to which the ``DISTINCT`` should apply. This
401
translates to a ``SELECT DISTINCT ON`` SQL query.
403
Here's the difference. For a normal ``distinct()`` call, the database compares
404
*each* field in each row when determining which rows are distinct. For a
405
``distinct()`` call with specified field names, the database will only compare
406
the specified field names.
409
This ability to specify field names is only available in PostgreSQL.
406
translates to a ``SELECT DISTINCT ON`` SQL query. Here's the difference. For a
407
normal ``distinct()`` call, the database compares *each* field in each row when
408
determining which rows are distinct. For a ``distinct()`` call with specified
409
field names, the database will only compare the specified field names.
412
412
When you specify field names, you *must* provide an ``order_by()`` in the
564
564
If you don't pass any values to ``values_list()``, it will return all the
565
565
fields in the model, in the order they were declared.
567
Note that this method returns a ``ValuesListQuerySet``. This class behaves
568
like a list. Most of the time this is enough, but if you require an actual
569
Python list object, you can simply call ``list()`` on it, which will evaluate
570
575
.. method:: dates(field, kind, order='ASC')
572
577
Returns a ``DateQuerySet`` — a ``QuerySet`` that evaluates to a list of
573
``datetime.datetime`` objects representing all available dates of a particular
574
kind within the contents of the ``QuerySet``.
576
``field`` should be the name of a ``DateField`` or ``DateTimeField`` of your
578
:class:`datetime.date` objects representing all available dates of a
579
particular kind within the contents of the ``QuerySet``.
581
.. versionchanged:: 1.6
583
``dates`` used to return a list of :class:`datetime.datetime` objects.
585
``field`` should be the name of a ``DateField`` of your model.
587
.. versionchanged:: 1.6
589
``dates`` used to accept operating on a ``DateTimeField``.
579
591
``kind`` should be either ``"year"``, ``"month"`` or ``"day"``. Each
580
``datetime.datetime`` object in the result list is "truncated" to the given
592
``datetime.date`` object in the result list is "truncated" to the given
583
595
* ``"year"`` returns a list of all distinct year values for the field.
594
606
>>> Entry.objects.dates('pub_date', 'year')
595
[datetime.datetime(2005, 1, 1)]
607
[datetime.date(2005, 1, 1)]
596
608
>>> Entry.objects.dates('pub_date', 'month')
597
[datetime.datetime(2005, 2, 1), datetime.datetime(2005, 3, 1)]
609
[datetime.date(2005, 2, 1), datetime.date(2005, 3, 1)]
598
610
>>> Entry.objects.dates('pub_date', 'day')
599
[datetime.datetime(2005, 2, 20), datetime.datetime(2005, 3, 20)]
611
[datetime.date(2005, 2, 20), datetime.date(2005, 3, 20)]
600
612
>>> Entry.objects.dates('pub_date', 'day', order='DESC')
601
[datetime.datetime(2005, 3, 20), datetime.datetime(2005, 2, 20)]
613
[datetime.date(2005, 3, 20), datetime.date(2005, 2, 20)]
602
614
>>> Entry.objects.filter(headline__contains='Lennon').dates('pub_date', 'day')
603
[datetime.datetime(2005, 3, 20)]
607
When :doc:`time zone support </topics/i18n/timezones>` is enabled, Django
608
uses UTC in the database connection, which means the aggregation is
609
performed in UTC. This is a known limitation of the current implementation.
615
[datetime.date(2005, 3, 20)]
620
.. versionadded:: 1.6
622
.. method:: datetimes(field, kind, order='ASC', tzinfo=None)
624
Returns a ``DateTimeQuerySet`` — a ``QuerySet`` that evaluates to a list of
625
:class:`datetime.datetime` objects representing all available dates of a
626
particular kind within the contents of the ``QuerySet``.
628
``field`` should be the name of a ``DateTimeField`` of your model.
630
``kind`` should be either ``"year"``, ``"month"``, ``"day"``, ``"hour"``,
631
``"minute"`` or ``"second"``. Each ``datetime.datetime`` object in the result
632
list is "truncated" to the given ``type``.
634
``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or
635
``'DESC'``. This specifies how to order the results.
637
``tzinfo`` defines the time zone to which datetimes are converted prior to
638
truncation. Indeed, a given datetime has different representations depending
639
on the time zone in use. This parameter must be a :class:`datetime.tzinfo`
640
object. If it's ``None``, Django uses the :ref:`current time zone
641
<default-current-time-zone>`. It has no effect when :setting:`USE_TZ` is
644
.. _database-time-zone-definitions:
648
This function performs time zone conversions directly in the database.
649
As a consequence, your database must be able to interpret the value of
650
``tzinfo.tzname(None)``. This translates into the following requirements:
652
- SQLite: install pytz_ — conversions are actually performed in Python.
653
- PostgreSQL: no requirements (see `Time Zones`_).
654
- Oracle: no requirements (see `Choosing a Time Zone File`_).
655
- MySQL: install pytz_ and load the time zone tables with
656
`mysql_tzinfo_to_sql`_.
658
.. _pytz: http://pytz.sourceforge.net/
659
.. _Time Zones: http://www.postgresql.org/docs/current/static/datatype-datetime.html#DATATYPE-TIMEZONES
660
.. _Choosing a Time Zone File: http://docs.oracle.com/cd/B19306_01/server.102/b14225/ch4datetime.htm#i1006667
661
.. _mysql_tzinfo_to_sql: http://dev.mysql.com/doc/refman/5.5/en/mysql-tzinfo-to-sql.html
614
666
.. method:: none()
616
Returns an ``EmptyQuerySet`` — a ``QuerySet`` subclass that always evaluates to
617
an empty list. This can be used in cases where you know that you should return
618
an empty result set and your caller is expecting a ``QuerySet`` object (instead
619
of returning an empty list, for example.)
668
Calling none() will create a queryset that never returns any objects and no
669
query will be executed when accessing the results. A qs.none() queryset
670
is an instance of ``EmptyQuerySet``.
623
674
>>> Entry.objects.none()
676
>>> from django.db.models.query import EmptyQuerySet
677
>>> isinstance(Entry.objects.none(), EmptyQuerySet)
1113
1177
.. versionchanged:: 1.5
1115
Some fields in a model won't be deferred, even if you ask for them. You can
1116
never defer the loading of the primary key. If you are using
1117
:meth:`select_related()` to retrieve related models, you shouldn't defer the
1118
loading of the field that connects from the primary model to the related
1119
one, doing so will result in an error.
1179
Some fields in a model won't be deferred, even if you ask for them. You can
1180
never defer the loading of the primary key. If you are using
1181
:meth:`select_related()` to retrieve related models, you shouldn't defer the
1182
loading of the field that connects from the primary model to the related
1183
one, doing so will result in an error.
1184
1248
# existing set of fields).
1185
1249
Entry.objects.defer("body").only("headline", "body")
1187
.. versionchanged:: 1.5
1189
1251
All of the cautions in the note for the :meth:`defer` documentation apply to
1190
1252
``only()`` as well. Use it cautiously and only after exhausting your other
1191
options. Also note that using :meth:`only` and omitting a field requested
1192
using :meth:`select_related` is an error as well.
1194
1255
.. versionchanged:: 1.5
1198
When calling :meth:`~django.db.models.Model.save()` for instances with
1199
deferred fields, only the loaded fields will be saved. See
1200
:meth:`~django.db.models.Model.save()` for more details.
1257
Using :meth:`only` and omitting a field requested using
1258
:meth:`select_related` is an error as well.
1262
When calling :meth:`~django.db.models.Model.save()` for instances with
1263
deferred fields, only the loaded fields will be saved. See
1264
:meth:`~django.db.models.Model.save()` for more details.
1400
1461
Finally, a word on using ``get_or_create()`` in Django views: please make sure
1401
1462
to use it only in ``POST`` requests unless you have a good reason not to
1402
1463
``GET`` requests shouldn't have any effect on data; use ``POST`` whenever a
1403
request to a page as a side effect on your data. For more, see `Safe methods`_
1464
request to a page has a side effect on your data. For more, see `Safe methods`_
1404
1465
in the HTTP spec.
1406
1467
.. _Safe methods: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
1471
You can use ``get_or_create()`` through :class:`~django.db.models.ManyToManyField`
1472
attributes and reverse relations. In that case you will restrict the queries
1473
inside the context of that relation. That could lead you to some integrity
1474
problems if you don't use it consistently.
1476
Being the following models::
1478
class Chapter(models.Model):
1479
title = models.CharField(max_length=255, unique=True)
1481
class Book(models.Model):
1482
title = models.CharField(max_length=256)
1483
chapters = models.ManyToManyField(Chapter)
1485
You can use ``get_or_create()`` through Book's chapters field, but it only
1486
fetches inside the context of that book::
1488
>>> book = Book.objects.create(title="Ulysses")
1489
>>> book.chapters.get_or_create(title="Telemachus")
1490
(<Chapter: Telemachus>, True)
1491
>>> book.chapters.get_or_create(title="Telemachus")
1492
(<Chapter: Telemachus>, False)
1493
>>> Chapter.objects.create(title="Chapter 1")
1494
<Chapter: Chapter 1>
1495
>>> book.chapters.get_or_create(title="Chapter 1")
1496
# Raises IntegrityError
1498
This is happening because it's trying to get or create "Chapter 1" through the
1499
book "Ulysses", but it can't do any of them: the relation can't fetch that
1500
chapter because it isn't related to that book, but it can't create it either
1501
because ``title`` field should be unique.
1411
1507
.. method:: bulk_create(objs, batch_size=None)
1413
.. versionadded:: 1.4
1415
1509
This method inserts the provided list of objects into the database in an
1416
1510
efficient manner (generally only 1 query, no matter how many objects there
1528
1623
If your model's :ref:`Meta <meta-options>` specifies
1529
1624
:attr:`~django.db.models.Options.get_latest_by`, you can leave off the
1530
``field_name`` argument to ``latest()``. Django will use the field specified
1531
in :attr:`~django.db.models.Options.get_latest_by` by default.
1533
Like :meth:`get()`, ``latest()`` raises
1534
:exc:`~django.core.exceptions.DoesNotExist` if there is no object with the given
1537
Note ``latest()`` exists purely for convenience and readability.
1625
``field_name`` argument to ``earliest()`` or ``latest()``. Django will use the
1626
field specified in :attr:`~django.db.models.Options.get_latest_by` by default.
1628
Like :meth:`get()`, ``earliest()`` and ``latest()`` raise
1629
:exc:`~django.core.exceptions.DoesNotExist` if there is no object with the
1632
Note that ``earliest()`` and ``latest()`` exist purely for convenience and
1638
.. method:: earliest(field_name=None)
1640
.. versionadded:: 1.6
1642
Works otherwise like :meth:`~django.db.models.query.QuerySet.latest` except
1643
the direction is changed.
1649
.. versionadded:: 1.6
1651
Returns the first object matched by the queryset, or ``None`` if there
1652
is no matching object. If the ``QuerySet`` has no ordering defined, then the
1653
queryset is automatically ordered by the primary key.
1657
p = Article.objects.order_by('title', 'pub_date').first()
1659
Note that ``first()`` is a convenience method, the following code sample is
1660
equivalent to the above example::
1663
p = Article.objects.order_by('title', 'pub_date')[0]
1671
.. versionadded:: 1.6
1673
Works like :meth:`first()`, but returns the last object in the queryset.
1586
1723
(e.g. ``primary_key``) is a member of a :class:`.QuerySet` is::
1588
1725
entry = Entry.objects.get(pk=123)
1589
if some_query_set.filter(pk=entry.pk).exists():
1726
if some_queryset.filter(pk=entry.pk).exists():
1590
1727
print("Entry contained in queryset")
1592
1729
Which will be faster than the following which requires evaluating and iterating
1593
1730
through the entire queryset::
1595
if entry in some_query_set:
1732
if entry in some_queryset:
1596
1733
print("Entry contained in QuerySet")
1598
1735
And to find whether a queryset contains any items::
1600
if some_query_set.exists():
1601
print("There is at least one object in some_query_set")
1737
if some_queryset.exists():
1738
print("There is at least one object in some_queryset")
1603
1740
Which will be faster than::
1606
print("There is at least one object in some_query_set")
1743
print("There is at least one object in some_queryset")
1608
1745
... but not by a large degree (hence needing a large queryset for efficiency
1611
Additionally, if a ``some_query_set`` has not yet been evaluated, but you know
1612
that it will be at some point, then using ``some_query_set.exists()`` will do
1748
Additionally, if a ``some_queryset`` has not yet been evaluated, but you know
1749
that it will be at some point, then using ``some_queryset.exists()`` will do
1613
1750
more overall work (one query for the existence check plus an extra one to later
1614
retrieve the results) than simply using ``bool(some_query_set)``, which
1751
retrieve the results) than simply using ``bool(some_queryset)``, which
1615
1752
retrieves the results and then checks if any were returned.
2130
2280
2 of the week), regardless of the month or year in which it occurs. Week days
2131
2281
are indexed with day 1 being Sunday and day 7 being Saturday.
2135
When :doc:`time zone support </topics/i18n/timezones>` is enabled, Django
2136
uses UTC in the database connection, which means the ``year``, ``month``,
2137
``day`` and ``week_day`` lookups are performed in UTC. This is a known
2138
limitation of the current implementation.
2283
When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
2284
current time zone before filtering. This requires :ref:`time zone definitions
2285
in the database <database-time-zone-definitions>`.
2287
.. fieldlookup:: hour
2292
.. versionadded:: 1.6
2294
For datetime fields, an exact hour match. Takes an integer between 0 and 23.
2298
Event.objects.filter(timestamp__hour=23)
2302
SELECT ... WHERE EXTRACT('hour' FROM timestamp) = '23';
2304
(The exact SQL syntax varies for each database engine.)
2306
When :setting:`USE_TZ` is ``True``, values are converted to the current time
2307
zone before filtering.
2309
.. fieldlookup:: minute
2314
.. versionadded:: 1.6
2316
For datetime fields, an exact minute match. Takes an integer between 0 and 59.
2320
Event.objects.filter(timestamp__minute=29)
2324
SELECT ... WHERE EXTRACT('minute' FROM timestamp) = '29';
2326
(The exact SQL syntax varies for each database engine.)
2328
When :setting:`USE_TZ` is ``True``, values are converted to the current time
2329
zone before filtering.
2331
.. fieldlookup:: second
2336
.. versionadded:: 1.6
2338
For datetime fields, an exact second match. Takes an integer between 0 and 59.
2342
Event.objects.filter(timestamp__second=31)
2346
SELECT ... WHERE EXTRACT('second' FROM timestamp) = '31';
2348
(The exact SQL syntax varies for each database engine.)
2350
When :setting:`USE_TZ` is ``True``, values are converted to the current time
2351
zone before filtering.
2140
2353
.. fieldlookup:: isnull