|
@@ -76,33 +76,33 @@ Some examples
|
|
|
|
|
|
# Annotate models with an aggregated value. Both forms
|
|
|
# below are equivalent.
|
|
|
- Company.objects.annotate(num_products=Count('products'))
|
|
|
- Company.objects.annotate(num_products=Count(F('products')))
|
|
|
+ >>> Company.objects.annotate(num_products=Count("products"))
|
|
|
+ >>> Company.objects.annotate(num_products=Count(F("products")))
|
|
|
|
|
|
# Aggregates can contain complex computations also
|
|
|
- Company.objects.annotate(num_offerings=Count(F('products') + F('services')))
|
|
|
+ >>> Company.objects.annotate(num_offerings=Count(F("products") + F("services")))
|
|
|
|
|
|
# Expressions can also be used in order_by(), either directly
|
|
|
- Company.objects.order_by(Length('name').asc())
|
|
|
- Company.objects.order_by(Length('name').desc())
|
|
|
+ >>> Company.objects.order_by(Length("name").asc())
|
|
|
+ >>> Company.objects.order_by(Length("name").desc())
|
|
|
# or using the double underscore lookup syntax.
|
|
|
- from django.db.models import CharField
|
|
|
- from django.db.models.functions import Length
|
|
|
- CharField.register_lookup(Length)
|
|
|
- Company.objects.order_by('name__length')
|
|
|
+ >>> from django.db.models import CharField
|
|
|
+ >>> from django.db.models.functions import Length
|
|
|
+ >>> CharField.register_lookup(Length)
|
|
|
+ >>> Company.objects.order_by("name__length")
|
|
|
|
|
|
# Boolean expression can be used directly in filters.
|
|
|
- from django.db.models import Exists
|
|
|
- Company.objects.filter(
|
|
|
- Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
|
|
|
- )
|
|
|
+ >>> from django.db.models import Exists
|
|
|
+ >>> Company.objects.filter(
|
|
|
+ ... Exists(Employee.objects.filter(company=OuterRef("pk"), salary__gt=10))
|
|
|
+ ... )
|
|
|
|
|
|
# Lookup expressions can also be used directly in filters
|
|
|
- Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
|
|
|
+ >>> Company.objects.filter(GreaterThan(F("num_employees"), F("num_chairs")))
|
|
|
# or annotations.
|
|
|
- Company.objects.annotate(
|
|
|
- need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
|
|
|
- )
|
|
|
+ >>> Company.objects.annotate(
|
|
|
+ ... need_chairs=GreaterThan(F("num_employees"), F("num_chairs")),
|
|
|
+ ... )
|
|
|
|
|
|
Built-in Expressions
|
|
|
====================
|
|
@@ -257,10 +257,10 @@ primary key value rather than a model instance:
|
|
|
|
|
|
.. code-block:: pycon
|
|
|
|
|
|
- >> car = Company.objects.annotate(built_by=F('manufacturer'))[0]
|
|
|
- >> car.manufacturer
|
|
|
+ >>> car = Company.objects.annotate(built_by=F("manufacturer"))[0]
|
|
|
+ >>> car.manufacturer
|
|
|
<Manufacturer: Toyota>
|
|
|
- >> car.built_by
|
|
|
+ >>> car.built_by
|
|
|
3
|
|
|
|
|
|
.. _using-f-to-sort-null-values:
|