Query Expression in Django — DjangoTip03
A query expression is a set of clauses that defines a particular search. In Django, a query expression is used to filter the results of a queryset. Django ORM is one of the most incredible aspects of Django. It makes queryset searching, filtering, and sorting really simple.
In this article you will learn about some query expression available to you in Django. The below Django Demo Project uses the following models.py
file:
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
published = models.DateTimeField(auto_now_add=True)
writer = models.ForeignKey(User, on_delete=models.CASCADE)
likes = models.PositiveIntegerField()
class Meta:
ordering = ("-published",)
get_latest_by = "published"
unique_together = [
["title", "content"],
]
Func()
The Func()
expressions in Django ORM allows the queryset to annotate an additional field after performing functions on the field. In the below example you will change the title
of the Post
objects to Uppercase.
>>> from main.models import Post
>>> from django.db.models import Func
>>> qs = Post.objects.all().annotate(title_upper=Func('title', function='UPPER'))
>>> qs.first().title
'Post 3'
>>> qs.first().title_upper
'POST 3'
In the above example you can see that a new field got added to the instances of queryset where the text is uppercase. For more information about the annotate
you can give a read to this article.
Subquery()
In Subquery()
expression used to add a query that is nested inside another query. The below example use Subquery()
to annotate each Post instance with a writer_joined
attribute.
>>> from django.contrib.auth.models import User
>>> from main.models import Post
>>> from django.db.models import Subquery
>>> users = User.objects.all()
>>> posts = Post.objects.annotate(writer_joined=Subquery(users.values('date_joined')))
>>> posts.first().writer_joined.ctime()
'Sun Nov 13 07:11:00 2022'
Aggregate
Django provide many built-in Aggregation Functions like Avg
, Sum
, Min
and Max
. Below is the example, how to use these functions:
>>> from main.models import Post
>>> from django.db.models import Max, Min, Count, Avg
>>> Post.objects.aggregate(Max('likes'))
{'likes__max': 25}
>>> Post.objects.aggregate(Min('likes'))
{'likes__min': 13}
>>> Post.objects.aggregate(Avg('likes'))
{'likes__avg': 17.666666666666668}
>>> Post.objects.aggregate(Count('likes'))
{'likes__count': 3}
I sincerely hope you enjoyed reading this article. Django offers a ton of other valuable features like these, which I intend to discuss in my upcoming blogs. Consider becoming a follower if this sounds like something you’d be interested in.