~ubuntu-branches/debian/sid/python-django/sid

« back to all changes in this revision

Viewing changes to docs/ref/models/querysets.txt

  • Committer: Package Import Robot
  • Author(s): Luke Faraone
  • Date: 2013-11-07 15:33:49 UTC
  • mfrom: (1.3.12)
  • Revision ID: package-import@ubuntu.com-20131107153349-e31sc149l2szs3jb
Tags: 1.6-1
* New upstream version. Closes: #557474, #724637.
* python-django now also suggests the installation of ipython,
  bpython, python-django-doc, and libgdal1.
  Closes: #636511, #686333, #704203
* Set package maintainer to Debian Python Modules Team.
* Bump standards version to 3.9.5, no changes needed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
232
232
For example, if you were manipulating a list of blogs, you may want
233
233
to determine how many entries have been made in each blog::
234
234
 
 
235
    >>> from django.db.models import Count
235
236
    >>> q = Blog.objects.annotate(Count('entry'))
236
237
    # The name of the first blog
237
238
    >>> q[0].name
335
336
:attr:`.QuerySet.ordered` attribute, which will be ``True`` if the
336
337
``QuerySet`` has been ordered in any way.
337
338
 
 
339
.. warning::
 
340
 
 
341
    Ordering is not a free operation. Each field you add to the ordering
 
342
    incurs a cost to your database. Each foreign key you add will
 
343
    implicitly include all of its default orderings as well.
 
344
 
338
345
reverse
339
346
~~~~~~~
340
347
 
394
401
    :meth:`values()` together, be careful when ordering by fields not in the
395
402
    :meth:`values()` call.
396
403
 
397
 
.. versionadded:: 1.4
398
 
 
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.
402
 
 
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.
407
 
 
408
 
.. note::
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.
410
410
 
411
411
.. note::
412
412
    When you specify field names, you *must* provide an ``order_by()`` in the
417
417
    value in column ``a``. If you don't specify an order, you'll get some
418
418
    arbitrary row.
419
419
 
420
 
Examples::
 
420
Examples (those after the first will only work on PostgreSQL)::
421
421
 
422
422
    >>> Author.objects.distinct()
423
423
    [...]
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.
566
566
 
 
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
the queryset.
 
571
 
567
572
dates
568
573
~~~~~
569
574
 
570
575
.. method:: dates(field, kind, order='ASC')
571
576
 
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``.
575
 
 
576
 
``field`` should be the name of a ``DateField`` or ``DateTimeField`` of your
577
 
model.
 
578
:class:`datetime.date` objects representing all available dates of a
 
579
particular kind within the contents of the ``QuerySet``.
 
580
 
 
581
.. versionchanged:: 1.6
 
582
 
 
583
    ``dates`` used to return a list of :class:`datetime.datetime` objects.
 
584
 
 
585
``field`` should be the name of a ``DateField`` of your model.
 
586
 
 
587
.. versionchanged:: 1.6
 
588
 
 
589
    ``dates`` used to accept operating on a ``DateTimeField``.
578
590
 
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
581
593
``type``.
582
594
 
583
595
* ``"year"`` returns a list of all distinct year values for the field.
592
604
Examples::
593
605
 
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)]
604
 
 
605
 
.. warning::
606
 
 
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)]
 
616
 
 
617
datetimes
 
618
~~~~~~~~~
 
619
 
 
620
.. versionadded:: 1.6
 
621
 
 
622
.. method:: datetimes(field, kind, order='ASC', tzinfo=None)
 
623
 
 
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``.
 
627
 
 
628
``field`` should be the name of a ``DateTimeField`` of your model.
 
629
 
 
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``.
 
633
 
 
634
``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or
 
635
``'DESC'``. This specifies how to order the results.
 
636
 
 
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
 
642
``False``.
 
643
 
 
644
.. _database-time-zone-definitions:
 
645
 
 
646
.. note::
 
647
 
 
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:
 
651
 
 
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`_.
 
657
 
 
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
610
662
 
611
663
none
612
664
~~~~
613
665
 
614
666
.. method:: none()
615
667
 
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``.
620
671
 
621
672
Examples::
622
673
 
623
674
    >>> Entry.objects.none()
624
675
    []
 
676
    >>> from django.db.models.query import EmptyQuerySet
 
677
    >>> isinstance(Entry.objects.none(), EmptyQuerySet)
 
678
    True
625
679
 
626
680
all
627
681
~~~
665
719
``select_related()`` follows foreign keys as far as possible. If you have the
666
720
following models::
667
721
 
 
722
    from django.db import models
 
723
 
668
724
    class City(models.Model):
669
725
        # ...
670
726
        pass
737
793
is defined. Instead of specifying the field name, use the :attr:`related_name
738
794
<django.db.models.ForeignKey.related_name>` for the field on the related object.
739
795
 
 
796
.. versionadded:: 1.6
 
797
 
 
798
If you need to clear the list of related fields added by past calls of
 
799
``select_related`` on a ``QuerySet``, you can pass ``None`` as a parameter::
 
800
 
 
801
   >>> without_relations = queryset.select_related(None)
 
802
 
740
803
.. deprecated:: 1.5
741
804
    The ``depth`` parameter to ``select_related()`` has been deprecated. You
742
805
    should replace it with the use of the ``(*fields)`` listing specific
756
819
 
757
820
.. method:: prefetch_related(*lookups)
758
821
 
759
 
.. versionadded:: 1.4
760
 
 
761
822
Returns a ``QuerySet`` that will automatically retrieve, in a single batch,
762
823
related objects for each of the specified lookups.
763
824
 
765
826
stop the deluge of database queries that is caused by accessing related objects,
766
827
but the strategy is quite different.
767
828
 
768
 
``select_related`` works by creating a SQL join and including the fields of the
 
829
``select_related`` works by creating an SQL join and including the fields of the
769
830
related object in the ``SELECT`` statement. For this reason, ``select_related``
770
831
gets the related objects in the same database query. However, to avoid the much
771
832
larger result set that would result from joining across a 'many' relationship,
782
843
 
783
844
For example, suppose you have these models::
784
845
 
 
846
    from django.db import models
 
847
 
785
848
    class Topping(models.Model):
786
849
        name = models.CharField(max_length=30)
787
850
 
789
852
        name = models.CharField(max_length=50)
790
853
        toppings = models.ManyToManyField(Topping)
791
854
 
 
855
        # On Python 3: def __str__(self):
792
856
        def __unicode__(self):
793
857
            return u"%s (%s)" % (self.name, u", ".join([topping.name
794
858
                                                        for topping in self.toppings.all()]))
892
956
additional queries on the ``ContentType`` table if the relevant rows have not
893
957
already been fetched.
894
958
 
895
 
``prefetch_related`` in most cases will be implemented using a SQL query that
 
959
``prefetch_related`` in most cases will be implemented using an SQL query that
896
960
uses the 'IN' operator. This means that for a large ``QuerySet`` a large 'IN' clause
897
961
could be generated, which, depending on the database, might have performance
898
962
problems of its own when it comes to parsing or executing the SQL query. Always
1112
1176
 
1113
1177
.. versionchanged:: 1.5
1114
1178
 
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.
1120
1184
 
1121
1185
.. note::
1122
1186
 
1184
1248
    # existing set of fields).
1185
1249
    Entry.objects.defer("body").only("headline", "body")
1186
1250
 
1187
 
.. versionchanged:: 1.5
1188
 
 
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.
 
1253
options.
1193
1254
 
1194
1255
.. versionchanged:: 1.5
1195
1256
 
1196
 
.. note::
1197
 
 
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.
 
1259
 
 
1260
    .. note::
 
1261
 
 
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.
1201
1265
 
1202
1266
using
1203
1267
~~~~~
1222
1286
 
1223
1287
.. method:: select_for_update(nowait=False)
1224
1288
 
1225
 
.. versionadded:: 1.4
1226
 
 
1227
1289
Returns a queryset that will lock rows until the end of the transaction,
1228
1290
generating a ``SELECT ... FOR UPDATE`` SQL statement on supported databases.
1229
1291
 
1242
1304
another transaction, :exc:`~django.db.DatabaseError` will be raised when the
1243
1305
queryset is evaluated.
1244
1306
 
1245
 
Note that using ``select_for_update()`` will cause the current transaction to be
1246
 
considered dirty, if under transaction management. This is to ensure that
1247
 
Django issues a ``COMMIT`` or ``ROLLBACK``, releasing any locks held by the
1248
 
``SELECT FOR UPDATE``.
1249
 
 
1250
1307
Currently, the ``postgresql_psycopg2``, ``oracle``, and ``mysql`` database
1251
1308
backends support ``select_for_update()``. However, MySQL has no support for the
1252
1309
``nowait`` argument. Obviously, users of external third-party backends should
1328
1385
 
1329
1386
.. method:: get_or_create(**kwargs)
1330
1387
 
1331
 
A convenience method for looking up an object with the given ``kwargs``,
1332
 
creating one if necessary.
 
1388
A convenience method for looking up an object with the given ``kwargs`` (may be
 
1389
empty if your model has defaults for all fields), creating one if necessary.
 
1390
 
 
1391
.. versionchanged:: 1.6
 
1392
 
 
1393
    Older versions of Django required ``kwargs``.
1333
1394
 
1334
1395
Returns a tuple of ``(object, created)``, where ``object`` is the retrieved or
1335
1396
created object and ``created`` is a boolean specifying whether a new object was
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.
1405
1466
 
1406
1467
.. _Safe methods: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
1407
1468
 
 
1469
.. warning::
 
1470
 
 
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.
 
1475
 
 
1476
  Being the following models::
 
1477
 
 
1478
      class Chapter(models.Model):
 
1479
          title = models.CharField(max_length=255, unique=True)
 
1480
 
 
1481
      class Book(models.Model):
 
1482
          title = models.CharField(max_length=256)
 
1483
          chapters = models.ManyToManyField(Chapter)
 
1484
 
 
1485
  You can use ``get_or_create()`` through Book's chapters field, but it only
 
1486
  fetches inside the context of that book::
 
1487
 
 
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
 
1497
 
 
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.
 
1502
 
 
1503
 
1408
1504
bulk_create
1409
1505
~~~~~~~~~~~
1410
1506
 
1411
1507
.. method:: bulk_create(objs, batch_size=None)
1412
1508
 
1413
 
.. versionadded:: 1.4
1414
 
 
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
1417
1511
are)::
1435
1529
where the default is such that at maximum 999 variables per query is used.
1436
1530
 
1437
1531
.. versionadded:: 1.5
 
1532
 
1438
1533
    The ``batch_size`` parameter was added in version 1.5.
1439
1534
 
1440
1535
count
1527
1622
 
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.
1532
 
 
1533
 
Like :meth:`get()`, ``latest()`` raises
1534
 
:exc:`~django.core.exceptions.DoesNotExist` if there is no object with the given
1535
 
parameters.
1536
 
 
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.
 
1627
 
 
1628
Like :meth:`get()`, ``earliest()`` and ``latest()`` raise
 
1629
:exc:`~django.core.exceptions.DoesNotExist` if there is no object with the
 
1630
given parameters.
 
1631
 
 
1632
Note that ``earliest()`` and ``latest()`` exist purely for convenience and
 
1633
readability.
 
1634
 
 
1635
earliest
 
1636
~~~~~~~~
 
1637
 
 
1638
.. method:: earliest(field_name=None)
 
1639
 
 
1640
.. versionadded:: 1.6
 
1641
 
 
1642
Works otherwise like :meth:`~django.db.models.query.QuerySet.latest` except
 
1643
the direction is changed.
 
1644
 
 
1645
first
 
1646
~~~~~
 
1647
.. method:: first()
 
1648
 
 
1649
.. versionadded:: 1.6
 
1650
 
 
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.
 
1654
 
 
1655
Example::
 
1656
 
 
1657
    p = Article.objects.order_by('title', 'pub_date').first()
 
1658
 
 
1659
Note that ``first()`` is a convenience method, the following code sample is
 
1660
equivalent to the above example::
 
1661
 
 
1662
    try:
 
1663
        p = Article.objects.order_by('title', 'pub_date')[0]
 
1664
    except IndexError:
 
1665
        p = None
 
1666
 
 
1667
last
 
1668
~~~~
 
1669
.. method:: last()
 
1670
 
 
1671
.. versionadded:: 1.6
 
1672
 
 
1673
Works like  :meth:`first()`, but returns the last object in the queryset.
1538
1674
 
1539
1675
aggregate
1540
1676
~~~~~~~~~
1556
1692
For example, when you are working with blog entries, you may want to know the
1557
1693
number of authors that have contributed blog entries::
1558
1694
 
 
1695
    >>> from django.db.models import Count
1559
1696
    >>> q = Blog.objects.aggregate(Count('entry'))
1560
1697
    {'entry__count': 16}
1561
1698
 
1586
1723
(e.g. ``primary_key``) is a member of a :class:`.QuerySet` is::
1587
1724
 
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")
1591
1728
 
1592
1729
Which will be faster than the following which requires evaluating and iterating
1593
1730
through the entire queryset::
1594
1731
 
1595
 
    if entry in some_query_set:
 
1732
    if entry in some_queryset:
1596
1733
       print("Entry contained in QuerySet")
1597
1734
 
1598
1735
And to find whether a queryset contains any items::
1599
1736
 
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")
1602
1739
 
1603
1740
Which will be faster than::
1604
1741
 
1605
 
    if some_query_set:
1606
 
        print("There is at least one object in some_query_set")
 
1742
    if some_queryset:
 
1743
        print("There is at least one object in some_queryset")
1607
1744
 
1608
1745
... but not by a large degree (hence needing a large queryset for efficiency
1609
1746
gains).
1610
1747
 
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.
1616
1753
 
1617
1754
update
1725
1862
(including cascaded deletions).
1726
1863
 
1727
1864
.. versionadded:: 1.5
1728
 
    Allow fast-path deletion of objects
 
1865
 
 
1866
    Allow fast-path deletion of objects.
1729
1867
 
1730
1868
Django needs to fetch objects into memory to send signals and handle cascades.
1731
1869
However, if there are no cascades and no signals, then Django may take a
2032
2170
 
2033
2171
Example::
2034
2172
 
 
2173
    import datetime
2035
2174
    start_date = datetime.date(2005, 1, 1)
2036
2175
    end_date = datetime.date(2005, 3, 31)
2037
2176
    Entry.objects.filter(pub_date__range=(start_date, end_date))
2059
2198
year
2060
2199
~~~~
2061
2200
 
2062
 
For date/datetime fields, exact year match. Takes a four-digit year.
 
2201
For date and datetime fields, an exact year match. Takes an integer year.
2063
2202
 
2064
2203
Example::
2065
2204
 
2071
2210
 
2072
2211
(The exact SQL syntax varies for each database engine.)
2073
2212
 
 
2213
When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
 
2214
current time zone before filtering.
 
2215
 
2074
2216
.. fieldlookup:: month
2075
2217
 
2076
2218
month
2089
2231
 
2090
2232
(The exact SQL syntax varies for each database engine.)
2091
2233
 
 
2234
When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
 
2235
current time zone before filtering. This requires :ref:`time zone definitions
 
2236
in the database <database-time-zone-definitions>`.
 
2237
 
2092
2238
.. fieldlookup:: day
2093
2239
 
2094
2240
day
2095
2241
~~~
2096
2242
 
2097
 
For date and datetime fields, an exact day match.
 
2243
For date and datetime fields, an exact day match. Takes an integer day.
2098
2244
 
2099
2245
Example::
2100
2246
 
2109
2255
Note this will match any record with a pub_date on the third day of the month,
2110
2256
such as January 3, July 3, etc.
2111
2257
 
 
2258
When :setting:`USE_TZ` is ``True``, datetime fields are converted to the
 
2259
current time zone before filtering. This requires :ref:`time zone definitions
 
2260
in the database <database-time-zone-definitions>`.
 
2261
 
2112
2262
.. fieldlookup:: week_day
2113
2263
 
2114
2264
week_day
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.
2132
2282
 
2133
 
.. warning::
2134
 
 
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>`.
 
2286
 
 
2287
.. fieldlookup:: hour
 
2288
 
 
2289
hour
 
2290
~~~~
 
2291
 
 
2292
.. versionadded:: 1.6
 
2293
 
 
2294
For datetime fields, an exact hour match. Takes an integer between 0 and 23.
 
2295
 
 
2296
Example::
 
2297
 
 
2298
    Event.objects.filter(timestamp__hour=23)
 
2299
 
 
2300
SQL equivalent::
 
2301
 
 
2302
    SELECT ... WHERE EXTRACT('hour' FROM timestamp) = '23';
 
2303
 
 
2304
(The exact SQL syntax varies for each database engine.)
 
2305
 
 
2306
When :setting:`USE_TZ` is ``True``, values are converted to the current time
 
2307
zone before filtering.
 
2308
 
 
2309
.. fieldlookup:: minute
 
2310
 
 
2311
minute
 
2312
~~~~~~
 
2313
 
 
2314
.. versionadded:: 1.6
 
2315
 
 
2316
For datetime fields, an exact minute match. Takes an integer between 0 and 59.
 
2317
 
 
2318
Example::
 
2319
 
 
2320
    Event.objects.filter(timestamp__minute=29)
 
2321
 
 
2322
SQL equivalent::
 
2323
 
 
2324
    SELECT ... WHERE EXTRACT('minute' FROM timestamp) = '29';
 
2325
 
 
2326
(The exact SQL syntax varies for each database engine.)
 
2327
 
 
2328
When :setting:`USE_TZ` is ``True``, values are converted to the current time
 
2329
zone before filtering.
 
2330
 
 
2331
.. fieldlookup:: second
 
2332
 
 
2333
second
 
2334
~~~~~~
 
2335
 
 
2336
.. versionadded:: 1.6
 
2337
 
 
2338
For datetime fields, an exact second match. Takes an integer between 0 and 59.
 
2339
 
 
2340
Example::
 
2341
 
 
2342
    Event.objects.filter(timestamp__second=31)
 
2343
 
 
2344
SQL equivalent::
 
2345
 
 
2346
    SELECT ... WHERE EXTRACT('second' FROM timestamp) = '31';
 
2347
 
 
2348
(The exact SQL syntax varies for each database engine.)
 
2349
 
 
2350
When :setting:`USE_TZ` is ``True``, values are converted to the current time
 
2351
zone before filtering.
2139
2352
 
2140
2353
.. fieldlookup:: isnull
2141
2354
 
2238
2451
aggregate functions, see
2239
2452
:doc:`the topic guide on aggregation </topics/db/aggregation>`.
2240
2453
 
 
2454
.. warning::
 
2455
 
 
2456
    SQLite can't handle aggregation on date/time fields out of the box.
 
2457
    This is because there are no native date/time fields in SQLite and Django
 
2458
    currently emulates these features using a text field. Attempts to use
 
2459
    aggregation on date/time fields in SQLite will raise
 
2460
    ``NotImplementedError``.
 
2461
 
2241
2462
Avg
2242
2463
~~~
2243
2464