Queryset are commonly used with Django's ORM. I Didn't Know Querysets Could do That by Charlie Guo is a nice Django Con US 2016 talk that delves deeper into useage of QuerySet. Following is summary notes of the talk
Queryset are commonly used with Django's ORM. I Didn't Know Querysets Could do That by Charlie Guo is a nice Django Con US 2016 talk that delves deeper into useage of QuerySet. Following is summary notes of the talk
Queryset are commonly used with Django’s ORM. I Didn’t Know Querysets Could do That by Charlie Guo is a nice Django Con US 2016 talk that delves deeper into useage of QuerySet.
Following is summary notes of the talk
Methods that return QuerySet
Methods that return model instance
annotate
and aggregate
both expect a expression
products = products.annotate(Count('item'))
products.first().item__count
grand_total = orders.aggregate(Sum('total'))
grand_total['total__sum']
select_related
: Allows getting related objects using single query via JOINs.prefetch_related
: Similar to select_related
will do JOINs in Pythondefer
: Allows to fetch all except specified queryonly
: Allows to fetch selected fields onlyvalues
: Return dictionaries rather than instances of modelsvalues_list
: Returns tuples that can be iterated overin_bulk
: You pass it list of IDs and returns a dictionary of ID to Model Instancebulk_create
: Does the job of creation/insertions in just a single queryWhen specifying attributes in filter method of QuerySet it generates SQL query with underlying AND construct
Q
E.g. find all users with certain name keywords
users = User.objects.filter(
Q(first_name__icontains='kelly') |
Q(last_name__icontains='kelly') |
Q(email__icontains='kelly')
).order_by('last_name')
F
, while Q
represented query contraint. F represents an implicit refrence in DB calls
item_sum = Sum(F('unit_price') * F('quantity'))
total = items.aggregate(amount=item_sum).get('amount', 0)
F
expressionsThey are examples of Django’s Query Expressions. This includes:
If you’re writing RAW SQL you should probably rethink what you’re about to do
EXTRA
Order.objects.extra(
select={"is_recent": "ordered_at > 2016-01-01"}
)
Other options
Order.objects.raw("""
SELECT * FROM ...
""")