<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Lucas Magnum</title>
    <description>The latest articles on DEV Community by Lucas Magnum (@lucasmagnum).</description>
    <link>https://dev.to/lucasmagnum</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F324697%2Fb2c76535-161e-424c-a645-49c2003a69ca.jpeg</url>
      <title>DEV Community: Lucas Magnum</title>
      <link>https://dev.to/lucasmagnum</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/lucasmagnum"/>
    <language>en</language>
    <item>
      <title>Hello world!</title>
      <dc:creator>Lucas Magnum</dc:creator>
      <pubDate>Fri, 12 Feb 2021 17:35:45 +0000</pubDate>
      <link>https://dev.to/codechallenges/hello-world-511e</link>
      <guid>https://dev.to/codechallenges/hello-world-511e</guid>
      <description>&lt;p&gt;Hello CodeChallenges.dev.br!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>#DjangoTip: Select &amp; Prefetch Related</title>
      <dc:creator>Lucas Magnum</dc:creator>
      <pubDate>Thu, 30 Jan 2020 15:09:55 +0000</pubDate>
      <link>https://dev.to/lucasmagnum/djangotip-select-prefetch-related-402i</link>
      <guid>https://dev.to/lucasmagnum/djangotip-select-prefetch-related-402i</guid>
      <description>&lt;p&gt;Today the &lt;strong&gt;#DjangoTip&lt;/strong&gt; will be about using &lt;code&gt;select_related&lt;/code&gt; and &lt;code&gt;prefetch_related&lt;/code&gt; to improve our queries performance.&lt;/p&gt;

&lt;p&gt;You can clone this project from &lt;code&gt;[http://github.com/LucasMagnum/django-tip-02](http://github.com/LucasMagnum/django-tip-02)&lt;/code&gt; and follow the examples below.&lt;/p&gt;

&lt;p&gt;It takes time to fully understand how &lt;code&gt;select_related&lt;/code&gt; and &lt;code&gt;prefetch_related&lt;/code&gt; works, so keep looking for other resources and I hope this post helps you to understand a bit more. Code and have fun ❤&lt;/p&gt;

&lt;p&gt;Before we start, let me ask you one question; &lt;strong&gt;Did you clapped today? I would love to hear your claps and read your feedback!&lt;/strong&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Product model
&lt;/h4&gt;

&lt;p&gt;This will be the model used in all examples below, so we can always come back here and read it again.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/LucasMagnum/django-tip-02/blob/master/app/products/models.py" rel="noopener noreferrer"&gt;https://github.com/LucasMagnum/django-tip-02/blob/master/app/products/models.py&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It’s pretty simple, right? The &lt;code&gt;Product&lt;/code&gt; has a &lt;strong&gt;foreign key relationship&lt;/strong&gt; with the &lt;code&gt;Category&lt;/code&gt; and the &lt;code&gt;Category&lt;/code&gt; has one &lt;strong&gt;many to many relationships&lt;/strong&gt; with itself.&lt;/p&gt;

&lt;p&gt;Let’s start, shall we?&lt;/p&gt;

&lt;h4&gt;
  
  
  List of products
&lt;/h4&gt;

&lt;p&gt;Let’s start creating a list of products function, this function will return one list of dicts with the fields: &lt;code&gt;id&lt;/code&gt;, &lt;code&gt;title&lt;/code&gt; and &lt;code&gt;category&lt;/code&gt; name:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/LucasMagnum/django-tip-02/blob/master/app/products/queries.py#L128" rel="noopener noreferrer"&gt;https://github.com/LucasMagnum/django-tip-02/blob/master/app/products/queries.py#L128&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For test our function, we need products into our database. We have one command to load products into the database, just execute the &lt;code&gt;load_products&lt;/code&gt; command and 500 products and 50 categories will be inserted into our database.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AIB1_AevBbdm2jDa_Km3EuQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AIB1_AevBbdm2jDa_Km3EuQ.png" alt="python app/manage.py load\_products"&gt;&lt;/a&gt;&lt;br&gt;
python app/manage.py load_products&lt;/p&gt;

&lt;p&gt;Now we open our &lt;code&gt;shell&lt;/code&gt; running &lt;code&gt;python app/manage.py shell&lt;/code&gt; and test our function:&lt;/p&gt;

&lt;p&gt;We have all our products, but what’s the problem with this function?&lt;br&gt;
Let’s see how many queries this function does into the database:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Note:&lt;/em&gt;&lt;/strong&gt; &lt;em&gt;I created one&lt;/em&gt; &lt;a href="https://github.com/LucasMagnum/django-tip-02/blob/master/app/products/decorators.py" rel="noopener noreferrer"&gt;&lt;em&gt;debugger decorator&lt;/em&gt;&lt;/a&gt; &lt;em&gt;to see how many queries each example takes, you don’t have to understand how it works, just have in mind that it shows the number of the queries and the time in seconds for each example :p&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AZ0NFMcHNM7oFdyh7zEy91Q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AZ0NFMcHNM7oFdyh7zEy91Q.png" alt="[https://gist.github.com/LucasMagnum/81a122b7317baccf7c6bb4c9c549c928](https://gist.github.com/LucasMagnum/81a122b7317baccf7c6bb4c9c549c928)"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://gist.github.com/LucasMagnum/81a122b7317baccf7c6bb4c9c549c928" rel="noopener noreferrer"&gt;https://gist.github.com/LucasMagnum/81a122b7317baccf7c6bb4c9c549c928&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Wow! 501 queries for that simple piece of code?? What happened?&lt;/p&gt;

&lt;p&gt;For each time we access one &lt;code&gt;foreign key&lt;/code&gt; that is not in cache, another&lt;br&gt;
query will be made to retrieve the value.&lt;/p&gt;

&lt;p&gt;In our case, we accessing the &lt;code&gt;category&lt;/code&gt; inside a loop, one query will be made for each time the loop executes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;product&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;product_qs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
   &lt;span class="n"&gt;products&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
       &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;id&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;product&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
       &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;title&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;product&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;title&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
       &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;category&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;product&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;category&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;
   &lt;span class="p"&gt;})&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To avoid this high number of queries when accessing &lt;code&gt;foreign keys&lt;/code&gt; or &lt;code&gt;one to one fields&lt;/code&gt; we can use the &lt;code&gt;select_related&lt;/code&gt; method.&lt;/p&gt;

&lt;h4&gt;
  
  
  Select related
&lt;/h4&gt;

&lt;p&gt;We can use the &lt;code&gt;select_related&lt;/code&gt; method to load the &lt;code&gt;foreign key&lt;/code&gt; values and cache those results for each object. By default Django ORM doesn’t make a JOIN for our results, so each time we need to access the foreign key another query will be made.&lt;/p&gt;

&lt;p&gt;Let’s change our code to use the &lt;code&gt;select_related&lt;/code&gt; with our products queryset:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/LucasMagnum/django-tip-02/blob/master/app/products/queries.py#L148" rel="noopener noreferrer"&gt;https://github.com/LucasMagnum/django-tip-02/blob/master/app/products/queries.py#L148&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we can verify that these two functions return the same values and see how many queries the &lt;code&gt;products_list_select_related&lt;/code&gt; does:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AKk0AczWgt-ady5kWoSLBJw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AKk0AczWgt-ady5kWoSLBJw.png" alt="[https://gist.github.com/LucasMagnum/5d5e54e80a7ec4b1c1b399e65081a4c4](https://gist.github.com/LucasMagnum/5d5e54e80a7ec4b1c1b399e65081a4c4)"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://gist.github.com/LucasMagnum/5d5e54e80a7ec4b1c1b399e65081a4c4" rel="noopener noreferrer"&gt;https://gist.github.com/LucasMagnum/5d5e54e80a7ec4b1c1b399e65081a4c4&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Congrats! Now we did only 1 query instead of 501, it’s a real improvement :D&lt;/p&gt;
&lt;h4&gt;
  
  
  List of categories
&lt;/h4&gt;

&lt;p&gt;It was an amazing improvement on the last function, now we will create a list of categories function, this will help us to understand the behavior of the &lt;code&gt;prefetch_related&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;Let’s create our categories list function to retrieve all categories and their subcategories. This function should return the &lt;code&gt;name&lt;/code&gt;, &lt;code&gt;is_active&lt;/code&gt; and a &lt;code&gt;subcategories&lt;/code&gt; list for each category.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/LucasMagnum/django-tip-02/blob/master/app/products/queries.py#L7" rel="noopener noreferrer"&gt;https://github.com/LucasMagnum/django-tip-02/blob/master/app/products/queries.py#L7&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If we run this function in the debugger mode, we will see how many queries this function is doing:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F600%2F1%2AxOogWcdKM3DHuNiwNCehhA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F600%2F1%2AxOogWcdKM3DHuNiwNCehhA.png" alt="[https://gist.github.com/LucasMagnum/b35cb3d6158644ebbc40ca7e345896ed](https://gist.github.com/LucasMagnum/b35cb3d6158644ebbc40ca7e345896ed)"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://gist.github.com/LucasMagnum/b35cb3d6158644ebbc40ca7e345896ed" rel="noopener noreferrer"&gt;https://gist.github.com/LucasMagnum/b35cb3d6158644ebbc40ca7e345896ed&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Ok, we saw this problem before, we just need to add the &lt;code&gt;select_related&lt;/code&gt; and we will end up with just one query, right? Err, No!&lt;/p&gt;

&lt;p&gt;If we try to change the &lt;code&gt;categories_qs&lt;/code&gt; to use &lt;code&gt;select_related&lt;/code&gt; we will receive an error from Django:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AVEz35_u2GcVUTIjsACvd0w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AVEz35_u2GcVUTIjsACvd0w.png" alt="Exception when trying to use select\_related in a many to many field"&gt;&lt;/a&gt;&lt;br&gt;
Exception when trying to use select_related in a many to many field&lt;/p&gt;

&lt;p&gt;We can not use the &lt;code&gt;select_related&lt;/code&gt; with &lt;code&gt;many to many relationships&lt;/code&gt;, do you remember? To improve our queries we need to use a new method called &lt;code&gt;prefetch_related&lt;/code&gt; .&lt;/p&gt;
&lt;h4&gt;
  
  
  Prefetch related
&lt;/h4&gt;

&lt;p&gt;When we are using &lt;code&gt;many to many relationships&lt;/code&gt; we could use &lt;code&gt;prefetch_related&lt;/code&gt; method to booster our queries =D&lt;/p&gt;

&lt;p&gt;Let’s create another function using the &lt;code&gt;prefetch_related&lt;/code&gt; to see our improvements:&lt;/p&gt;

&lt;p&gt;Categories list using prefetch related to improve our queries.&lt;/p&gt;

&lt;p&gt;We just changed the line 5 to use &lt;code&gt;prefetch_related&lt;/code&gt; on &lt;code&gt;subcategories&lt;/code&gt; field. Now let’s see how many queries this new function is doing:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F600%2F1%2AvMMYH8ae0p4Ub2L1vZ0T4w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F600%2F1%2AvMMYH8ae0p4Ub2L1vZ0T4w.png" alt="[https://gist.github.com/LucasMagnum/efe74895552ebd24c5897db90b81712a](https://gist.github.com/LucasMagnum/efe74895552ebd24c5897db90b81712a)"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://gist.github.com/LucasMagnum/efe74895552ebd24c5897db90b81712a" rel="noopener noreferrer"&gt;https://gist.github.com/LucasMagnum/efe74895552ebd24c5897db90b81712a&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Good job! We improved the performance of our query, but wait for a second, why we have &lt;strong&gt;two&lt;/strong&gt; queries?&lt;/p&gt;

&lt;p&gt;Different from &lt;code&gt;select_related&lt;/code&gt; the &lt;code&gt;prefetch_related&lt;/code&gt; made the JOIN using Python rather than in the database.&lt;/p&gt;

&lt;p&gt;In this case, Django made two queries and then join the results into one queryset for us.&lt;/p&gt;

&lt;p&gt;Let’s create a new function that will return only the active subcategories using the prefetch_related:&lt;/p&gt;

&lt;p&gt;Categories list using the prefetch related function.&lt;/p&gt;

&lt;p&gt;Now, when we run the debugger for this function, we see:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AN_W-xbJ8nGx4H51rqppWcg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AN_W-xbJ8nGx4H51rqppWcg.png" alt="[https://gist.github.com/LucasMagnum/f5022fc09830a21c534e8ca1f2b8bd92](https://gist.github.com/LucasMagnum/f5022fc09830a21c534e8ca1f2b8bd92)"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://gist.github.com/LucasMagnum/f5022fc09830a21c534e8ca1f2b8bd92" rel="noopener noreferrer"&gt;https://gist.github.com/LucasMagnum/f5022fc09830a21c534e8ca1f2b8bd92&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;WOW! We increased the number of queries, how it’s possible?????&lt;/strong&gt;&lt;br&gt;
Calm down, there is a reason for this:&lt;/p&gt;

&lt;p&gt;When we use the &lt;code&gt;prefetch related&lt;/code&gt; we are saying to Django we want all the results to be JOINED, but when we use the &lt;code&gt;filter(is_active=True)&lt;/code&gt; we are changing the primary query and then Django doesn’t JOIN the right results for us.&lt;/p&gt;

&lt;p&gt;That’s why we have 52 queries, 51 queries iterating over the categories and 1 query to get all the results in prefetch.&lt;/p&gt;

&lt;p&gt;Let’s see how to solve this problem using the new &lt;code&gt;Prefetch&lt;/code&gt; introduced recently by Django (;&lt;/p&gt;
&lt;h4&gt;
  
  
  &lt;strong&gt;Using Prefetch with to_attr&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;Prefetch using to_attr to return prefetch related values&lt;/p&gt;

&lt;p&gt;There’s two changes in this new function, I changed the &lt;code&gt;categories_qs&lt;/code&gt; query to use the custom &lt;code&gt;Prefetch&lt;/code&gt; and changed the loop to use a new attribute &lt;code&gt;active_subcategories&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Let’s understand what it is doing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;Category&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;objects&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;prefetch_related&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nc"&gt;Prefetch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
         &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;subcategories&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
          &lt;span class="n"&gt;queryset&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;Category&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;objects&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;filter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;is_active&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
          &lt;span class="n"&gt;to_attr&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;active_subcategories&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are prefetching all values from &lt;code&gt;subcategories&lt;/code&gt;field, using the &lt;code&gt;Category.objects.filter(is_active=True)&lt;/code&gt; as &lt;code&gt;base queryset&lt;/code&gt; and passing telling Django we want all the prefetched values into the attribute &lt;code&gt;active_subcategories&lt;/code&gt;. This will create an attribute &lt;code&gt;active_subcategories&lt;/code&gt; for each &lt;code&gt;category&lt;/code&gt; returned by our &lt;code&gt;queryset&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We can see it in our &lt;code&gt;django shell&lt;/code&gt; :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F600%2F1%2AAI6rKYRIgGyoS6x5kX9B-w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F600%2F1%2AAI6rKYRIgGyoS6x5kX9B-w.png" alt="[https://gist.github.com/LucasMagnum/a13afb6ad657136d7c17f5e53d2a6f68](https://gist.github.com/LucasMagnum/a13afb6ad657136d7c17f5e53d2a6f68)"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://gist.github.com/LucasMagnum/a13afb6ad657136d7c17f5e53d2a6f68" rel="noopener noreferrer"&gt;https://gist.github.com/LucasMagnum/a13afb6ad657136d7c17f5e53d2a6f68&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As we can see, when we try to access the &lt;code&gt;active_subcategories&lt;/code&gt; without making the prefetch related we will receive an error.&lt;/p&gt;

&lt;p&gt;We need to use the new &lt;code&gt;Prefetch&lt;/code&gt; to set the new attribute for our use.&lt;/p&gt;

&lt;p&gt;Now we will make a new query to prefetch all the results;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AGSs7Jdw0MT3nhdEpHJVTNg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AGSs7Jdw0MT3nhdEpHJVTNg.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;YEES!! Now we can understand a bit better how the new &lt;code&gt;Prefetch&lt;/code&gt; works.&lt;/p&gt;

&lt;p&gt;Let’s debug our function now:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AYOaoMGQRLhZLLYSHpbM09w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AYOaoMGQRLhZLLYSHpbM09w.png" alt="[https://gist.github.com/LucasMagnum/f6060fe8bc0a1390aed0e27439eb029b](https://gist.github.com/LucasMagnum/f6060fe8bc0a1390aed0e27439eb029b)"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://gist.github.com/LucasMagnum/f6060fe8bc0a1390aed0e27439eb029b" rel="noopener noreferrer"&gt;https://gist.github.com/LucasMagnum/f6060fe8bc0a1390aed0e27439eb029b&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Great!! Now we have only two queries and not 52 =D&lt;/p&gt;

&lt;p&gt;Let’s how we could achieve the same result without using the &lt;code&gt;to_attr&lt;/code&gt; parameter.&lt;/p&gt;

&lt;h4&gt;
  
  
  Using Prefetch without to_attr
&lt;/h4&gt;

&lt;p&gt;If we don’t want to create a new attribute, we can reuse the attribute from the field and just change our base query:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://gist.github.com/LucasMagnum/21074818968d99d7507d24526fa63818" rel="noopener noreferrer"&gt;https://gist.github.com/LucasMagnum/21074818968d99d7507d24526fa63818&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here, we are using the &lt;code&gt;Prefetch&lt;/code&gt; without specifying an attribute.&lt;br&gt;
When we are accessing the &lt;code&gt;category.subcategories&lt;/code&gt; we are using the values from the &lt;code&gt;Prefetch&lt;/code&gt;, so we don’t need to filter the &lt;code&gt;is_active&lt;/code&gt; here because the results will come filtered =)&lt;/p&gt;

&lt;p&gt;And if we debug this function, we still have only two queries:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AW2GYvFx1n5tm9F7SxqMZLQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AW2GYvFx1n5tm9F7SxqMZLQ.png" alt="[https://gist.github.com/LucasMagnum/5bda88c72978ad4679b8062a5cd7d6b0](https://gist.github.com/LucasMagnum/5bda88c72978ad4679b8062a5cd7d6b0)"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://gist.github.com/LucasMagnum/5bda88c72978ad4679b8062a5cd7d6b0" rel="noopener noreferrer"&gt;https://gist.github.com/LucasMagnum/5bda88c72978ad4679b8062a5cd7d6b0&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can check if our functions are returning the same values:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AZbNvx0LHh3w1ouNPNrliGg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F800%2F1%2AZbNvx0LHh3w1ouNPNrliGg.png" alt="[https://gist.github.com/LucasMagnum/65425f73807da299b08acac8ef393daa](https://gist.github.com/LucasMagnum/65425f73807da299b08acac8ef393daa)"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://gist.github.com/LucasMagnum/65425f73807da299b08acac8ef393daa" rel="noopener noreferrer"&gt;https://gist.github.com/LucasMagnum/65425f73807da299b08acac8ef393daa&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;FANTASTIC!!! Everything is working and I hope that you learned a bit more about the new Prefetch today =)&lt;/p&gt;

&lt;h4&gt;
  
  
  &lt;strong&gt;TL;DR;&lt;/strong&gt;
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;  Select related &amp;amp; Prefetch related are performance boosters&lt;/li&gt;
&lt;li&gt;  Select related does one query to JOIN the tables&lt;/li&gt;
&lt;li&gt;  Select related could be used with ForeignKey and OneToOneField&lt;/li&gt;
&lt;li&gt;  Select related doesn’t work with ManyToMany fields&lt;/li&gt;
&lt;li&gt;  Prefetch related makes two queries and do the JOIN using Python&lt;/li&gt;
&lt;li&gt;  Prefetch related loses it effect when you change the base query&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Useful links
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;a href="https://docs.djangoproject.com/en/1.11/ref/models/querysets/" rel="noopener noreferrer"&gt;https://docs.djangoproject.com/en/1.11/ref/models/querysets/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;a href="https://docs.djangoproject.com/en/1.11/ref/models/querysets/#prefetch-related" rel="noopener noreferrer"&gt;https://docs.djangoproject.com/en/1.11/ref/models/querysets/#prefetch-related&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;a href="https://docs.djangoproject.com/en/1.11/ref/models/querysets/#django.db.models.query.QuerySet.select_related" rel="noopener noreferrer"&gt;https://docs.djangoproject.com/en/1.11/ref/models/querysets/#django.db.models.query.QuerySet.select_related&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;See you later, keep coding and have fun ❤&lt;/p&gt;

</description>
      <category>python</category>
      <category>django</category>
    </item>
    <item>
      <title>Criando um CI de uma aplicação Django com Github Actions</title>
      <dc:creator>Lucas Magnum</dc:creator>
      <pubDate>Mon, 27 Jan 2020 01:36:12 +0000</pubDate>
      <link>https://dev.to/lucasmagnum/criando-um-ci-de-uma-aplicacao-django-com-github-actions-28dh</link>
      <guid>https://dev.to/lucasmagnum/criando-um-ci-de-uma-aplicacao-django-com-github-actions-28dh</guid>
      <description>&lt;p&gt;Hoje vamos aprender como criar uma pipeline de CI usando Github Actions.&lt;/p&gt;

&lt;p&gt;A configuração é bem simples e pode ser vista no vídeo abaixo:&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/KpSlY8leYFY"&gt;
&lt;/iframe&gt;
&lt;/p&gt;


&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vJ70wriM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://practicaldev-herokuapp-com.freetls.fastly.net/assets/github-logo-ba8488d21cd8ee1fee097b8410db9deaa41d0ca30b004c0c63de0a479114156f.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/LucasMagnum"&gt;
        LucasMagnum
      &lt;/a&gt; / &lt;a href="https://github.com/LucasMagnum/django-github-actions-ci"&gt;
        django-github-actions-ci
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      Application used in to create a simple CI with Github actions
    &lt;/h3&gt;
  &lt;/div&gt;
  &lt;div class="ltag-github-body"&gt;
    
&lt;div id="readme" class="md"&gt;
&lt;h1&gt;
Django Github Actions CI&lt;/h1&gt;
&lt;p&gt;&lt;a rel="noopener noreferrer" href="https://github.com/lucasmagnum/django-github-actions-ci/workflows/Python%20application/badge.svg"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--UmA18x3V--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://github.com/lucasmagnum/django-github-actions-ci/workflows/Python%2520application/badge.svg" alt="alt text"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Application used to create a simple CI with Github actions.&lt;/p&gt;
&lt;p&gt;Watch it: &lt;a href="https://www.youtube.com/watch?v=hzotqP2-O3k&amp;amp;feature=youtu.be" rel="nofollow"&gt;https://www.youtube.com/watch?v=hzotqP2-O3k&amp;amp;feature=youtu.be&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;



&lt;/div&gt;
&lt;br&gt;
  &lt;div class="gh-btn-container"&gt;&lt;a class="gh-btn" href="https://github.com/LucasMagnum/django-github-actions-ci"&gt;View on GitHub&lt;/a&gt;&lt;/div&gt;
&lt;br&gt;
&lt;/div&gt;
&lt;br&gt;


&lt;p&gt;Não esqueça de deixar seu feedback e se inscrever no canal :)&lt;/p&gt;

</description>
      <category>python</category>
      <category>django</category>
      <category>github</category>
      <category>testing</category>
    </item>
  </channel>
</rss>
