Simplifying Django Queries with Custom Field Lookups

Let’s Write Readable ORM.

Rahul Beniwal
Django Unleashed
2 min readJun 19, 2024

--

Welcome everyone! Today, we’ll explore how to add custom lookups to Django fields, enhancing the flexibility and readability of your queries.

Finding Authors Whose Name is Greater than 10 Characters

Let’s consider a simple Author model:

from django.db import models

class Author(models.Model):
name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100, null=True, blank=True)

We can use two different approaches to find authors whose names are longer than 10 characters.

First Approach: Using Built-in Lookups

In this method, we apply the GreaterThan lookup on the result of the Length function:

from django.db.models.lookups import GreaterThan
from django.db.models.functions import Length


Author.objects.filter(GreaterThan(Length("name"), 10)).count()
# 92

Here, we use the Length function to get the length of the name field and then apply the GreaterThan lookup to filter authors whose names are longer than 10 characters.

Second Approach: Registering a Custom Lookup

A more readable and natural way to achieve the same result is by registering a custom lookup. This approach allows us to use the __length lookup directly in our queries.

First, let’s register the Length function as a lookup for CharField:

from django.db.models import CharField
from django.db.models.functions import Length

CharField.register_lookup(Length, 'length')

Now, we can use this custom lookup in our queries.

Author.objects.filter(name__length__gt=10).count()
# 92

This method makes our query more readable and intuitive.

Conclusion

By registering custom lookups, you can make your Django queries more expressive and maintainable. In this article, we’ve seen two approaches to filter authors based on the length of their names. The first method uses built-in lookups, while the second method shows how to register and use a custom lookup. The second approach is more natural and improves the readability of your code.

Feel free to try these approaches in your projects and see how custom lookups can simplify your query logic!

Leave a 👏 and follow Rahul Beniwal for more upcoming articles.

You can also check my other writings also

--

--