@@ -26,6 +26,9 @@ Some examples
26
26
27
27
.. code-block:: python
28
28
29
+ from django.db.models import F, Count
30
+ from django.db.models.functions import Length
31
+
29
32
# Find companies that have more employees than chairs.
30
33
Company.objects.filter(num_employees__gt=F('num_chairs'))
31
34
@@ -62,6 +65,12 @@ Some examples
62
65
Built-in Expressions
63
66
====================
64
67
68
+ .. note::
69
+
70
+ These expressions are defined in ``django.db.models.expressions`` and
71
+ ``django.db.models.aggregates``, but for convenience they're available and
72
+ usually imported from :mod:`django.db.models`.
73
+
65
74
``F()`` expressions
66
75
-------------------
67
76
@@ -88,6 +97,7 @@ into memory and manipulated it using familiar Python operators, and then saved
88
97
the object back to the database. But instead we could also have done::
89
98
90
99
from django.db.models import F
100
+
91
101
reporter = Reporters.objects.get(name='Tintin')
92
102
reporter.stories_filed = F('stories_filed') + 1
93
103
reporter.save()
@@ -194,6 +204,8 @@ directly support ``output_field`` you will need to wrap the expression with
194
204
database functions like ``COALESCE`` and ``LOWER``, or aggregates like ``SUM``.
195
205
They can be used directly::
196
206
207
+ from django.db.models import Func, F
208
+
197
209
queryset.annotate(field_lower=Func(F('field'), function='LOWER'))
198
210
199
211
or they can be used to build a library of database functions::
@@ -259,6 +271,8 @@ like ``Sum()`` and ``Count()``, inherit from ``Aggregate()``.
259
271
Since ``Aggregate``\s are expressions and wrap expressions, you can represent
260
272
some complex computations::
261
273
274
+ from django.db.models import Count
275
+
262
276
Company.objects.annotate(
263
277
managers_required=(Count('num_employees') / 4) + Count('num_managers'))
264
278
@@ -314,6 +328,8 @@ Creating your own aggregate is extremely easy. At a minimum, you need
314
328
to define ``function``, but you can also completely customize the
315
329
SQL that is generated. Here's a brief example::
316
330
331
+ from django.db.models import Aggregate
332
+
317
333
class Count(Aggregate):
318
334
# supports COUNT(distinct field)
319
335
function = 'COUNT'
@@ -578,6 +594,7 @@ to play nice with other query expressions::
578
594
579
595
Let's see how it works::
580
596
597
+ >>> from django.db.models import F, Value, CharField
581
598
>>> qs = Company.objects.annotate(
582
599
... tagline=Coalesce([
583
600
... F('motto'),
0 commit comments