<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Farhanahmed on Medium]]></title>
        <description><![CDATA[Stories by Farhanahmed on Medium]]></description>
        <link>https://medium.com/@farhan313ahmed?source=rss-582674515ad4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*AgNnxNzuXuz7jHGf</url>
            <title>Stories by Farhanahmed on Medium</title>
            <link>https://medium.com/@farhan313ahmed?source=rss-582674515ad4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 11:06:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@farhan313ahmed/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Slow to Swift: Optimizing Django’s N+1 Query Conundrum]]></title>
            <link>https://python.plainenglish.io/from-slow-to-swift-optimizing-the-djangos-n-1-query-conundrum-56b2b072f841?source=rss-582674515ad4------2</link>
            <guid isPermaLink="false">https://medium.com/p/56b2b072f841</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[django-orm]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[database-query]]></category>
            <dc:creator><![CDATA[Farhanahmed]]></dc:creator>
            <pubDate>Sun, 24 Sep 2023 21:24:59 GMT</pubDate>
            <atom:updated>2023-09-25T08:55:37.093Z</atom:updated>
            <content:encoded><![CDATA[<p>Django empowers developers to build robust and efficient web applications with ease. One of its standout features is the Object-Relational Mapping (ORM) system, which allows developers to interact with the database using Python objects instead of raw SQL queries. It makes the database calls implicit, freeing the developer from having to think about when and how the database queries are run, encouraging a developer to <em>not think about when and how the database queries are run</em>!</p><h4>The N+1 Menace</h4><p>One of the most common issues developers face when working with Django ORM is N+1 queries. These queries can lead to slow loading times, poor responsiveness, and increased server load on your application. This scenario is most common for cases where a model has a foreign key, and we want to get the relational data, and in doing so, we might make additional queries to retrieve related data for each result of the original query.</p><p>Lets explore this example through code to better understand this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*SgYtE7yd-fBkejPm.png" /></figure><h4>Creating a Listing API</h4><p>Lets get to the code, and do some hands-on. You can get the sample code from this <a href="https://github.com/farhan1ahmed/django_performance.git">repository</a>.</p><p>We have two models, Author and Books, which are related to each other in a one-to-many relationship.</p><pre>class Author(models.Model):<br>    first_name = models.CharField(max_length=30, blank=True)<br>    last_name = models.CharField(max_length=30, blank=True)<br><br><br>class Books(models.Model):<br>    name = models.CharField(max_length=100)<br>    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name=&quot;books&quot;)</pre><p>We have also defined a views.py and serializers.py file which returns a list of Authors as a json payload. Notice, that we want to get the list of books’ names as well as part of Author object.</p><pre>#views.py<br>class AuthorsApiView(ListAPIView):<br>    serializer_class = AuthorSerializer<br>    MODEL = Author<br>    ordering = [&quot;-created_at&quot;]<br><br>    def get_queryset(self):<br>        return self.MODEL.objects.all()<br><br>#serializers.py<br>class AuthorSerializer(serializers.ModelSerializer):<br>    book_names = serializers.SerializerMethodField()<br>    class Meta:<br>        model = Author<br>        fields = [<br>            &quot;id&quot;,<br>            &quot;first_name&quot;,<br>            &quot;last_name&quot;,<br>            &quot;book_names&quot;<br>        ]<br><br>    def get_book_names(self, obj):<br>        return list(obj.books.values_list(&#39;name&#39;, flat=True))</pre><p>The code is straight-forward and returns the following response for a listing of 5 authors:</p><pre>{<br>    &quot;count&quot;: 20,<br>    &quot;next&quot;: &quot;http://localhost:9000/authors/?limit=5&amp;offset=5&quot;,<br>    &quot;previous&quot;: null,<br>    &quot;results&quot;: [<br>        {<br>            &quot;id&quot;: 1,<br>            &quot;first_name&quot;: &quot;Author1&quot;,<br>            &quot;last_name&quot;: &quot;LastName1&quot;,<br>            &quot;book_names&quot;: [<br>                &quot;Book1 by Author1&quot;,<br>                &quot;Book2 by Author1&quot;,<br>                &quot;Book3 by Author1&quot;<br>            ]<br>        },<br>        {<br>            &quot;id&quot;: 2,<br>            &quot;first_name&quot;: &quot;Author2&quot;,<br>            &quot;last_name&quot;: &quot;LastName2&quot;,<br>            &quot;book_names&quot;: [<br>                &quot;Book1 by Author2&quot;,<br>                &quot;Book2 by Author2&quot;,<br>                &quot;Book3 by Author2&quot;<br>            ]<br>        },<br>        {<br>            &quot;id&quot;: 3,<br>            &quot;first_name&quot;: &quot;Author3&quot;,<br>            &quot;last_name&quot;: &quot;LastName3&quot;,<br>            &quot;book_names&quot;: [<br>                &quot;Book1 by Author3&quot;,<br>                &quot;Book2 by Author3&quot;,<br>                &quot;Book3 by Author3&quot;<br>            ]<br>        },<br>        {<br>            &quot;id&quot;: 4,<br>            &quot;first_name&quot;: &quot;Author4&quot;,<br>            &quot;last_name&quot;: &quot;LastName4&quot;,<br>            &quot;book_names&quot;: [<br>                &quot;Book1 by Author4&quot;,<br>                &quot;Book2 by Author4&quot;,<br>                &quot;Book3 by Author4&quot;<br>            ]<br>        },<br>        {<br>            &quot;id&quot;: 5,<br>            &quot;first_name&quot;: &quot;Author5&quot;,<br>            &quot;last_name&quot;: &quot;LastName5&quot;,<br>            &quot;book_names&quot;: [<br>                &quot;Book1 by Author5&quot;,<br>                &quot;Book2 by Author5&quot;,<br>                &quot;Book3 by Author5&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p>This looks good so far. But, is it really?</p><p>Let’s dive deep down and see what’s going on under the hood.</p><h4>Database Queries</h4><p>Lets drill down to the database layer and investigate whats the ORM really doing while fetching the required information for the JSON response. We can integrate the <a href="https://pypi.org/project/django-querycount/">‘django-querycount’</a> package with our Django application and print out all the queries that are taking place behind the ORM. In order to do that, lets add <em>‘querycount.middleware.QueryCountMiddleware’</em> to our <strong>MIDDLEWARES</strong> defined in the setting.py file.</p><pre>MIDDLEWARE = [<br>    &#39;django.contrib.sessions.middleware.SessionMiddleware&#39;,<br>    &#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;,<br>    &#39;django.contrib.messages.middleware.MessageMiddleware&#39;,<br>    &quot;querycount.middleware.QueryCountMiddleware&quot;<br>]</pre><p>Now hitting the API endpoint will print all the SQL statements that are run as part of the GET API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*eoVO8C5QijF0XPzyQ_sEgw.png" /><figcaption>Database Query Count</figcaption></figure><p>The results above reveal something interesting about our API. It looks like our API is working hard to fetch information about authors from the ‘author’s’ table. It’s also keeping track of how many authors there are for the paginated API. But here’s the kicker: it’s making five separate trips to the books table to get the names of all the books for each author. These extra trips don’t really serve a purpose and are causing our database to work harder than it needs to. This could make it tough for us to expand our system in the future and might slow down how well our system performs</p><h4>Controlling Chaos</h4><p>Now lets tackle this problem. Any seasoned developer will point out that all this information should be fetched in one database call so that the overall db calls are reduced while also improving the efficiency of our system. In Django, we can use <strong><em>select_related</em></strong>, <strong><em>prefetch_related</em></strong> and <strong><em>Subqueries</em></strong> to implement table joins and get all the data in a single db call.</p><p>Let’s use the Subquery method to get the names of all the books at the time of querying our Author’s model. Our views.py and serializer.py file would look something like this:</p><pre>#views.py<br>class AuthorsApiView(ListAPIView):<br>    serializer_class = AuthorSerializer<br>    MODEL = Author<br>    ordering = [&quot;-created_at&quot;]<br><br>    def get_queryset(self):<br>        return self.MODEL.objects.annotate(<br>           book_names=Subquery(<br>                Books.objects.filter(author_id=OuterRef(&quot;id&quot;))<br>                    .values(&quot;author_id&quot;)<br>                    .annotate(book_names=ArrayAgg(&quot;name&quot;))<br>                    .values(&quot;book_names&quot;)<br>                )<br>        ).all()<br><br>#serializers.py<br>class AuthorSerializer(serializers.ModelSerializer):<br>    book_names = serializers.ListSerializer(child=serializers.CharField())<br>    class Meta:<br>        model = Author<br>        fields = [<br>            &quot;id&quot;,<br>            &quot;first_name&quot;,<br>            &quot;last_name&quot;,<br>            &quot;book_names&quot;<br>        ]</pre><p>Thanks to this optimized code, we’ve managed to reduce the total number of database queries, resulting in a significant <strong><em>39%</em></strong> improvement in response time. Specifically, the response time has been cut down from <strong><em>0.0130</em></strong> seconds to a swift <strong><em>0.0078</em></strong><em> </em>seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*2RLWV9IMQpHz9UrMOwARxQ.png" /><figcaption>Improved Database Query Count</figcaption></figure><p>In conclusion, Django’s ORM, while a powerful asset, presents a notable challenge in the form of the N+1 query problem. We’ve explored this issue in-depth, uncovering its performance implications and effective solutions like <em>select_related, prefetch_related</em> and optimized joins with <em>subqueries.</em> Armed with these tools, you can enhance your application&#39;s efficiency, ensuring it can handle real-world demands seamlessly. By mastering N+1 query resolution, you&#39;ll harness the full potential of Django&#39;s ORM, enabling your applications to shine in terms of speed and user experience.</p><p>Happy coding!</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/XxRS92b2"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56b2b072f841" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/from-slow-to-swift-optimizing-the-djangos-n-1-query-conundrum-56b2b072f841">From Slow to Swift: Optimizing Django’s N+1 Query Conundrum</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>