forked from django/django
-
Notifications
You must be signed in to change notification settings - Fork 0
/
querysets.txt
3781 lines (2638 loc) · 138 KB
/
querysets.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
==========================
``QuerySet`` API reference
==========================
.. currentmodule:: django.db.models.query
This document describes the details of the ``QuerySet`` API. It builds on the
material presented in the :doc:`model </topics/db/models>` and :doc:`database
query </topics/db/queries>` guides, so you'll probably want to read and
understand those documents before reading this one.
Throughout this reference we'll use the :ref:`example Weblog models
<queryset-model-example>` presented in the :doc:`database query guide
</topics/db/queries>`.
.. _when-querysets-are-evaluated:
When ``QuerySet``\s are evaluated
=================================
Internally, a ``QuerySet`` can be constructed, filtered, sliced, and generally
passed around without actually hitting the database. No database activity
actually occurs until you do something to evaluate the queryset.
You can evaluate a ``QuerySet`` in the following ways:
* **Iteration.** A ``QuerySet`` is iterable, and it executes its database
query the first time you iterate over it. For example, this will print
the headline of all entries in the database::
for e in Entry.objects.all():
print(e.headline)
Note: Don't use this if all you want to do is determine if at least one
result exists. It's more efficient to use :meth:`~QuerySet.exists`.
* **Slicing.** As explained in :ref:`limiting-querysets`, a ``QuerySet`` can
be sliced, using Python's array-slicing syntax. Slicing an unevaluated
``QuerySet`` usually returns another unevaluated ``QuerySet``, but Django
will execute the database query if you use the "step" parameter of slice
syntax, and will return a list. Slicing a ``QuerySet`` that has been
evaluated also returns a list.
Also note that even though slicing an unevaluated ``QuerySet`` returns
another unevaluated ``QuerySet``, modifying it further (e.g., adding
more filters, or modifying ordering) is not allowed, since that does not
translate well into SQL and it would not have a clear meaning either.
* **Pickling/Caching.** See the following section for details of what
is involved when `pickling QuerySets`_. The important thing for the
purposes of this section is that the results are read from the database.
* **repr().** A ``QuerySet`` is evaluated when you call ``repr()`` on it.
This is for convenience in the Python interactive interpreter, so you can
immediately see your results when using the API interactively.
* **len().** A ``QuerySet`` is evaluated when you call ``len()`` on it.
This, as you might expect, returns the length of the result list.
Note: If you only need to determine the number of records in the set (and
don't need the actual objects), it's much more efficient to handle a count
at the database level using SQL's ``SELECT COUNT(*)``. Django provides a
:meth:`~QuerySet.count` method for precisely this reason.
* **list().** Force evaluation of a ``QuerySet`` by calling ``list()`` on
it. For example::
entry_list = list(Entry.objects.all())
* **bool().** Testing a ``QuerySet`` in a boolean context, such as using
``bool()``, ``or``, ``and`` or an ``if`` statement, will cause the query
to be executed. If there is at least one result, the ``QuerySet`` is
``True``, otherwise ``False``. For example::
if Entry.objects.filter(headline="Test"):
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`.
.. _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
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.
If you only want to pickle the necessary information to recreate the
``QuerySet`` from the database at a later time, pickle the ``query`` attribute
of the ``QuerySet``. You can then recreate the original ``QuerySet`` (without
any results loaded) using some code like this::
>>> import pickle
>>> query = pickle.loads(s) # Assuming 's' is the pickled string.
>>> qs = MyModel.objects.all()
>>> qs.query = query # Restore the original 'query'.
The ``query`` attribute is an opaque object. It represents the internals of
the query construction and is not part of the public API. However, it is safe
(and fully supported) to pickle and unpickle the attribute's contents as
described here.
.. admonition:: Restrictions on ``QuerySet.values_list()``
If you recreate :meth:`QuerySet.values_list` using the pickled ``query``
attribute, it will be converted to :meth:`QuerySet.values`::
>>> import pickle
>>> qs = Blog.objects.values_list('id', 'name')
>>> qs
<QuerySet [(1, 'Beatles Blog')]>
>>> reloaded_qs = Blog.objects.all()
>>> reloaded_qs.query = pickle.loads(pickle.dumps(qs.query))
>>> reloaded_qs
<QuerySet [{'id': 1, 'name': 'Beatles Blog'}]>
.. admonition:: You can't share pickles between versions
Pickles of ``QuerySets`` are only valid for the version of Django that
was used to generate them. If you generate a pickle using Django
version N, there is no guarantee that pickle will be readable with
Django version N+1. Pickles should not be used as part of a long-term
archival strategy.
Since pickle compatibility errors can be difficult to diagnose, such as
silently corrupted objects, a ``RuntimeWarning`` is raised when you try to
unpickle a queryset in a Django version that is different than the one in
which it was pickled.
.. _queryset-api:
``QuerySet`` API
================
Here's the formal declaration of a ``QuerySet``:
.. class:: QuerySet(model=None, query=None, using=None, hints=None)
Usually when you'll interact with a ``QuerySet`` you'll use it by
:ref:`chaining filters <chaining-filters>`. To make this work, most
``QuerySet`` methods return new querysets. These methods are covered in
detail later in this section.
The ``QuerySet`` class has two public attributes you can use for
introspection:
.. attribute:: ordered
``True`` if the ``QuerySet`` is ordered — i.e. has an
:meth:`order_by()` clause or a default ordering on the model.
``False`` otherwise.
.. attribute:: db
The database that will be used if this query is executed now.
.. note::
The ``query`` parameter to :class:`QuerySet` exists so that specialized
query subclasses can reconstruct internal query state. The value of the
parameter is an opaque representation of that query state and is not
part of a public API.
.. currentmodule:: django.db.models.query.QuerySet
Methods that return new ``QuerySet``\s
--------------------------------------
Django provides a range of ``QuerySet`` refinement methods that modify either
the types of results returned by the ``QuerySet`` or the way its SQL query is
executed.
``filter()``
~~~~~~~~~~~~
.. method:: filter(**kwargs)
Returns a new ``QuerySet`` containing objects that match the given lookup
parameters.
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>`.
``exclude()``
~~~~~~~~~~~~~
.. method:: exclude(**kwargs)
Returns a new ``QuerySet`` containing objects that do *not* match the given
lookup parameters.
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, and the whole thing is enclosed in a ``NOT()``.
This example excludes all entries whose ``pub_date`` is later than 2005-1-3
AND whose ``headline`` is "Hello"::
Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3), headline='Hello')
In SQL terms, that evaluates to:
.. code-block:: sql
SELECT ...
WHERE NOT (pub_date > '2005-1-3' AND headline = 'Hello')
This example excludes all entries whose ``pub_date`` is later than 2005-1-3
OR whose headline is "Hello"::
Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3)).exclude(headline='Hello')
In SQL terms, that evaluates to:
.. code-block:: sql
SELECT ...
WHERE NOT pub_date > '2005-1-3'
AND NOT headline = 'Hello'
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>`.
``annotate()``
~~~~~~~~~~~~~~
.. method:: annotate(*args, **kwargs)
Annotates each object in the ``QuerySet`` with the provided list of :doc:`query
expressions </ref/models/expressions>`. An expression may be a simple value, a
reference to a field on the model (or any related models), or an aggregate
expression (averages, sums, etc.) that has been computed over the objects that
are related to the objects in the ``QuerySet``.
Each argument to ``annotate()`` is an annotation that will be added
to each object in the ``QuerySet`` that is returned.
The aggregation functions that are provided by Django are described
in `Aggregation Functions`_ below.
Annotations specified using keyword arguments will use the keyword as
the alias for the annotation. Anonymous arguments will have an alias
generated for them based upon the name of the aggregate function and
the model field that is being aggregated. Only aggregate expressions
that reference a single field can be anonymous arguments. Everything
else must be a keyword argument.
For example, if you were manipulating a list of blogs, you may want
to determine how many entries have been made in each blog::
>>> from django.db.models import Count
>>> q = Blog.objects.annotate(Count('entry'))
# The name of the first blog
>>> q[0].name
'Blogasaurus'
# The number of entries on the first blog
>>> q[0].entry__count
42
The ``Blog`` model doesn't define an ``entry__count`` attribute by itself,
but by using a keyword argument to specify the aggregate function, you can
control the name of the annotation::
>>> q = Blog.objects.annotate(number_of_entries=Count('entry'))
# The number of entries on the first blog, using the name provided
>>> q[0].number_of_entries
42
For an in-depth discussion of aggregation, see :doc:`the topic guide on
Aggregation </topics/db/aggregation>`.
``alias()``
~~~~~~~~~~~
.. method:: alias(*args, **kwargs)
.. versionadded:: 3.2
Same as :meth:`annotate`, but instead of annotating objects in the
``QuerySet``, saves the expression for later reuse with other ``QuerySet``
methods. This is useful when the result of the expression itself is not needed
but it is used for filtering, ordering, or as a part of a complex expression.
Not selecting the unused value removes redundant work from the database which
should result in better performance.
For example, if you want to find blogs with more than 5 entries, but are not
interested in the exact number of entries, you could do this::
>>> from django.db.models import Count
>>> blogs = Blog.objects.alias(entries=Count('entry')).filter(entries__gt=5)
``alias()`` can be used in conjunction with :meth:`annotate`, :meth:`exclude`,
:meth:`filter`, :meth:`order_by`, and :meth:`update`. To use aliased expression
with other methods (e.g. :meth:`aggregate`), you must promote it to an
annotation::
Blog.objects.alias(entries=Count('entry')).annotate(
entries=F('entries'),
).aggregate(Sum('entries'))
:meth:`filter` and :meth:`order_by` can take expressions directly, but
expression construction and usage often does not happen in the same place (for
example, ``QuerySet`` method creates expressions, for later use in views).
``alias()`` allows building complex expressions incrementally, possibly
spanning multiple methods and modules, refer to the expression parts by their
aliases and only use :meth:`annotate` for the final result.
``order_by()``
~~~~~~~~~~~~~~
.. method:: order_by(*fields)
By default, results returned by a ``QuerySet`` are ordered by the ordering
tuple given by the ``ordering`` option in the model's ``Meta``. You can
override this on a per-``QuerySet`` basis by using the ``order_by`` method.
Example::
Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')
The result above will be ordered by ``pub_date`` descending, then by
``headline`` ascending. The negative sign in front of ``"-pub_date"`` indicates
*descending* order. Ascending order is implied. To order randomly, use ``"?"``,
like so::
Entry.objects.order_by('?')
Note: ``order_by('?')`` queries may be expensive and slow, depending on the
database backend you're using.
To order by a field in a different model, use the same syntax as when you are
querying across model relations. That is, the name of the field, followed by a
double underscore (``__``), followed by the name of the field in the new model,
and so on for as many models as you want to join. For example::
Entry.objects.order_by('blog__name', 'headline')
If you try to order by a field that is a relation to another model, Django will
use the default ordering on the related model, or order by the related model's
primary key if there is no :attr:`Meta.ordering
<django.db.models.Options.ordering>` specified. For example, since the ``Blog``
model has no default ordering specified::
Entry.objects.order_by('blog')
...is identical to::
Entry.objects.order_by('blog__id')
If ``Blog`` had ``ordering = ['name']``, then the first queryset would be
identical to::
Entry.objects.order_by('blog__name')
You can also order by :doc:`query expressions </ref/models/expressions>` by
calling :meth:`~.Expression.asc` or :meth:`~.Expression.desc` on the
expression::
Entry.objects.order_by(Coalesce('summary', 'headline').desc())
:meth:`~.Expression.asc` and :meth:`~.Expression.desc` have arguments
(``nulls_first`` and ``nulls_last``) that control how null values are sorted.
Be cautious when ordering by fields in related models if you are also using
:meth:`distinct()`. See the note in :meth:`distinct` for an explanation of how
related model ordering can change the expected results.
.. note::
It is permissible to specify a multi-valued field to order the results by
(for example, a :class:`~django.db.models.ManyToManyField` field, or the
reverse relation of a :class:`~django.db.models.ForeignKey` field).
Consider this case::
class Event(Model):
parent = models.ForeignKey(
'self',
on_delete=models.CASCADE,
related_name='children',
)
date = models.DateField()
Event.objects.order_by('children__date')
Here, there could potentially be multiple ordering data for each ``Event``;
each ``Event`` with multiple ``children`` will be returned multiple times
into the new ``QuerySet`` that ``order_by()`` creates. In other words,
using ``order_by()`` on the ``QuerySet`` could return more items than you
were working on to begin with - which is probably neither expected nor
useful.
Thus, take care when using multi-valued field to order the results. **If**
you can be sure that there will only be one ordering piece of data for each
of the items you're ordering, this approach should not present problems. If
not, make sure the results are what you expect.
There's no way to specify whether ordering should be case sensitive. With
respect to case-sensitivity, Django will order results however your database
backend normally orders them.
You can order by a field converted to lowercase with
:class:`~django.db.models.functions.Lower` which will achieve case-consistent
ordering::
Entry.objects.order_by(Lower('headline').desc())
If you don't want any ordering to be applied to a query, not even the default
ordering, call :meth:`order_by()` with no parameters.
You can tell if a query is ordered or not by checking the
:attr:`.QuerySet.ordered` attribute, which will be ``True`` if the
``QuerySet`` has been ordered in any way.
Each ``order_by()`` call will clear any previous ordering. For example, this
query will be ordered by ``pub_date`` and not ``headline``::
Entry.objects.order_by('headline').order_by('pub_date')
.. warning::
Ordering is not a free operation. Each field you add to the ordering
incurs a cost to your database. Each foreign key you add will
implicitly include all of its default orderings as well.
If a query doesn't have an ordering specified, results are returned from
the database in an unspecified order. A particular ordering is guaranteed
only when ordering by a set of fields that uniquely identify each object in
the results. For example, if a ``name`` field isn't unique, ordering by it
won't guarantee objects with the same name always appear in the same order.
``reverse()``
~~~~~~~~~~~~~
.. method:: reverse()
Use the ``reverse()`` method to reverse the order in which a queryset's
elements are returned. Calling ``reverse()`` a second time restores the
ordering back to the normal direction.
To retrieve the "last" five items in a queryset, you could do this::
my_queryset.reverse()[:5]
Note that this is not quite the same as slicing from the end of a sequence in
Python. The above example will return the last item first, then the
penultimate item and so on. If we had a Python sequence and looked at
``seq[-5:]``, we would see the fifth-last item first. Django doesn't support
that mode of access (slicing from the end), because it's not possible to do it
efficiently in SQL.
Also, note that ``reverse()`` should generally only be called on a ``QuerySet``
which has a defined ordering (e.g., when querying against a model which defines
a default ordering, or when using :meth:`order_by()`). If no such ordering is
defined for a given ``QuerySet``, calling ``reverse()`` on it has no real
effect (the ordering was undefined prior to calling ``reverse()``, and will
remain undefined afterward).
``distinct()``
~~~~~~~~~~~~~~
.. method:: distinct(*fields)
Returns a new ``QuerySet`` that uses ``SELECT DISTINCT`` in its SQL query. This
eliminates duplicate rows from the query results.
By default, a ``QuerySet`` will not eliminate duplicate rows. In practice, this
is rarely a problem, because simple queries such as ``Blog.objects.all()``
don't introduce the possibility of duplicate result rows. However, if your
query spans multiple tables, it's possible to get duplicate results when a
``QuerySet`` is evaluated. That's when you'd use ``distinct()``.
.. note::
Any fields used in an :meth:`order_by` call are included in the SQL
``SELECT`` columns. This can sometimes lead to unexpected results when used
in conjunction with ``distinct()``. If you order by fields from a related
model, those fields will be added to the selected columns and they may make
otherwise duplicate rows appear to be distinct. Since the extra columns
don't appear in the returned results (they are only there to support
ordering), it sometimes looks like non-distinct results are being returned.
Similarly, if you use a :meth:`values()` query to restrict the columns
selected, the columns used in any :meth:`order_by()` (or default model
ordering) will still be involved and may affect uniqueness of the results.
The moral here is that if you are using ``distinct()`` be careful about
ordering by related models. Similarly, when using ``distinct()`` and
:meth:`values()` together, be careful when ordering by fields not in the
:meth:`values()` call.
On PostgreSQL only, you can pass positional arguments (``*fields``) in order to
specify the names of fields to which the ``DISTINCT`` should apply. This
translates to a ``SELECT DISTINCT ON`` SQL query. Here's the difference. For a
normal ``distinct()`` call, the database compares *each* field in each row when
determining which rows are distinct. For a ``distinct()`` call with specified
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.
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
arbitrary row.
Examples (those after the first will only work on PostgreSQL)::
>>> Author.objects.distinct()
[...]
>>> Entry.objects.order_by('pub_date').distinct('pub_date')
[...]
>>> Entry.objects.order_by('blog').distinct('blog')
[...]
>>> Entry.objects.order_by('author', 'pub_date').distinct('author', 'pub_date')
[...]
>>> Entry.objects.order_by('blog__name', 'mod_date').distinct('blog__name', 'mod_date')
[...]
>>> Entry.objects.order_by('author', 'pub_date').distinct('author')
[...]
.. note::
Keep in mind that :meth:`order_by` uses any default related model ordering
that has been defined. You might have to explicitly order by the relation
``_id`` or referenced field to make sure the ``DISTINCT ON`` expressions
match those at the beginning of the ``ORDER BY`` clause. For example, if
the ``Blog`` model defined an :attr:`~django.db.models.Options.ordering` by
``name``::
Entry.objects.order_by('blog').distinct('blog')
...wouldn't work because the query would be ordered by ``blog__name`` thus
mismatching the ``DISTINCT ON`` expression. You'd have to explicitly order
by the relation ``_id`` field (``blog_id`` in this case) or the referenced
one (``blog__pk``) to make sure both expressions match.
``values()``
~~~~~~~~~~~~
.. method:: values(*fields, **expressions)
Returns a ``QuerySet`` that returns dictionaries, rather than model instances,
when used as an iterable.
Each of those dictionaries represents an object, with the keys corresponding to
the attribute names of model objects.
This example compares the dictionaries of ``values()`` with the normal model
objects::
# This list contains a Blog object.
>>> Blog.objects.filter(name__startswith='Beatles')
<QuerySet [<Blog: Beatles Blog>]>
# This list contains a dictionary.
>>> Blog.objects.filter(name__startswith='Beatles').values()
<QuerySet [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]>
The ``values()`` method takes optional positional arguments, ``*fields``, which
specify field names to which the ``SELECT`` should be limited. If you specify
the fields, each dictionary will contain only the field keys/values for the
fields you specify. If you don't specify the fields, each dictionary will
contain a key and value for every field in the database table.
Example::
>>> Blog.objects.values()
<QuerySet [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]>
>>> Blog.objects.values('id', 'name')
<QuerySet [{'id': 1, 'name': 'Beatles Blog'}]>
The ``values()`` method also takes optional keyword arguments,
``**expressions``, which are passed through to :meth:`annotate`::
>>> from django.db.models.functions import Lower
>>> Blog.objects.values(lower_name=Lower('name'))
<QuerySet [{'lower_name': 'beatles blog'}]>
You can use built-in and :doc:`custom lookups </howto/custom-lookups>` in
ordering. For example::
>>> from django.db.models import CharField
>>> from django.db.models.functions import Lower
>>> CharField.register_lookup(Lower)
>>> Blog.objects.values('name__lower')
<QuerySet [{'name__lower': 'beatles blog'}]>
An aggregate within a ``values()`` clause is applied before other arguments
within the same ``values()`` clause. If you need to group by another value,
add it to an earlier ``values()`` clause instead. For example::
>>> from django.db.models import Count
>>> Blog.objects.values('entry__authors', entries=Count('entry'))
<QuerySet [{'entry__authors': 1, 'entries': 20}, {'entry__authors': 1, 'entries': 13}]>
>>> Blog.objects.values('entry__authors').annotate(entries=Count('entry'))
<QuerySet [{'entry__authors': 1, 'entries': 33}]>
A few subtleties that are worth mentioning:
* If you have a field called ``foo`` that is a
:class:`~django.db.models.ForeignKey`, the default ``values()`` call
will return a dictionary key called ``foo_id``, since this is the name
of the hidden model attribute that stores the actual value (the ``foo``
attribute refers to the related model). When you are calling
``values()`` and passing in field names, you can pass in either ``foo``
or ``foo_id`` and you will get back the same thing (the dictionary key
will match the field name you passed in).
For example::
>>> Entry.objects.values()
<QuerySet [{'blog_id': 1, 'headline': 'First Entry', ...}, ...]>
>>> Entry.objects.values('blog')
<QuerySet [{'blog': 1}, ...]>
>>> Entry.objects.values('blog_id')
<QuerySet [{'blog_id': 1}, ...]>
* When using ``values()`` together with :meth:`distinct()`, be aware that
ordering can affect the results. See the note in :meth:`distinct` for
details.
* If you use a ``values()`` clause after an :meth:`extra()` call,
any fields defined by a ``select`` argument in the :meth:`extra()` must
be explicitly included in the ``values()`` call. Any :meth:`extra()` call
made after a ``values()`` call will have its extra selected fields
ignored.
* Calling :meth:`only()` and :meth:`defer()` after ``values()`` doesn't make
sense, so doing so will raise a ``TypeError``.
* Combining transforms and aggregates requires the use of two :meth:`annotate`
calls, either explicitly or as keyword arguments to :meth:`values`. As above,
if the transform has been registered on the relevant field type the first
:meth:`annotate` can be omitted, thus the following examples are equivalent::
>>> from django.db.models import CharField, Count
>>> from django.db.models.functions import Lower
>>> CharField.register_lookup(Lower)
>>> Blog.objects.values('entry__authors__name__lower').annotate(entries=Count('entry'))
<QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>
>>> Blog.objects.values(
... entry__authors__name__lower=Lower('entry__authors__name')
... ).annotate(entries=Count('entry'))
<QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>
>>> Blog.objects.annotate(
... entry__authors__name__lower=Lower('entry__authors__name')
... ).values('entry__authors__name__lower').annotate(entries=Count('entry'))
<QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>
It is useful when you know you're only going to need values from a small number
of the available fields and you won't need the functionality of a model
instance object. It's more efficient to select only the fields you need to use.
Finally, note that you can call ``filter()``, ``order_by()``, etc. after the
``values()`` call, that means that these two calls are identical::
Blog.objects.values().order_by('id')
Blog.objects.order_by('id').values()
The people who made Django prefer to put all the SQL-affecting methods first,
followed (optionally) by any output-affecting methods (such as ``values()``),
but it doesn't really matter. This is your chance to really flaunt your
individualism.
You can also refer to fields on related models with reverse relations through
``OneToOneField``, ``ForeignKey`` and ``ManyToManyField`` attributes::
>>> Blog.objects.values('name', 'entry__headline')
<QuerySet [{'name': 'My blog', 'entry__headline': 'An entry'},
{'name': 'My blog', 'entry__headline': 'Another entry'}, ...]>
.. warning::
Because :class:`~django.db.models.ManyToManyField` attributes and reverse
relations can have multiple related rows, including these can have a
multiplier effect on the size of your result set. This will be especially
pronounced if you include multiple such fields in your ``values()`` query,
in which case all possible combinations will be returned.
``values_list()``
~~~~~~~~~~~~~~~~~
.. method:: values_list(*fields, flat=False, named=False)
This is similar to ``values()`` except that instead of returning dictionaries,
it returns tuples when iterated over. Each tuple contains the value from the
respective field or expression passed into the ``values_list()`` call — so the
first item is the first field, etc. For example::
>>> Entry.objects.values_list('id', 'headline')
<QuerySet [(1, 'First entry'), ...]>
>>> from django.db.models.functions import Lower
>>> Entry.objects.values_list('id', Lower('headline'))
<QuerySet [(1, 'first entry'), ...]>
If you only pass in a single field, you can also pass in the ``flat``
parameter. If ``True``, this will mean the returned results are single values,
rather than one-tuples. An example should make the difference clearer::
>>> Entry.objects.values_list('id').order_by('id')
<QuerySet[(1,), (2,), (3,), ...]>
>>> Entry.objects.values_list('id', flat=True).order_by('id')
<QuerySet [1, 2, 3, ...]>
It is an error to pass in ``flat`` when there is more than one field.
You can pass ``named=True`` to get results as a
:func:`~python:collections.namedtuple`::
>>> Entry.objects.values_list('id', 'headline', named=True)
<QuerySet [Row(id=1, headline='First entry'), ...]>
Using a named tuple may make use of the results more readable, at the expense
of a small performance penalty for transforming the results into a named tuple.
If you don't pass any values to ``values_list()``, it will return all the
fields in the model, in the order they were declared.
A common need is to get a specific field value of a certain model instance. To
achieve that, use ``values_list()`` followed by a ``get()`` call::
>>> Entry.objects.values_list('headline', flat=True).get(pk=1)
'First entry'
``values()`` and ``values_list()`` are both intended as optimizations for a
specific use case: retrieving a subset of data without the overhead of creating
a model instance. This metaphor falls apart when dealing with many-to-many and
other multivalued relations (such as the one-to-many relation of a reverse
foreign key) because the "one row, one object" assumption doesn't hold.
For example, notice the behavior when querying across a
:class:`~django.db.models.ManyToManyField`::
>>> Author.objects.values_list('name', 'entry__headline')
<QuerySet [('Noam Chomsky', 'Impressions of Gaza'),
('George Orwell', 'Why Socialists Do Not Believe in Fun'),
('George Orwell', 'In Defence of English Cooking'),
('Don Quixote', None)]>
Authors with multiple entries appear multiple times and authors without any
entries have ``None`` for the entry headline.
Similarly, when querying a reverse foreign key, ``None`` appears for entries
not having any author::
>>> Entry.objects.values_list('authors')
<QuerySet [('Noam Chomsky',), ('George Orwell',), (None,)]>
``dates()``
~~~~~~~~~~~
.. method:: dates(field, kind, order='ASC')
Returns a ``QuerySet`` that evaluates to a list of :class:`datetime.date`
objects representing all available dates of a particular kind within the
contents of the ``QuerySet``.
``field`` should be the name of a ``DateField`` of your model.
``kind`` should be either ``"year"``, ``"month"``, ``"week"``, or ``"day"``.
Each :class:`datetime.date` object in the result list is "truncated" to the
given ``type``.
* ``"year"`` returns a list of all distinct year values for the field.
* ``"month"`` returns a list of all distinct year/month values for the
field.
* ``"week"`` returns a list of all distinct year/week values for the field. All
dates will be a Monday.
* ``"day"`` returns a list of all distinct year/month/day values for the
field.
``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or
``'DESC'``. This specifies how to order the results.
Examples::
>>> Entry.objects.dates('pub_date', 'year')
[datetime.date(2005, 1, 1)]
>>> Entry.objects.dates('pub_date', 'month')
[datetime.date(2005, 2, 1), datetime.date(2005, 3, 1)]
>>> Entry.objects.dates('pub_date', 'week')
[datetime.date(2005, 2, 14), datetime.date(2005, 3, 14)]
>>> Entry.objects.dates('pub_date', 'day')
[datetime.date(2005, 2, 20), datetime.date(2005, 3, 20)]
>>> Entry.objects.dates('pub_date', 'day', order='DESC')
[datetime.date(2005, 3, 20), datetime.date(2005, 2, 20)]
>>> Entry.objects.filter(headline__contains='Lennon').dates('pub_date', 'day')
[datetime.date(2005, 3, 20)]
``datetimes()``
~~~~~~~~~~~~~~~
.. method:: datetimes(field_name, kind, order='ASC', tzinfo=None, is_dst=None)
Returns a ``QuerySet`` that evaluates to a list of :class:`datetime.datetime`
objects representing all available dates of a particular kind within the
contents of the ``QuerySet``.
``field_name`` should be the name of a ``DateTimeField`` of your model.
``kind`` should be either ``"year"``, ``"month"``, ``"week"``, ``"day"``,
``"hour"``, ``"minute"``, or ``"second"``. Each :class:`datetime.datetime`
object in the result list is "truncated" to the given ``type``.
``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or
``'DESC'``. This specifies how to order the results.
``tzinfo`` defines the time zone to which datetimes are converted prior to
truncation. Indeed, a given datetime has different representations depending
on the time zone in use. This parameter must be a :class:`datetime.tzinfo`
object. If it's ``None``, Django uses the :ref:`current time zone
<default-current-time-zone>`. It has no effect when :setting:`USE_TZ` is
``False``.
``is_dst`` indicates whether or not ``pytz`` should interpret nonexistent and
ambiguous datetimes in daylight saving time. By default (when ``is_dst=None``),
``pytz`` raises an exception for such datetimes.
.. versionadded:: 3.1
The ``is_dst`` parameter was added.
.. _database-time-zone-definitions:
.. note::
This function performs time zone conversions directly in the database.
As a consequence, your database must be able to interpret the value of
``tzinfo.tzname(None)``. This translates into the following requirements:
- SQLite: no requirements. Conversions are performed in Python with pytz_
(installed when you install Django).
- PostgreSQL: no requirements (see `Time Zones`_).
- Oracle: no requirements (see `Choosing a Time Zone File`_).
- MySQL: load the time zone tables with `mysql_tzinfo_to_sql`_.
.. _pytz: http://pytz.sourceforge.net/
.. _Time Zones: https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-TIMEZONES
.. _Choosing a Time Zone File: https://docs.oracle.com/en/database/oracle/
oracle-database/18/nlspg/datetime-data-types-and-time-zone-support.html
#GUID-805AB986-DE12-4FEA-AF56-5AABCD2132DF
.. _mysql_tzinfo_to_sql: https://dev.mysql.com/doc/refman/en/mysql-tzinfo-to-sql.html
``none()``
~~~~~~~~~~
.. method:: none()
Calling none() will create a queryset that never returns any objects and no
query will be executed when accessing the results. A qs.none() queryset
is an instance of ``EmptyQuerySet``.
Examples::
>>> Entry.objects.none()
<QuerySet []>
>>> from django.db.models.query import EmptyQuerySet
>>> isinstance(Entry.objects.none(), EmptyQuerySet)
True
``all()``
~~~~~~~~~
.. method:: all()
Returns a *copy* of the current ``QuerySet`` (or ``QuerySet`` subclass). This
can be useful in situations where you might want to pass in either a model
manager or a ``QuerySet`` and do further filtering on the result. After calling
``all()`` on either object, you'll definitely have a ``QuerySet`` to work with.
When a ``QuerySet`` is :ref:`evaluated <when-querysets-are-evaluated>`, it
typically caches its results. If the data in the database might have changed
since a ``QuerySet`` was evaluated, you can get updated results for the same
query by calling ``all()`` on a previously evaluated ``QuerySet``.
``union()``
~~~~~~~~~~~
.. method:: union(*other_qs, all=False)
Uses SQL's ``UNION`` operator to combine the results of two or more
``QuerySet``\s. For example:
>>> qs1.union(qs2, qs3)
The ``UNION`` operator selects only distinct values by default. To allow
duplicate values, use the ``all=True`` argument.
``union()``, ``intersection()``, and ``difference()`` return model instances
of the type of the first ``QuerySet`` even if the arguments are ``QuerySet``\s
of other models. Passing different models works as long as the ``SELECT`` list
is the same in all ``QuerySet``\s (at least the types, the names don't matter
as long as the types are in the same order). In such cases, you must use the
column names from the first ``QuerySet`` in ``QuerySet`` methods applied to the
resulting ``QuerySet``. For example::
>>> qs1 = Author.objects.values_list('name')
>>> qs2 = Entry.objects.values_list('headline')
>>> qs1.union(qs2).order_by('name')
In addition, only ``LIMIT``, ``OFFSET``, ``COUNT(*)``, ``ORDER BY``, and
specifying columns (i.e. slicing, :meth:`count`, :meth:`order_by`, and
:meth:`values()`/:meth:`values_list()`) are allowed on the resulting
``QuerySet``. Further, databases place restrictions on what operations are
allowed in the combined queries. For example, most databases don't allow
``LIMIT`` or ``OFFSET`` in the combined queries.
``intersection()``
~~~~~~~~~~~~~~~~~~
.. method:: intersection(*other_qs)
Uses SQL's ``INTERSECT`` operator to return the shared elements of two or more
``QuerySet``\s. For example:
>>> qs1.intersection(qs2, qs3)
See :meth:`union` for some restrictions.
``difference()``
~~~~~~~~~~~~~~~~
.. method:: difference(*other_qs)
Uses SQL's ``EXCEPT`` operator to keep only elements present in the
``QuerySet`` but not in some other ``QuerySet``\s. For example::
>>> qs1.difference(qs2, qs3)
See :meth:`union` for some restrictions.
``select_related()``
~~~~~~~~~~~~~~~~~~~~
.. method:: select_related(*fields)
Returns a ``QuerySet`` that will "follow" foreign-key relationships, selecting
additional related-object data when it executes its query. This is a
performance booster which results in a single more complex query but means
later use of foreign-key relationships won't require database queries.
The following examples illustrate the difference between plain lookups and
``select_related()`` lookups. Here's standard lookup::
# Hits the database.
e = Entry.objects.get(id=5)
# Hits the database again to get the related Blog object.
b = e.blog
And here's ``select_related`` lookup::
# Hits the database.
e = Entry.objects.select_related('blog').get(id=5)
# Doesn't hit the database, because e.blog has been prepopulated
# in the previous query.
b = e.blog
You can use ``select_related()`` with any queryset of objects::
from django.utils import timezone
# Find all the blogs with entries scheduled to be published in the future.
blogs = set()
for e in Entry.objects.filter(pub_date__gt=timezone.now()).select_related('blog'):
# Without select_related(), this would make a database query for each
# loop iteration in order to fetch the related blog for each entry.
blogs.add(e.blog)
The order of ``filter()`` and ``select_related()`` chaining isn't important.
These querysets are equivalent::
Entry.objects.filter(pub_date__gt=timezone.now()).select_related('blog')
Entry.objects.select_related('blog').filter(pub_date__gt=timezone.now())
You can follow foreign keys in a similar way to querying them. If you have the
following models::
from django.db import models