DEV Community

Cover image for Optimize query size in Django
Mangabo Kolawole
Mangabo Kolawole Subscriber

Posted on • Originally published at Medium

5 1

Optimize query size in Django

Problem

When your project grows, it's possible that with time you'll start having models with more and more fields.
What are the consequences of that? Well, if you have a model with more than 30 fields and you are trying to retrieve an object or a list of objects from the database, the return queryset will be really heavy.
And it's possible you won't definitely need all the fields.

How to optimize the query?

Django provides the only() method that returns a queryset with objects that only contain the list of fields and the values specified in the only(*args).
As stated in Django,

Here's an example:

from django.db import models


class User(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField(max_length=254)
    bio = models.CharField(max_length=50)

    def __str__(self) -> str:
        return "%s (%s)" % (self.name,
            ", ".join(profile.first_name for profile in self.profile_set.all()))
Enter fullscreen mode Exit fullscreen mode

And here's the queryset:

users = User.objects.only('name', 'email').all()
Enter fullscreen mode Exit fullscreen mode

There is also the defer() method -- opposite to only -- that can be used to remove fields you don't want to use in a particular query.
Following this, these two queries are identical if the User table has only name, email, and bio fields.

users = User.objects.only('name', 'email').all()

users = User.objects.defer('bio').all()
Enter fullscreen mode Exit fullscreen mode

Article posted using bloggu.io. Try it for free.

API Trace View

Struggling with slow API calls?

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more