<?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 Ryley Sill on Medium]]></title>
        <description><![CDATA[Stories by Ryley Sill on Medium]]></description>
        <link>https://medium.com/@ryleysill93?source=rss-fde5470f9e44------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_6gw8_S4v8X-MJ4ZEMcFtA.jpeg</url>
            <title>Stories by Ryley Sill on Medium</title>
            <link>https://medium.com/@ryleysill93?source=rss-fde5470f9e44------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:04:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ryleysill93/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[Basic Performance Optimization in Django]]></title>
            <link>https://medium.com/@ryleysill93/basic-performance-optimization-in-django-ebd19089a33f?source=rss-fde5470f9e44------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebd19089a33f</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Ryley Sill]]></dc:creator>
            <pubDate>Mon, 07 Jan 2019 01:36:43 GMT</pubDate>
            <atom:updated>2019-02-17T21:26:31.979Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TL;DR:</strong> Profile your code, make fewer SQL queries, serialize less data</p><p>I recently built <a href="https://carta.com/blog/scenario-modeling/">Carta’s Scenario Modeling</a> platform. A little ways into the project I realized I didn’t know how to write performant code. I still don’t, but here are some things I wish I knew before I got started.</p><h4>Disclaimer</h4><p>The sections below are high-level explanations meant to expose you to different techniques you can use to optimize your Django code. Results will vary depending on your database, models, and the nature of your data.</p><h4>Getting Started — example data model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSQW17SMwsyDvRlE2qk3Xw.png" /></figure><pre><strong>class Library</strong>(models.Model):<br>    name = models.CharField(max_length=200, default=&#39;&#39;)<br>    address = models.CharField(max_length=200, default=&#39;&#39;)<br></pre><pre><strong>class Author</strong>(models.Model):<br>    name = models.CharField(max_length=200, default=&#39;&#39;)</pre><pre><br><strong>class Book</strong>(models.Model):<br>    library = models.ForeignKey(<br>        Library,<br>        on_delete=models.CASCADE,<br>        related_name=&#39;books&#39;,<br>    )<br>    author = models.ForeignKey(<br>        Author,<br>        on_delete=models.CASCADE,<br>        related_name=&#39;books&#39;<br>    )<br>    title = models.CharField(max_length=200, default=&#39;&#39;)<br>    address = models.CharField(max_length=200, default=&#39;&#39;)</pre><pre>    <strong>def</strong> get_page_count(self):<br>        <strong>return</strong> self.pages.count()</pre><pre><br><strong>class Page</strong>(models.Model):<br>    book = models.ForeignKey(<br>        Book,<br>        on_delete=models.CASCADE,<br>        related_name=&#39;pages&#39;,<br>    )<br>    text = models.TextField(null=True, blank=True)<br>    page_number = models.IntegerField()</pre><p>I created a simple data model consisting of books, pages, authors, and libraries so we can play with the techniques outlined below. The database is seeded with 10,000 books, 1,000,000 pages, 1,000 authors, and 1,000 libraries. The pages are randomly assigned to books and the books are randomly assigned to authors and libraries.</p><h4>Use line_profiler</h4><p>If we don’t know why our code is slow its going to be difficult to figure out how to optimize it. <a href="https://github.com/rkern/line_profiler">line_profiler</a> is a cool python module that tells us how much time it takes to execute each line in a function. Before you get started, install the package with pip install line_profiler.</p><p>Here’s how I typically use it. Imagine we needed a function which returned all of the books corresponding to each library in our database. Let’s say we ended up with something like this…</p><pre><strong>def</strong> get_books_by_library_id():<br>    libraries = Library.objects.all()<br>    result = {}<br>    <br>    for library in libraries:<br>        books_in_library = library.books.all()<br>        result[library.id] = list(books_in_library)</pre><pre><strong>    return</strong> result</pre><p>…which was causing the below view to run slowly.</p><pre><strong>from django.http import</strong> HttpResponse<br><strong>from test_app.helpers import </strong>get_books_by_library_id</pre><pre><br><strong>def</strong> books_by_library_id_view(request):<br>    books_by_library_id = get_books_by_library_id()</pre><pre>    ...</pre><pre>    <strong>return</strong> HttpResponse(response)</pre><p>To find out where the computer is spending its time during the execution of the function you can add an IPython debugger to the view right before where the suspect function is called…</p><pre><strong>from django.http import</strong> HttpResponse<br><strong>from test_app.helpers import </strong>get_books_by_library_id</pre><pre><strong>def</strong> books_by_library_id_view(request):<br>    <strong>from IPython import </strong>embed; embed()<br>    books_by_library_id = get_books_by_library_id()</pre><pre>    ...</pre><pre><strong>    return</strong> HttpResponse(response)</pre><p>…perform whatever action triggers the view, wait for your server to stop running and the IPython shell to start up, load line_profiler as an extension into the IPython shell, and then profile the function with lprun -f your_function_name your_function_name(). If any arguments need to be passed into the function, pass them inside the parentheses of the last part of that command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ur2mv_nQZOkAf4AbY-IQWw.png" /></figure><p>The % Time column tells you how much of the Total time the function spent executing that line of code. So out of the 47.977 seconds it took to execute the entire function we spent 98.8% of the total time executing line 6, where we evaluate the library.books.all() queryset by coercing it to a list.</p><p>The Hits column tells you how many times that line of code was executed. It looks like line 6 is executed 1000 times — one time for each Library in the database. That means we’re making 1000 SQL queries which is probably why this function is so slow. We’ll cover how to get make this faster in later sections.</p><h4>Turn on SQL logging</h4><p>When we’re really digging into a function to see where the bottlenecks are it can be useful to turn on SQL logging.</p><pre># settings.py</pre><pre>LOGGING = {<br>    &#39;version&#39;: 1,<br>    &#39;filters&#39;: {<br>        &#39;require_debug_true&#39;: {<br>            &#39;()&#39;: &#39;django.utils.log.RequireDebugTrue&#39;,<br>        }<br>     },<br>     &#39;handlers&#39;: {<br>        &#39;console&#39;: {<br>            &#39;level&#39;: &#39;DEBUG&#39;,<br>            &#39;filters&#39;: [&#39;require_debug_true&#39;],<br>            &#39;class&#39;: &#39;logging.StreamHandler&#39;,<br>         }<br>    },<br>    &#39;loggers&#39;: {<br>        &#39;django.db.backends&#39;: {<br>            &#39;level&#39;: &#39;DEBUG&#39;,<br>            &#39;handlers&#39;: [&#39;console&#39;],<br>        }<br>    }<br>}</pre><p>We can add this snippet to settings.py to get a full printout of every SQL query executed in your code. It’s usually way too much to keep on at all times but it can be enlightening to see how many queries are being executed and how long its taking to execute each of them in a given block of code.</p><p>The way I typically use SQL logging is to put a debugger before and after a suspect block of code. I then execute the code, clear my terminal once I hit the first debugger, continue through the first debugger, and investigate the queries that were executed in between while keeping an eye out for repeated, unexpected, or slow queries.</p><p>This post wont cover SQL query optimization but we will go over how to reduce or eliminate the number of repeated queries in a function.</p><h4>Avoid queries in loops</h4><pre><strong>def</strong> get_books_by_library_id():<br>    libraries = Library.objects.all()<br>    result = {}<br>    <br>    for library in libraries:<br>        books_in_library = library.books.all()<br>        result[library.id] = list(books_in_library)</pre><pre>    <strong>return</strong> result</pre><p>Back to our terminally ill function get_books_by_library. The problem with this is we’re making a round trip to the database to fetch the books for <em>each</em> library. This might be what you want if you only have a few libraries each with millions of books. But if you have thousands of libraries each with thousands of books, your code is now executing thousands of queries. To get around this we can grab all of the books up front:</p><pre><strong>def</strong> get_books_by_library_id_one_query():<br>    books = Book.objects.all()<br>    result = defaultdict(list)<br>    <br>    for book in books:<br>        result[book.library_id].append(book)</pre><pre>    <strong>return</strong> result</pre><p>Boom. Now you’re only making one SQL query regardless of how many libraries exist in your database.</p><p>So how do we know if this is any faster? Python has this cool little module called <a href="https://docs.python.org/2/library/timeit.html">timeit</a> that tells you how long it takes to execute a function.</p><pre>In [12]: timeit(get_books_by_library_id, number=10)<br>Out[12]: 6.598360636999132<br>In [13]: timeit(get_books_by_library_id_one_query, number=10)<br>Out[13]: 0.677092163998168</pre><p>Even though our second function has to loop over 10,000 books, it still runs nearly 10x faster than the original function by eliminating round trips to the database. Keep in mind this all depends on the sparseness/density and scale of your data. In my experience, code generally runs slower if the number of SQL queries made scales with some other input.</p><h4>select_related()</h4><p>Imagine you wanted a list of strings in the format of Harry Potter and the Sorcerer&#39;s Stone by J.K. Rowling corresponding to each library.</p><p>Django makes it easy to write code that executes unnecessary queries. If you don’t know what’s happening under the hood or you’re working with unfamiliar models, you might write something like this:</p><pre><strong>def</strong> get_books_by_author():<br>    books = Book.objects.all()<br>    result = defaultdict(list)</pre><pre>    for book in books:<br>        author = book.author<br>        title_and_author = &#39;{} by {}&#39;.format(<br>            book.title,<br>            author.name<br>        )<br>        result[book.library_id].append(title_and_author)</pre><pre>    <strong>return</strong> result</pre><p>Here’s the problem: each time you access book.author you’re making a query equivalent to Author.objects.get(id=book.author_id). If you’re looping over thousands of books you’re also making thousands of completely unnecessary queries. Use <a href="https://docs.djangoproject.com/en/2.1/ref/models/querysets/#select-related">select_related</a> to avoid this:</p><pre><strong>def</strong> get_books_by_author_select_related():<br>    books = Book.objects.all().select_related(&#39;author&#39;)<br>    result = defaultdict(list)</pre><pre>    for book in books:<br>        author = book.author<br>        title_and_author = &#39;{} by {}&#39;.format(<br>            book.title,<br>            author.name<br>        )<br>        result[book.library_id].append(title_and_author)</pre><pre>    <strong>return</strong> result</pre><p>select_related works by making a single more complex SQL query which also returns the fields of the related object. So instead of just getting back data about all of the books, you’re also grabbing data for each book’s author as well. Now when you access book.author you’re actually accessing a cached version of the author rather than making a separate database query.</p><p>How much faster is the naive approach vs the approach using select_related? I ran both of these functions using the timeit module and found that the function using select_related was 32x faster:</p><pre>In [12]: timeit(get_books_by_author, number=10)<br>Out[12]: 41.363460485998075<br>In [13]: timeit(get_books_by_author_select_related, number=10)<br>Out[13]: 1.2787263889913447</pre><p>select_related wont work in all situations however:</p><blockquote>to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.</blockquote><p>In order to traverse reverse ForeignKey or ManyToMany relationships we’ll need prefetch_related.</p><h4>prefetch_related()</h4><p><a href="https://docs.djangoproject.com/en/2.1/ref/models/querysets/#prefetch-related">prefetch_related</a> is similar to select_related in that it prevents unnecessary SQL queries. Instead of fetching the primary and related objects in one go, prefetch_related makes separate queries for each relationship and “joins” the results together in python. The downside of this approach is it requires multiple round trips to the database.</p><pre>Author.objects.filter(name__startswith=&#39;R&#39;).prefetch(&#39;books&#39;)</pre><p>How it works: first a request is fired off which runs the primary query Author.objects.filter(name__startswith=letter). Then a second query equivalent to: Book.objects.filter(author_id__in=PKS_OF_AUTHORS_FROM_FIRST_REQUEST) is executed and both of the responses are merged together into an Author queryset that has each author’s books cached in memory. So you end up with a similar result as with select_related but you arrive there through different means.</p><p>Although you can use prefetch_related anywhere you use select_related, generally your code will run faster with select_related since it will grab everything you need in one SQL query. But if your data is particularly sparse (millions of books to just a few libraries) you may see a performance boost despite the extra trips to the database. So when in doubt, try both methods and see which one comes out on top.</p><p>To summarize: use select_related and prefetch_related if you’re going to access a model’s relationship after making an initial query. Use prefetch_related if you’re following a reverse ForeignKey or ManyToMany relationship. Use select_related if you’re following a ForeignKey or OneToOne relationship but keep in mind that prefetch_related <em>could</em> be a better choice for these types of relationships depending on the nature of your data.</p><h4>values() and values_list()</h4><p>The time it takes to serialize SQL responses into python scales with both the number of rows and columns being returned. In the function below, we’re serializing <em>all </em>of the fields defined on the book and author even though we only need the author’s name and the book’s library_id and title. We’re also are initializing a Django model instance for no reason since we’re not doing anything special with it (like calling model methods).</p><pre><strong>def</strong> get_books_by_author_select_related():<br>    books = Book.objects.all().select_related(&#39;author&#39;)<br>    result = defaultdict(list)</pre><pre>    for book in books:<br>        author = book.author<br>        title_and_author = &#39;{} by {}&#39;.format(<br>            book.title,<br>            author.name<br>        )<br>        result[book.library_id].append(title_and_author)</pre><pre>    <strong>return</strong> result</pre><p>Because of this, we incur pretty significant overhead that can be eliminated by calling .<a href="https://docs.djangoproject.com/en/2.1/topics/db/aggregation/#values">values</a>() or .<a href="https://docs.djangoproject.com/en/2.1/ref/models/querysets/#values-list">values_list</a>() on the queryset to ask only for the fields we need:</p><pre><strong>def</strong> get_books_by_author_select_related_values():<br>    books = (<br>        Book.objects<br>         .all()<br>         .select_related(&#39;author&#39;)<br>         .values(&#39;title&#39;, &#39;library_id&#39;, &#39;author__name&#39;)<br>    )<br>    result = defaultdict(list)</pre><pre>    for book in books.iterator():<br>        title_and_author = &#39;{} by {}&#39;.format(<br>            book[&#39;title&#39;],<br>            book[&#39;author__name&#39;]<br>        )<br>        result[book[&#39;library_id&#39;]].append(title_and_author)<br>    <br>    <strong>return</strong> result</pre><pre><strong>def</strong> get_books_by_author_select_related_values_list():<br>    books = (<br>        Book.objects<br>         .all()<br>         .select_related(&#39;author&#39;)<br>         .values_list(&#39;title&#39;, &#39;library_id&#39;, &#39;author__name&#39;)<br>    )<br>    result = defaultdict(list)</pre><pre>    for book in books.iterator():<br>        title_and_author = &#39;{} by {}&#39;.format(<br>            book[0],<br>            book[2]<br>        )<br>        result[book[1]].append(title_and_author)<br>    <br>    <strong>return</strong> result</pre><p>.values() returns a list of dictionary representations of the model instance: [{&#39;title&#39;: &#39;Snow Crash&#39;, &#39;library_id&#39;: 9, &#39;author__name&#39;: &#39;Neil&#39;}, ...] and .values_list() returns a list of tuples representing the model instance [(&#39;Snow Crash&#39;, 9, &#39;Neil&#39;), ...].</p><p>So how much faster are these functions? By only grabbing the fields we need, the functions using.values() and .values_list() runs ~7x faster than the original function.</p><pre>In [13]: timeit(get_books_by_author_select_related, number=10)<br>Out[13]: 1.2787263889913447<br>In [14]: timeit(get_books_by_author_select_related_values, number=1)<br>Out[14]: 0.19064296898432076<br>In [15]: timeit(get_books_by_author_select_related_values_list, number=1)<br>Out[15]: 0.17425400999491103</pre><p>Something to note here is these models are super lightweight — there are only 4 fields on the Book model. If we were working with models which had tons of fields, the results would be more extreme.</p><p>Even if you need all of the fields on the object, .values() and .values_list() will still provide a substantial performance boost by skipping model initialization. You can get all of the fields back by not passing in any fields as arguments.</p><pre># returns list of model instances<br><strong>def</strong> get_book_instances():<br>    <strong>return</strong> list(<br>        Book.objects<br>        .all()<br>        .select_related(&#39;author&#39;)<br>    )</pre><pre># returns list of dictionaries representing model instances<br><strong>def</strong> get_book_dictionaries():<br>    <strong>return</strong> list(<br>        Book.objects<br>        .all()<br>        .select_related(&#39;author&#39;)<br>        .values()<br>    )<br></pre><pre># returns a list of dictionaries with the name of each book<br><strong>def</strong> get_book_dictionaries_title_only():<br>    <strong>return</strong> list(<br>        Book.objects<br>        .all()<br>        .select_related(&#39;author&#39;)<br>        .values(&#39;title&#39;)<br>    )</pre><p>Getting the dictionary representation of the books is 6.5x faster and asking for a particular field on the book is 8.8x faster than requesting the model instances.</p><pre>In [64]: timeit(get_book_instances, number=100)<br>Out[64]: 12.904168864974054<br>In [65]: timeit(get_book_dictionaries, number=100)<br>Out[65]: 2.049193776998436<br>In [66]: timeit(get_book_dictionaries_title_only, number=100)<br>Out[66]: 1.4734381759772077</pre><p>Initializing Django model instances is expensive. If you’re only using the data on the model you’re likely better off working with their dictionary or tuple representations.</p><h4>bulk_create()</h4><p>This one is pretty simple. If we’re going to create more than one object at a time, use <a href="https://docs.djangoproject.com/en/2.1/ref/models/querysets/#bulk-create">bulk_create</a> instead of creating the objects in a loop. As the name suggests, bulk_create will insert a list of objects into the database using one query, regardless of how many objects we’re inserting.</p><p>It’s possible to insert so many objects that the single query generated by bulk_create will be slower than multiple smaller queries. In that case, you can pass in batch_size=SIZE_OF_BATCH as an argument which will break the master query into smaller queries.</p><p>I’m not aware of any rules of thumb regarding the number of objects you need to insert before it makes sense to use batch_size or how to decide on the size of the batch. Usually I omit it until it becomes clear that there’s a bottleneck and then determine a suitable batch_size from there.</p><h4>SQL is (generally) faster than Python</h4><p>Let’s imagine you wanted a function that returns the total number of pages for each library. Using what we’ve learned above you might end up with something like this:</p><pre><strong>def</strong> get_page_count_by_library_id():<br>    result = defaultdict(int)</pre><pre>    books = Book.objects.all().prefetch_related(&#39;pages&#39;)</pre><pre>    for book in books:<br>        result[book.library_id] += book.get_page_count()</pre><pre><strong>    return</strong> result</pre><p>Even though this will only fire off two queries, we still have to pull all of the books into memory and loop over each one of them. This sort of thing can easily be turned into an <a href="https://docs.djangoproject.com/en/2.1/ref/models/querysets/#annotate">annotation</a>.</p><pre><strong>from</strong> django.db.models <strong>import</strong> Sum</pre><pre><strong>def</strong> get_page_count_by_library_id_using_annotation():<br>    result = {}</pre><pre>    libraries = (<br>        Library.objects<br>        .all()<br>        .annotate(page_count=Sum(&#39;books__pages&#39;))<br>        .values_list(&#39;id&#39;, &#39;page_count&#39;)<br>    )</pre><pre>    for library_id, page_count in libraries:<br>        result[library_id] = page_count</pre><pre><strong>    return</strong> result</pre><p>Now, instead of pulling a bunch of Django instances into memory and calling a model method on each of them, you’re only pulling the two values you actually care about for each Library: the id and page_count. Our new function runs about 115x faster than the original.</p><pre>In [66]: timeit(get_page_count_by_library_id, number=10)<br>Out[66]: 158.0743614450039<br>In [67]: timeit(get_page_count_by_library_id_using_annotation, number=10)<br>Out[67]: 1.3725216790044215</pre><p>This example is pretty simple but there’s a lot you can do with annotations. If you’re running into performance issues while doing math on a large queryset, consider writing an annotation to offload that work to the database.</p><h4>Wrapping up</h4><p>If you’re working on a Django-based project where there has been little or no thought regarding performance, there should be quite a bit of low hanging fruit to get you started. In the majority of cases, the techniques described above will provide a substantial performance boost without much of a trade off in terms of readability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebd19089a33f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>