<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>django &amp;mdash; sandeepk</title>
    <link>https://blogs.dgplug.org/sandeepk/tag:django</link>
    <description></description>
    <pubDate>Sun, 19 Apr 2026 07:42:57 +0000</pubDate>
    <item>
      <title>The Debug Diary - Chapter I</title>
      <link>https://blogs.dgplug.org/sandeepk/the-debug-diary-chapter-i</link>
      <description>&lt;![CDATA[The Debug Diary - Chapter I&#xA;&#xA;Lately, I was debugging an issue with the importer tasks of our codebase and came across a code block which looks fine but makes an extra database query in the loop. When you have a look at the Django ORM query&#xA;&#xA;jatovehicles = JatoVehicle.objects.filter(&#xA;    yearin=availableyears,morefilters&#xA;).only(&#34;manufacturercode&#34;, &#34;uid&#34;, &#34;year&#34;, &#34;model&#34;, &#34;trim&#34;)&#xA;&#xA;for entry in jatovehicles.iterator():&#xA;    if entry.manufacturercode:&#xA;        logic&#xA;    ymtkey = (entry.year, entry.model, entry.trimprocessed)&#xA;...&#xA;you will notice we are using only, which only loads the set of fields mentioned and deferred other fields, but in the loop, we are using the field trimprocessed which is a deferred field and will result in an extra database call.&#xA;&#xA;Now, as we have identified the performance issue, the best way to handle the cases like this is to use values or valueslist. The use of only should be discouraged in the cases like these.&#xA;&#xA;Update code will look like this&#xA;jatovehicles = JatoVehicle.objects.filter(&#xA;    yearin=availableyears,more-filters).valueslist(&#xA;    &#34;manufacturercode&#34;,&#xA;    &#34;uid&#34;,&#xA;    &#34;year&#34;,&#xA;    &#34;model&#34;,&#xA;    &#34;trimprocessed&#34;,&#xA;    named=True,&#xA;)&#xA;&#xA;for entry in jatovehicles.iterator():&#xA;    if entry.manufacturercode:&#xA;        logic&#xA;    ymtkey = (entry.year, entry.model, entry.trimprocessed)&#xA;...&#xA;&#xA;By doing this, we are safe from accessing the fields which are not mentioned in the valueslist. If anyone tries to do so, an exception will be raised.&#xA;&#xA;** By using named=True we get the result as a named tuple which makes it easy to access the values :)&#xA;&#xA; &#xA;Cheers!&#xA;&#xA;Django&#xA;ORM&#xA;Debug]]&gt;</description>
      <content:encoded><![CDATA[<h2 id="the-debug-diary-chapter-i">The Debug Diary – Chapter I</h2>

<p>Lately, I was debugging an issue with the importer tasks of our codebase and came across a code block which looks fine but makes an extra database query in the loop. When you have a look at the Django ORM query</p>

<pre><code class="language-python">jato_vehicles = JatoVehicle.objects.filter(
    year__in=available_years,&lt;more_filters&gt;
).only(&#34;manufacturer_code&#34;, &#34;uid&#34;, &#34;year&#34;, &#34;model&#34;, &#34;trim&#34;)

for entry in jato_vehicles.iterator():
    if entry.manufacturer_code:
        &lt;logic&gt;
    ymt_key = (entry.year, entry.model, entry.trim_processed)
...
</code></pre>

<p>you will notice we are using <code>only</code>, which only loads the set of fields mentioned and deferred other fields, but in the loop, we are using the field <code>trim_processed</code> which is a deferred field and will result in an extra database call.</p>

<p>Now, as we have identified the performance issue, the best way to handle the cases like this is to use <code>values</code> or <code>values_list</code>. The use of <code>only</code> should be discouraged in the cases like these.</p>

<p>Update code will look like this</p>

<pre><code class="language-python">jato_vehicles = JatoVehicle.objects.filter(
    year__in=available_years,&lt;more-filters&gt;).values_list(
    &#34;manufacturer_code&#34;,
    &#34;uid&#34;,
    &#34;year&#34;,
    &#34;model&#34;,
    &#34;trim_processed&#34;,
    named=True,
)

for entry in jato_vehicles.iterator():
    if entry.manufacturer_code:
        &lt;logic&gt;
    ymt_key = (entry.year, entry.model, entry.trim_processed)
...
</code></pre>

<p>By doing this, we are safe from accessing the fields which are not mentioned in the <code>values_list</code>. If anyone tries to do so, an exception will be raised.</p>

<p>** By using <code>named=True</code> we get the result as a named tuple which makes it easy to access the values :)</p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:Django" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Django</span></a>
<a href="/sandeepk/tag:ORM" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">ORM</span></a>
<a href="/sandeepk/tag:Debug" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Debug</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/the-debug-diary-chapter-i</guid>
      <pubDate>Tue, 30 Aug 2022 07:34:12 +0000</pubDate>
    </item>
    <item>
      <title>Django: How to acquire a lock on the database rows? </title>
      <link>https://blogs.dgplug.org/sandeepk/django-how-to-acquire-a-lock-on-the-database-rows</link>
      <description>&lt;![CDATA[selectforupdate is the answer if you want to acquire a lock on the row. The lock is only released after the transaction is completed. This is similar to the Select for update statement in the SQL query.&#xA;&#xA;      Dealership.objects.selectforupdate().get(pk=&#39;iamid&#39;)&#xA;      # Here lock is only required on Dealership object&#xA;      Dealership.objects.selectrelated(&#39;oem&#39;).selectforupdate(of=(&#39;self&#39;,))&#xA;selectforupdate have these four arguments with these default value&#xA;nowait=False&#xA;skiplocked=False&#xA;of=()&#xA;nokey=False&#xA;&#xA;Let&#39;s see what these all arguments mean&#xA;&#xA;nowait&#xA;Think of the scenario where the lock is already acquired by another query, in this case, you want your query to wait or raise an error, This behavior can be controlled by nowait, If nowait=True we will raise the DatabaseError otherwise it will wait for the lock to be released.&#xA;skiplocked&#xA;As somewhat name implies, it helps to decide whether to consider a locked row in the evaluated query. If the skiplocked=true locked rows will not be considered.&#xA;&#xA;  nowait and skiplocked are mutually exclusive using both together will raise ValueError&#xA;&#xA;of&#xA;In selectforupdate when the query is evaluated, the lock is also acquired on the select related rows as in the query. If one doesn&#39;t wish the same, they can use of where they can specify fields to acquire a lock on&#xA;      Dealership.objects.selectrelated(&#39;oem&#39;).selectforupdate(of=(&#39;self&#39;,))&#xA;Just be sure we don&#39;t have any nullable relation with OEM&#xA;nokey&#xA;This helps you to create a weak lock. This means the other query can create new rows which refer to the locked rows (any reference relationship).&#xA;&#xA;Few more important points to keep in mind selectforupdate doesn&#39;t allow nullable relations, you have to explicitly exclude these nullable conditions. In auto-commit mode, selectforupdate fails with error TransactionManagementError you have to add code in a transaction explicitly. I have struggled around these points :).&#xA;&#xA;Here is all about selectforupdate which you require to know to use in your code and to do changes to your database.&#xA;&#xA;Cheers!&#xA;&#xA;Python&#xA;Django&#xA;ORM&#xA;Database&#xA;]]&gt;</description>
      <content:encoded><![CDATA[<p><code>select_for_update</code> is the answer if you want to acquire a lock on the row. The lock is only released after the transaction is completed. This is similar to the <code>Select for update statement</code> in the SQL query.</p>

<pre><code class="language-python">&gt;&gt;&gt; Dealership.objects.select_for_update().get(pk=&#39;iamid&#39;)
&gt;&gt;&gt; # Here lock is only required on Dealership object
&gt;&gt;&gt; Dealership.objects.select_related(&#39;oem&#39;).select_for_update(of=(&#39;self&#39;,))
</code></pre>

<p><code>select_for_update</code> have these four arguments with these default value
– nowait=False
– skip<em>locked=False
– of=()
– no</em>key=False</p>

<p>Let&#39;s see what these all arguments mean</p>

<h2 id="nowait">nowait</h2>

<p>Think of the scenario where the lock is already acquired by another query, in this case, you want your query to wait or raise an error, This behavior can be controlled by <code>nowait</code>, If <code>nowait=True</code> we will raise the <code>DatabaseError</code> otherwise it will wait for the lock to be released.</p>

<h2 id="skip-locked">skip_locked</h2>

<p>As somewhat name implies, it helps to decide whether to consider a locked row in the evaluated query. If the <code>skip_locked=true</code> locked rows will not be considered.</p>

<blockquote><p>nowait and skip_locked are mutually exclusive using both together will raise ValueError</p></blockquote>

<h2 id="of">of</h2>

<p>In <code>select_for_update</code> when the query is evaluated, the lock is also acquired on the select related rows as in the query. If one doesn&#39;t wish the same, they can use <code>of</code> where they can specify fields to acquire a lock on</p>

<pre><code class="language-python">&gt;&gt;&gt; Dealership.objects.select_related(&#39;oem&#39;).select_for_update(of=(&#39;self&#39;,))
# Just be sure we don&#39;t have any nullable relation with OEM
</code></pre>

<h2 id="no-key">no_key</h2>

<p>This helps you to create a weak lock. This means the other query can create new rows which refer to the locked rows (any reference relationship).</p>

<p>Few more important points to keep in mind <code>select_for_update</code> doesn&#39;t allow nullable relations, you have to explicitly exclude these nullable conditions. In auto-commit mode, <code>select_for_update</code> fails with error <code>TransactionManagementError</code> you have to add code in a transaction explicitly. I have struggled around these points :).</p>

<p>Here is all about <code>select_for_update</code> which you require to know to use in your code and to do changes to your database.</p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:Python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Python</span></a>
<a href="/sandeepk/tag:Django" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Django</span></a>
<a href="/sandeepk/tag:ORM" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">ORM</span></a>
<a href="/sandeepk/tag:Database" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Database</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/django-how-to-acquire-a-lock-on-the-database-rows</guid>
      <pubDate>Sat, 14 May 2022 14:06:03 +0000</pubDate>
    </item>
    <item>
      <title>Django: Many-to-One Relationship</title>
      <link>https://blogs.dgplug.org/sandeepk/django-many-to-one-relationship</link>
      <description>&lt;![CDATA[Today we are gone to talk about the Foreign Key which is used to establish a many-to-one relationship and different args which can be passed.&#xA;&#xA;Syntax to define a Foreign key relationship&#xA;from django.db import models&#xA;&#xA;class GSTRate(models.Model):&#xA;    # ...&#xA;    pass&#xA;&#xA;class PurchaseOrder(models.Model):&#xA;    gst = models.ForeignKey(GSTRate, ondelete=models.CASCADE)&#xA;&#xA;Different args for the Foreign Key&#xA;&#xA;ondelete&#xA;limitchoicesto&#xA;relatedname&#xA;relatedqueryname&#xA;tofield&#xA;dbconstraints&#xA;&#xA;ondelete&#xA;This args handle the process, of what to do if the reference keys are deleted, we have three options&#xA;CASCADE: It deletes the objects contains the Foreign key&#xA;PROTECT: It prevents the deletion of the referenced object by raising ProtectedError&#xA;RESTRICT: Introduced in Django 3.1, It only deletes the object, if another references object is being deleted in the same operation, but with CASCADE flow otherwise raise RestrictedError&#xA;&#xA;from django.db import models&#xA;&#xA;class GSTRate(models.Model):&#xA;    # ...&#xA;    pass&#xA;&#xA;class PurchaseOrder(models.Model):&#xA;    gst = models.ForeignKey(GSTRate, ondelete=models.CASCADE)&#xA;&#xA;limit\choices\to&#xA;This is helpful in the form rendering to restrict the option for the reference field. The limited choice can either be a dict, Q object  or a callable that return dict or Q object &#xA;&#xA;from django.db import models&#xA;&#xA;class GSTRate(models.Model):&#xA;    # ...&#xA;    pass&#xA;&#xA;class PurchaseOrder(models.Model):&#xA;    gst = models.ForeignKey(GSTRate, ondelete=models.CASCADE, limitchoicesto={&#39;taxtype&#39;: &#39;gst&#39;},)&#xA;here we only show the tax of type GST only.&#xA;&#xA;relatedname&#xA;It&#39;s the name that can be used for the reverse or backward reference while querying. You can also stop the backward relation by assigning  + in relatedname.&#xA;&#xA;class GSTRate(models.Model):&#xA;    # ...&#xA;    pass&#xA;&#xA;class PurchaseOrder(models.Model):&#xA;    gst = models.ForeignKey(GSTRate, ondelete=models.CASCADE, relatedname=&#39;+&#39;,) # IN this case GSTRate cannot backward realte to the Purchase Order obejct.&#xA;&#xA;class PurchaseOrder(models.Model):&#xA;    gst = models.ForeignKey(GSTRate, ondelete=models.CASCADE, relatedname=&#39;invoice&#39;)&#xA;&#xA;here you can refer to Invoice inside GSTRate query by the related name.&#xA;GSTRate.objects.filter(invoiceid=1232)&#xA;&#xA;related\query\name&#xA;It has the same value as the relatedname, unless not specified explicitly. If it is defined then you have to use that name while querying&#xA;&#xA;class GSTRate(models.Model):&#xA;    # ...&#xA;    pass&#xA;&#xA;class OrderConfirmation(models.Model):&#xA;    gst = models.ForeignKey(GSTRate, ondelete=models.CASCADE, relatedname=&#39;orderconfirmation&#39;, relatedqueryname=&#39;oc&#39;)&#xA;&#xA;here you can refer to Invoice inside GSTRate query by the related name.&#xA;GSTRate.objects.filter(ocid=112)&#xA;tofield&#xA;This is helpful in the case where you want to refer other the primary key of the modal, but the condition whatever key you referred it should be unique=True&#xA;&#xA;db_constraints&#xA;This is used to create a constraint at the database level, by default value is true and if the user sets the value to False, then accessing a related object that doesn’t exist will raise its DoesNotExist exception.&#xA;&#xA;Conclusion&#xA;These args are handy which gives us the possibilities of implementing the additional constraint and functionality to query data in the Django ORM query language.&#xA;&#xA;Cheers!&#xA;&#xA;#100DaysToOffload #Python#Django]]&gt;</description>
      <content:encoded><![CDATA[<p>Today we are gone to talk about the Foreign Key which is used to establish a many-to-one relationship and different args which can be passed.</p>

<p>Syntax to define a Foreign key relationship</p>

<pre><code class="language-python">from django.db import models

class GSTRate(models.Model):
    # ...
    pass

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE)
</code></pre>

<p>Different args for the <em>Foreign Key</em></p>
<ul><li>on_delete</li>
<li>limit<em>choices</em>to</li>
<li>related_name</li>
<li>related<em>query</em>name</li>
<li>to_field</li>
<li>db_constraints</li></ul>

<p><strong>on_delete</strong>
This args handle the process, of what to do if the reference keys are deleted, we have three options
– CASCADE: It deletes the objects contains the Foreign key
– PROTECT: It prevents the deletion of the referenced object by raising <em>ProtectedError</em>
– RESTRICT: Introduced in <strong>Django 3.1</strong>, It only deletes the object, if another references object is being deleted in the same operation, but with <em>CASCADE</em> flow otherwise raise <em>RestrictedError</em></p>

<pre><code class="language-python">from django.db import models

class GSTRate(models.Model):
    # ...
    pass

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE)
</code></pre>

<p><strong>limit_choices_to</strong>
This is helpful in the form rendering to restrict the option for the reference field. The limited choice can either be a <em>dict</em>, <em>Q object</em>  or a callable that return <em>dict</em> or <em>Q object</em></p>

<pre><code class="language-python">from django.db import models

class GSTRate(models.Model):
    # ...
    pass

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE, limit_choices_to={&#39;tax_type&#39;: &#39;gst&#39;},)
# here we only show the tax of type GST only.
</code></pre>

<p><strong>related_name</strong>
It&#39;s the name that can be used for the reverse or backward reference while querying. You can also stop the backward relation by assigning  <em>+</em> in related_name.</p>

<pre><code class="language-python">
class GSTRate(models.Model):
    # ...
    pass

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE, related_name=&#39;+&#39;,) # IN this case GSTRate cannot backward realte to the Purchase Order obejct.

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE, related_name=&#39;invoice&#39;)

# here you can refer to Invoice inside GSTRate query by the related name.
GSTRate.objects.filter(invoice_id=1232)
</code></pre>

<p><strong>related_query_name</strong>
It has the same value as the <em>related_name</em>, unless not specified explicitly. If it is defined then you have to use that name while querying</p>

<pre><code class="language-python">
class GSTRate(models.Model):
    # ...
    pass

class OrderConfirmation(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE, related_name=&#39;order_confirmation&#39;, related_query_name=&#39;oc&#39;)

# here you can refer to Invoice inside GSTRate query by the related name.
GSTRate.objects.filter(oc_id=112)
</code></pre>

<p><strong>to_field</strong>
This is helpful in the case where you want to refer other the primary key of the modal, but the condition whatever key you referred it should be <em>unique=True</em></p>

<p><strong>db_constraints</strong>
This is used to create a constraint at the database level, by default value is true and if the user sets the value to <em>False</em>, then accessing a related object that doesn’t exist will raise its <em>DoesNotExist</em> exception.</p>

<p><strong>Conclusion</strong>
These <em>args</em> are handy which gives us the possibilities of implementing the additional constraint and functionality to query data in the Django ORM query language.</p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:100DaysToOffload" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">100DaysToOffload</span></a> <a href="/sandeepk/tag:Python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Python</span></a><a href="/sandeepk/tag:Django" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Django</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/django-many-to-one-relationship</guid>
      <pubDate>Thu, 15 Apr 2021 16:21:50 +0000</pubDate>
    </item>
    <item>
      <title>Django: Template Tags and Filters</title>
      <link>https://blogs.dgplug.org/sandeepk/django-template-tags-and-filters</link>
      <description>&lt;![CDATA[Template is the one of powerful features of Django Framework, and we will discuss the tag and filter. If you do not have any idea about the template, please go read about that here, I will wait for you.&#xA;&#xA;Template tags which we are going to discuss today are&#xA;&#xA;URL&#xA;Now&#xA;Spaceless&#xA;&#xA;URL&#xA;The URL tag is the template equivalent of the reverse function. URL can accept args or kwargs for routes that expect other variables. &#xA;a href=&#34;{% url &#34;anamedview&#34; %}&#34;Go to a named view/a&#xA;Now&#xA;Now is a convenient method to display information about the current time. It was a problem solver for the copyright year update, which I first have to update every year manually.&#xA;&amp;copy; {% now &#34;Y&#34; %} sandeepk.dev.&#xA;Spaceless&#xA;It removes the whitespace, newline, tab from the HTML&#xA;{% spaceless %}&#xA;    div&#xA;        spanI am a good span./span&#xA;    /div&#xA;{% endspaceless %}&#xA;Now let&#39;s talk about the filter which we can use in the template.&#xA;&#xA;date&#xA;default&#xA;pluralize&#xA;yesno&#xA;&#xA;Date&#xA;This filter can be used to control the format of the datetime passed in the context of the response.&#xA;{{ birthdate|date:&#34;Y-m-d&#34; }}&#xA;Default&#xA;Have you ever been in a condition when you want to show a text for a falsy value, then default filter is the one thing you should use&#xA;{{ valuetocheck|default:&#34;Nothing to see here.&#34; }}&#xA;Pluralize&#xA;When your text considers counts of things. Pluralize can use to save you from if and else check&#xA;{ countitems }} item{{ countitems|pluralize }}&#xA;&#xA;0 items&#xA;1 item&#xA;2 items&#xA;3 items&#xA;(and so on)&#xA;YesNo&#xA;YesNo is good for converting True|False|None into a meaningful text message&#xA;{{ user.name }} has {{ useraccepted|yesno:&#34;accepted,declined,not RSVPed&#34; }} request.&#xA;These are the tags and filter which I use very often but there many more which you can check out here&#xA;&#xA;Cheers!&#xA;&#xA;#100DaysToOffload #Python #Django&#xA;]]&gt;</description>
      <content:encoded><![CDATA[<p>Template is the one of powerful features of Django Framework, and we will discuss the tag and filter. If you do not have any idea about the template, please go read about that <a href="https://docs.djangoproject.com/en/3.1/topics/templates/" rel="nofollow">here</a>, I will wait for you.</p>

<p>Template tags which we are going to discuss today are</p>
<ul><li>URL</li>
<li>Now</li>
<li>Spaceless</li></ul>

<p><strong>URL</strong>
The URL tag is the template equivalent of the reverse function. URL can accept args or kwargs for routes that expect other variables.</p>

<pre><code class="language-python">&lt;a href=&#34;{% url &#34;a_named_view&#34; %}&#34;&gt;Go to a named view&lt;/a&gt;
</code></pre>

<p><strong>Now</strong>
Now is a convenient method to display information about the current time. It was a problem solver for the copyright year update, which I first have to update every year manually.</p>

<pre><code class="language-python">&amp;copy; {% now &#34;Y&#34; %} sandeepk.dev.
</code></pre>

<p><strong>Spaceless</strong>
It removes the whitespace, newline, tab from the HTML</p>

<pre><code class="language-html">{% spaceless %}
    &lt;div&gt;
        &lt;span&gt;I am a good span.&lt;/span&gt;
    &lt;/div&gt;
{% endspaceless %}
</code></pre>

<p>Now let&#39;s talk about the filter which we can use in the template.</p>
<ul><li>date</li>
<li>default</li>
<li>pluralize</li>
<li>yesno</li></ul>

<p><strong>Date</strong>
This filter can be used to control the format of the datetime passed in the context of the response.</p>

<pre><code class="language-python">{{ birth_date|date:&#34;Y-m-d&#34; }}
</code></pre>

<p><strong>Default</strong>
Have you ever been in a condition when you want to show a text for a falsy value, then default filter is the one thing you should use</p>

<pre><code class="language-python">{{ value_to_check|default:&#34;Nothing to see here.&#34; }}
</code></pre>

<p><strong>Pluralize</strong>
When your text considers counts of things. Pluralize can use to save you from if and else check</p>

<pre><code class="language-python">{ count_items }} item{{ count_items|pluralize }}

0 items
1 item
2 items
3 items
(and so on)
</code></pre>

<p><strong>YesNo</strong>
YesNo is good for converting True|False|None into a meaningful text message</p>

<pre><code class="language-python">{{ user.name }} has {{ user_accepted|yesno:&#34;accepted,declined,not RSVPed&#34; }} request.
</code></pre>

<p>These are the tags and filter which I use very often but there many more which you can check out <a href="https://docs.djangoproject.com/en/3.0/ref/templates/builtins/" rel="nofollow">here</a></p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:100DaysToOffload" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">100DaysToOffload</span></a> <a href="/sandeepk/tag:Python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Python</span></a> <a href="/sandeepk/tag:Django" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Django</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/django-template-tags-and-filters</guid>
      <pubDate>Mon, 05 Apr 2021 15:14:38 +0000</pubDate>
    </item>
    <item>
      <title>Django: Connecting multiple databases.</title>
      <link>https://blogs.dgplug.org/sandeepk/django-connecting-multiple-databases</link>
      <description>&lt;![CDATA[Django provides the support of using multiple databases in your project. Let&#39;s see how we can do that, but first, let me put some use case where we might need multiple databases for our application.&#xA;Why need multiple databases?&#xA;In today&#39;s world, we are gathering a lot of data from user which is used for different purposes, some data is relational data and other is non-relational data. Let me put few use cases&#xA;&#xA;Suppose you need to record all the touchpoints of a web page in your web application, for this you need a non-relation database to store that data to run some analytical result on it.&#xA;Read replicas, you need to set up read replicas of your default database to speed up the fetching of data from the database.&#xA;Saving the email metadata like how many emails were sent, open rate, error rate, link clicked to see the engagement of the emails.&#xA;&#xA;Lets us see how to set up multiple databases in the Django project.&#xA;&#xA;Need to add the details of the databases in settings.py of Django project.&#xA;&#xA;DATABASES = {&#xA;    &#34;default&#34;: {&#xA;        &#34;ENGINE&#34;: &#34;django.db.backends.mysql&#34;,&#xA;        &#34;NAME&#34;: config.get(&#34;databasedefault&#34;, &#34;name&#34;),&#xA;        &#34;USER&#34;: config.get(&#34;databasedefault&#34;, &#34;user&#34;),&#xA;        &#34;PASSWORD&#34;: config.get(&#34;databasedefault&#34;, &#34;password&#34;),&#xA;        &#34;HOST&#34;: config.get(&#34;databasedefault&#34;, &#34;host&#34;),&#xA;        &#34;PORT&#34;: &#34;3306&#34;,&#xA;        &#34;CONNMAXAGE&#34;: 0,&#xA;    },&#xA;    &#34;replica1&#34;: {&#xA;        &#34;ENGINE&#34;: &#34;django.db.backends.mysql&#34;,&#xA;        &#34;NAME&#34;: config.get(&#34;databasereplica1&#34;, &#34;name&#34;),&#xA;        &#34;USER&#34;: config.get(&#34;databasereplica1&#34;, &#34;user&#34;),&#xA;        &#34;PASSWORD&#34;: config.get(&#34;databasereplica1&#34;, &#34;password&#34;),&#xA;        &#34;HOST&#34;: config.get(&#34;databasereplica1&#34;, &#34;host&#34;),&#xA;        &#34;PORT&#34;: &#34;3306&#34;,&#xA;        &#34;CONNMAXAGE&#34;: 0,&#xA;    },&#xA;    &#34;mongo&#34;: {&#xA;        &#34;ENGINE&#34;: &#34;djongo&#34;,&#xA;        &#34;NAME&#34;: config.get(&#34;mongodatabase&#34;, &#34;name&#34;),&#xA;        &#34;HOST&#34;: config.get(&#34;mongodatabase&#34;, &#34;host&#34;),&#xA;        &#34;USER&#34;: config.get(&#34;mongodatabase&#34;, &#34;user&#34;),&#xA;        &#34;PASSWORD&#34;: config.get(&#34;mongodatabase&#34;, &#34;password&#34;),&#xA;    },&#xA;}&#xA;&#xA;Here you can see we define 2 databases other than the default databases mongo and replica1. After this, you need to tell the Django router in which app you want to use which connection of database. This is one of the ways to do it, you can manually decide which database you want to use while querying.&#xA;&#xA;DATABASEROUTERS = [&#39;path.to.replica1&#39;, &#39;path.to.mongo&#39;]&#xA;&#xA;Now we need to define this router class to tell them which database to use, for that we need to write a class&#xA;&#xA;class MongoRouter:&#xA;    &#34;&#34;&#34;&#xA;    A router to control all database operations on models in the&#xA;    analytics and status applications.&#xA;    &#34;&#34;&#34;&#xA;    routeapplabels = {&#39;analytics&#39;, &#39;status&#39;}&#xA;&#xA;    def dbforread(self, model, hints):&#xA;        &#34;&#34;&#34;&#xA;        Attempts to read analytics and status models go to mongo db.&#xA;        &#34;&#34;&#34;&#xA;        if model.meta.applabel in self.routeapplabels:&#xA;            return &#39;mongo&#39;&#xA;        return None&#xA;&#xA;    def dbforwrite(self, model, hints):&#xA;        &#34;&#34;&#34;&#xA;        Attempts to write analytics and status models go to authdb.&#xA;        &#34;&#34;&#34;&#xA;        if model.meta.applabel in self.routeapplabels:&#xA;            return &#39;mongo&#39;&#xA;        return None&#xA;&#xA;    def allowrelation(self, obj1, obj2, hints):&#xA;        &#34;&#34;&#34;&#xA;        Allow relations if a model in the analytics and status apps is&#xA;        involved.&#xA;        &#34;&#34;&#34;&#xA;        if (&#xA;            obj1.meta.applabel in self.routeapplabels or&#xA;            obj2.meta.applabel in self.routeapplabels&#xA;        ):&#xA;           return True&#xA;        return None&#xA;&#xA;    def allowmigrate(self, db, applabel, modelname=None, hints):&#xA;        &#34;&#34;&#34;&#xA;        Make sure the analytics and status apps only appear in the&#xA;        &#39;mongo&#39; database.&#xA;        &#34;&#34;&#34;&#xA;        if applabel in self.routeapplabels:&#xA;            return db == &#39;mongo&#xA;        return None&#xA;&#xA;similar goes for replica1 database&#xA;&#xA;class ReplicaRouter:&#xA;    def dbforread(self, model, hints):&#xA;        &#34;&#34;&#34;&#xA;        Reads go to replica1.&#xA;        &#34;&#34;&#34;&#xA;        return &#39;replica1&#39;&#xA;&#xA;    def dbforwrite(self, model, hints):&#xA;        &#34;&#34;&#34;&#xA;        Writes always go to default.&#xA;        &#34;&#34;&#34;&#xA;        return &#39;default&#39;&#xA;&#xA;    def allowrelation(self, obj1, obj2, hints):&#xA;        &#34;&#34;&#34;&#xA;        Relations between objects are allowed if both objects are&#xA;        in the default/replica1 pool.&#xA;        &#34;&#34;&#34;&#xA;        dbset = {&#39;default&#39;, &#39;replica1&#39;}&#xA;        if obj1.state.db in dbset and obj2.state.db in dbset:&#xA;            return True&#xA;        return None&#xA;&#xA;    def allowmigrate(self, db, applabel, modelname=None, hints):&#xA;        &#34;&#34;&#34;&#xA;        All non-mongo models end up in this pool.&#xA;        &#34;&#34;&#34;&#xA;        return True&#xA;&#xA;That&#39;s it, now you read to use multiples database in your project, which we early handle by the routers class you have defined.&#xA;&#xA;Cheers!&#xA;&#xA;#100DaysToOffload #Django #Python]]&gt;</description>
      <content:encoded><![CDATA[<p>Django provides the support of using multiple databases in your project. Let&#39;s see how we can do that, but first, let me put some use case where we might need multiple databases for our application.
<strong>Why need multiple databases?</strong>
In today&#39;s world, we are gathering a lot of data from user which is used for different purposes, some data is relational data and other is non-relational data. Let me put few use cases</p>
<ul><li>Suppose you need to record all the touchpoints of a web page in your web application, for this you need a non-relation database to store that data to run some analytical result on it.</li>
<li>Read replicas, you need to set up read replicas of your default database to speed up the fetching of data from the database.</li>
<li>Saving the email metadata like how many emails were sent, open rate, error rate, link clicked to see the engagement of the emails.</li></ul>

<p>Lets us see how to set up multiple databases in the Django project.</p>
<ol><li>Need to add the details of the databases in <em>settings.py</em> of Django project.</li></ol>

<pre><code class="language-python">DATABASES = {
    &#34;default&#34;: {
        &#34;ENGINE&#34;: &#34;django.db.backends.mysql&#34;,
        &#34;NAME&#34;: config.get(&#34;database_default&#34;, &#34;name&#34;),
        &#34;USER&#34;: config.get(&#34;database_default&#34;, &#34;user&#34;),
        &#34;PASSWORD&#34;: config.get(&#34;database_default&#34;, &#34;password&#34;),
        &#34;HOST&#34;: config.get(&#34;database_default&#34;, &#34;host&#34;),
        &#34;PORT&#34;: &#34;3306&#34;,
        &#34;CONN_MAX_AGE&#34;: 0,
    },
    &#34;replica1&#34;: {
        &#34;ENGINE&#34;: &#34;django.db.backends.mysql&#34;,
        &#34;NAME&#34;: config.get(&#34;database_replica1&#34;, &#34;name&#34;),
        &#34;USER&#34;: config.get(&#34;database_replica1&#34;, &#34;user&#34;),
        &#34;PASSWORD&#34;: config.get(&#34;database_replica1&#34;, &#34;password&#34;),
        &#34;HOST&#34;: config.get(&#34;database_replica1&#34;, &#34;host&#34;),
        &#34;PORT&#34;: &#34;3306&#34;,
        &#34;CONN_MAX_AGE&#34;: 0,
    },
    &#34;mongo&#34;: {
        &#34;ENGINE&#34;: &#34;djongo&#34;,
        &#34;NAME&#34;: config.get(&#34;mongo_database&#34;, &#34;name&#34;),
        &#34;HOST&#34;: config.get(&#34;mongo_database&#34;, &#34;host&#34;),
        &#34;USER&#34;: config.get(&#34;mongo_database&#34;, &#34;user&#34;),
        &#34;PASSWORD&#34;: config.get(&#34;mongo_database&#34;, &#34;password&#34;),
    },
}
</code></pre>

<p>Here you can see we define 2 databases other than the default databases <em>mongo</em> and <em>replica1</em>. After this, you need to tell the Django <em>router</em> in which app you want to use which connection of database. This is one of the ways to do it, you can manually decide which database you want to use while querying.</p>

<pre><code class="language-python">DATABASE_ROUTERS = [&#39;path.to.replica1&#39;, &#39;path.to.mongo&#39;]
</code></pre>
<ol><li>Now we need to define this <em>router</em> class to tell them which database to use, for that we need to write a class</li></ol>

<pre><code class="language-python">class MongoRouter:
    &#34;&#34;&#34;
    A router to control all database operations on models in the
    analytics and status applications.
    &#34;&#34;&#34;
    route_app_labels = {&#39;analytics&#39;, &#39;status&#39;}

    def db_for_read(self, model, **hints):
        &#34;&#34;&#34;
        Attempts to read analytics and status models go to mongo db.
        &#34;&#34;&#34;
        if model._meta.app_label in self.route_app_labels:
            return &#39;mongo&#39;
        return None

    def db_for_write(self, model, **hints):
        &#34;&#34;&#34;
        Attempts to write analytics and status models go to auth_db.
        &#34;&#34;&#34;
        if model._meta.app_label in self.route_app_labels:
            return &#39;mongo&#39;
        return None

    def allow_relation(self, obj1, obj2, **hints):
        &#34;&#34;&#34;
        Allow relations if a model in the analytics and status apps is
        involved.
        &#34;&#34;&#34;
        if (
            obj1._meta.app_label in self.route_app_labels or
            obj2._meta.app_label in self.route_app_labels
        ):
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        &#34;&#34;&#34;
        Make sure the analytics and status apps only appear in the
        &#39;mongo&#39; database.
        &#34;&#34;&#34;
        if app_label in self.route_app_labels:
            return db == &#39;mongo
        return None
</code></pre>

<p>similar goes for replica1 database</p>

<pre><code class="language-python">
class ReplicaRouter:
    def db_for_read(self, model, **hints):
        &#34;&#34;&#34;
        Reads go to replica1.
        &#34;&#34;&#34;
        return &#39;replica1&#39;

    def db_for_write(self, model, **hints):
        &#34;&#34;&#34;
        Writes always go to default.
        &#34;&#34;&#34;
        return &#39;default&#39;

    def allow_relation(self, obj1, obj2, **hints):
        &#34;&#34;&#34;
        Relations between objects are allowed if both objects are
        in the default/replica1 pool.
        &#34;&#34;&#34;
        db_set = {&#39;default&#39;, &#39;replica1&#39;}
        if obj1._state.db in db_set and obj2._state.db in db_set:
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        &#34;&#34;&#34;
        All non-mongo models end up in this pool.
        &#34;&#34;&#34;
        return True
</code></pre>

<p>That&#39;s it, now you read to use multiples database in your project, which we early handle by the <em>routers</em> class you have defined.</p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:100DaysToOffload" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">100DaysToOffload</span></a> <a href="/sandeepk/tag:Django" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Django</span></a> <a href="/sandeepk/tag:Python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">Python</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/django-connecting-multiple-databases</guid>
      <pubDate>Sat, 13 Mar 2021 18:35:49 +0000</pubDate>
    </item>
    <item>
      <title>Django Model Abstraction</title>
      <link>https://blogs.dgplug.org/sandeepk/django-model-abstraction</link>
      <description>&lt;![CDATA[In Django, we can use the abstraction concept in defining the tables for the columns which are common. We can make any modal as an abstract model by adding this meta property  abstract = true.&#xA;&#xA;Suppose you have some column fields which are common in all the tables, which you can abstract and have to just inherit this abstract class to add the fields in the model which can help you to follow the Don&#39;t Repeat Yourself principle. Let see an example&#xA;&#xA;class Base(models.Model):&#xA;  &#34;&#34;&#34;&#xA;  Base parent class for all the models&#xA;  &#34;&#34;&#34;&#xA;  timestamp = models.DateTimeField(blank=True, dbindex=True)&#xA;  isactive = models.BooleanField(default=True, dbindex=True)&#xA;&#xA;  def init(self, args, kwargs):&#xA;    super(Base, self).init(args, *kwargs)&#xA;&#xA;  class Meta:&#xA;    abstract = True&#xA;&#xA;class OttPlatform(Base):&#xA;  &#34;&#34;&#34;&#xA;  &#34;&#34;&#34;&#xA;&#xA;  name = models.CharField(maxlength=200)&#xA;  otttype = models.CharField(maxlength=50)&#xA;&#xA;  def str(self):&#xA;    return self.name&#xA;&#xA;So, this helps you to stop duplication of code, but there is one more issue we can handle here. The isactive column is used to mark the row as deleted. Mainly in our use case, we can&#39;t delete the data from the table to keep the track of changes. So isactive field helps us with that. But now we have to use the isactive filter in every  query.&#xA;&#xA;We can solve this by overriding the manager, let see how&#xA;&#xA;First, define the Manager subclass.&#xA;class AtiveOTTManager(models.Manager):&#xA;    def getqueryset(self):&#xA;        return super().getqueryset().filter(isactive=True)&#xA;&#xA;class OttPlatform(Base):&#xA;  &#34;&#34;&#34;&#xA;  &#34;&#34;&#34;&#xA;&#xA;  name = models.CharField(maxlength=200)&#xA;  otttype = models.CharField(maxlength=50)&#xA;  &#xA;   # the order matters, first come default manager, then custom managers.&#xA;  objects = models.Manager() # The default manager.&#xA;  activeobjects = AtiveOTTManager() # The active OTT manager.&#xA;&#xA;  def str(self):&#xA;    return self.name&#xA;&#xA;Now you have to do OttPlatform.activeobjects.all(), to get all the active OTT platform name.&#xA;&#xA;So, with overriding the manager we don&#39;t have to write a filter for isactive* in every query.&#xA;&#xA;Cheers!&#xA;&#xA;#100DaysToOffload #django #python&#xA;]]&gt;</description>
      <content:encoded><![CDATA[<p>In Django, we can use the abstraction concept in defining the tables for the columns which are common. We can make any modal as an abstract model by adding this meta property  <em>abstract = true</em>.</p>

<p>Suppose you have some column fields which are common in all the tables, which you can abstract and have to just inherit this abstract class to add the fields in the model which can help you to follow the <em>Don&#39;t Repeat Yourself</em> principle. Let see an example</p>

<pre><code class="language-python">class Base(models.Model):
  &#34;&#34;&#34;
  Base parent class for all the models
  &#34;&#34;&#34;
  timestamp = models.DateTimeField(blank=True, db_index=True)
  is_active = models.BooleanField(default=True, db_index=True)

  def __init__(self, *args, **kwargs):
    super(Base, self).__init__(*args, **kwargs)

  class Meta:
    abstract = True

class OttPlatform(Base):
  &#34;&#34;&#34;
  &#34;&#34;&#34;

  name = models.CharField(max_length=200)
  ott_type = models.CharField(max_length=50)

  def __str__(self):
    return self.name
</code></pre>

<p>So, this helps you to stop duplication of code, but there is one more issue we can handle here. The <em>is_active</em> column is used to mark the row as deleted. Mainly in our use case, we can&#39;t delete the data from the table to keep the track of changes. So <em>is_active</em> field helps us with that. But now we have to use the <em>is_active</em> filter in every  query.</p>

<p>We can solve this by overriding the manager, let see how</p>

<pre><code class="language-python">
# First, define the Manager subclass.
class AtiveOTTManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(is_active=True)

class OttPlatform(Base):
  &#34;&#34;&#34;
  &#34;&#34;&#34;

  name = models.CharField(max_length=200)
  ott_type = models.CharField(max_length=50)
  
   # the order matters, first come default manager, then custom managers.
  objects = models.Manager() # The default manager.
  active_objects = AtiveOTTManager() # The active OTT manager.

  def __str__(self):
    return self.name

# Now you have to do OttPlatform.active_objects.all(), to get all the active OTT platform name.

</code></pre>

<p>So, with overriding the manager we don&#39;t have to write a filter for <em>is_active</em> in every query.</p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:100DaysToOffload" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">100DaysToOffload</span></a> <a href="/sandeepk/tag:django" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">django</span></a> <a href="/sandeepk/tag:python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">python</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/django-model-abstraction</guid>
      <pubDate>Sun, 07 Mar 2021 15:55:57 +0000</pubDate>
    </item>
    <item>
      <title>Django - Q() objects</title>
      <link>https://blogs.dgplug.org/sandeepk/django-q-objects</link>
      <description>&lt;![CDATA[Django Q() object helps to define SQL condition on the database and can be combined with the &amp;(AND) and |(or) operator. Q() helps in the flexibility of defining and reusing the conditions.&#xA;&#xA;Using Q() objects to make an AND conditions.&#xA;Using Q() objects to make an OR conditions.&#xA;Using Q() objects to make reusable conditions.&#xA;&#xA;Using Q() objects to make an AND conditions&#xA;We can use Q() objects to combine multiple filter conditions into one condition as filter conditions always perform AND operations.&#xA;&#xA;from django.db.models import Q&#xA;&#xA;Without Q() object&#xA;documentobj = Document.objects.filter(createdby=1282).filter(doctype=&#39;purchaseorder&#39;).filter(edit=0).filter(cancelled=0)&#xA;&#xA;With Q() object&#xA;qfilterdocument = Q(createdby=1282) &amp; Q(doctype=&#39;purchaseorder&#39;) &amp; Q(cancelled=0) &amp;(edit=0)&#xA;&#xA;can also be written as&#xA;qfilterdocumentanotherway = Q(createdby=1282, doctype=&#39;purchaseorder&#39;, cancelled=0, edit=0)&#xA;&#xA;documentobj = Document.objects.filter(qfilterdocument)&#xA;&#xA;Using Q() objects to make an OR conditions&#xA;&#xA;from django.db.models import Q&#xA;&#xA;With Q() object&#xA;qfilterdocument = Q(createdby=1282) | Q(createdby=1282)&#xA;documentobj = Document.objects.filter(qfilterdocument)&#xA;&#xA;Q() to make reusable filter condition&#xA;The best use of Q() objects is reusability, we define the Q() once and can use them to combine with different Q() objects with help of &amp;, |, and ~ operators.&#xA;&#xA;Let&#39;s consider a use case, in which the user can generate a report based on certain filters. User can filter report based on these values documenttype, isdraft, createdby, documentstatus&#xA;&#xA;def getdocumentobject(documenttype, isdraft, createdby, documentstatus):&#xA;    basequery = Q(active=1, cancelled=0, documenttye=documenttype, isdraft=isdraft)&#xA;&#xA;    # based on condition we can different Q() objects to filter the tables&#xA;    if documentstatus = &#39;inprogress&#39;:&#xA;        basequery = basequery &amp; Q(documentstatus=documentstatus, completed=0)&#xA;    else if documentstatus = &#39;completed&#39;:&#xA;        basequery = basequery &amp; Q(documentstatus=documentstatus, completed=1)&#xA;&#xA;   return Documents.objects.filter(base_query)&#xA;&#xA;In Q() objects we can use the same conditional operator which we use in filter objects like in operator, startswith, endswith, etc.&#xA;&#xA;Conclusion&#xA;Q() objects contribute to clean code and reusability. It helps to define the condition  with  &amp;, |, and ~ relation operator to simplify the complex queries.&#xA;&#xA;Cheers!&#xA;&#xA;#django #python #100DaysToOffload]]&gt;</description>
      <content:encoded><![CDATA[<p>Django Q() object helps to define SQL condition on the database and can be combined with the &amp;(AND) and |(or) operator. Q() helps in the flexibility of defining and reusing the conditions.</p>
<ul><li>Using Q() objects to make an AND conditions.</li>
<li>Using Q() objects to make an OR conditions.</li>
<li>Using Q() objects to make reusable conditions.</li></ul>

<p><strong>Using Q() objects to make an AND conditions</strong>
We can use Q() objects to combine multiple filter conditions into one condition as filter conditions always perform <em>AND</em> operations.</p>

<pre><code class="language-python">from django.db.models import Q

# Without Q() object
document_obj = Document.objects.filter(created_by=1282).filter(doc_type=&#39;purchase_order&#39;).filter(edit=0).filter(cancelled=0)

#With Q() object
q_filter_document = Q(created_by=1282) &amp; Q(doc_type=&#39;purchase_order&#39;) &amp; Q(cancelled=0) &amp;(edit=0)

# can also be written as
q_filter_document_another_way = Q(created_by=1282, doc_type=&#39;purchase_order&#39;, cancelled=0, edit=0)

document_obj = Document.objects.filter(q_filter_document)
</code></pre>

<p><strong>Using Q() objects to make an OR conditions</strong></p>

<pre><code class="language-python">from django.db.models import Q


#With Q() object
q_filter_document = Q(created_by=1282) | Q(created_by=1282)
document_obj = Document.objects.filter(q_filter_document)

</code></pre>

<p><strong>Q() to make reusable filter condition</strong>
The best use of Q() objects is reusability, we define the Q() once and can use them to combine with different Q() objects with help of <em>&amp;</em>, <em>|</em>, and <em>~</em> operators.</p>

<p>Let&#39;s consider a use case, in which the user can generate a report based on certain filters. User can filter report based on these values <em>document</em>type, is<em>draft, created</em>by, document<em>status</em></p>

<pre><code class="language-python">
def get_document_object(document_type, is_draft, created_by, document_status):
    base_query = Q(active=1, cancelled=0, document_tye=document_type, is_draft=is_draft)

    # based on condition we can different Q() objects to filter the tables
    if document_status = &#39;in_progress&#39;:
        base_query = base_query &amp; Q(document_status=document_status, completed=0)
    else if document_status = &#39;completed&#39;:
        base_query = base_query &amp; Q(document_status=document_status, completed=1)


   return Documents.objects.filter(base_query)

</code></pre>

<p>In Q() objects we can use the same conditional operator which we use in filter objects like in operator, startswith, endswith, etc.</p>

<p><strong>Conclusion</strong>
Q() objects contribute to clean code and reusability. It helps to define the condition  with  <em>&amp;</em>, <em>|</em>, and <em>~</em> relation operator to simplify the complex queries.</p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:django" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">django</span></a> <a href="/sandeepk/tag:python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">python</span></a> <a href="/sandeepk/tag:100DaysToOffload" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">100DaysToOffload</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/django-q-objects</guid>
      <pubDate>Tue, 02 Mar 2021 17:27:18 +0000</pubDate>
    </item>
    <item>
      <title>Django - Query Expression</title>
      <link>https://blogs.dgplug.org/sandeepk/django-query-expression</link>
      <description>&lt;![CDATA[In the previous blog post, we have discussed F() Expression, we will now explore more query expression in Django, to name few that we will discuss in this post are&#xA;&#xA;Func() Expression&#xA;Subquery Expression&#xA;Aggregation () Expression&#xA;&#xA;Func() Expression&#xA;Func () Expression is the base of all the expressions and can be used to create your custom expression for the database level function.&#xA;&#xA;The table that we using for our query is the Student which keeps records of the students for the whole school.&#xA;&#xA;from django.db.models import F, Func&#xA;studentobj = Student.objects.annotate(fullname=Func(F(&#39;firstname&#39;) + F(&#39;lastname&#39;), function=&#39;UPPER&#39;)&#xA;&#xA;This will give a student object with a new field that is fullname of the student in upper case.&#xA;&#xA;Subquery Expression&#xA;Subquery are like nested condition in the query filter which helps you to make a complex query into a clean concise query. But you need to know the order of the sequence the query will be executed to use effectively. While using a Subquery you will also need to know about the OuterRef, which is like an F() Expression but points to the parent query value, let see both Subquery and OuterRef in action&#xA;&#xA;you are given a task to get the name of the student whose name starts with S and whose fees are due.&#xA;&#xA;from django.db.models import OuterRef, Subquery&#xA;feeobjects = Fees.objects.filter(paymentduegt=0)&#xA;studentobj = Student.objects.filter(namestartswith=&#39;S&#39;).filter(idin=Subquery(feeobjects.values(&#39;studentid&#39;)))&#xA;&#xA;Get the lastest remarks for the students&#xA;remark = Remark.objects.filter(studentid=OuterRef(&#39;pk&#39;)).orderby(&#39;-createdat&#39;)&#xA;studentobj = Student.objects.annotate(newestremark=Subquery(remark.values(&#39;remarkstrl&#39;)[:1]))&#xA;&#xA;Aggregation () Expression&#xA;&#xA;Aggregation Expression is the Func Expression with GroupBy clause in the query filter.&#xA;&#xA;get the total student enrolled in the Blind Faith subject.&#xA;&#xA;studentobj = Student.objects.filter(subjectname=&#39;blindfaith&#39;).annotate(total_count=Count(&#39;id&#39;))&#xA;&#xA;Note: All queries mentioned above in the code are not tested. So if you see any typo, a query that does not make sense, feel free to reach out to me at sandeepchoudhary1507[at]gmail[DOT]com.&#xA;&#xA;Cheers!&#xA;&#xA;#100DaysToOffload  #django #python&#xA;]]&gt;</description>
      <content:encoded><![CDATA[<p>In the previous blog post, we have discussed <a href="https://blogs.dgplug.org/sandeepk/django-f-expression" rel="nofollow">F() Expression</a>, we will now explore more query expression in Django, to name few that we will discuss in this post are</p>
<ul><li><strong>Func() Expression</strong></li>
<li><strong>Subquery Expression</strong></li>
<li><strong>Aggregation () Expression</strong></li></ul>

<p><strong>Func() Expression</strong>
Func () Expression is the base of all the expressions and can be used to create your custom expression for the database level function.</p>

<pre><code class="language-python"># The table that we using for our query is the *Student* which keeps records of the students for the whole school.

from django.db.models import F, Func
student_obj = Student.objects.annotate(full_name=Func(F(&#39;first_name&#39;) + F(&#39;last_name&#39;), function=&#39;UPPER&#39;)

# This will give a student object with a new field that is *full_name* of the student in upper case.

</code></pre>

<p><strong>Subquery Expression</strong>
Subquery are like nested condition in the query filter which helps you to make a complex query into a clean concise query. But you need to know the order of the sequence the query will be executed to use effectively. While using a Subquery you will also need to know about the <em>OuterRef</em>, which is like an <a href="https://blogs.dgplug.org/sandeepk/django-f-expression" rel="nofollow">F() Expression</a> but points to the parent query value, let see both <em>Subquery</em> and <em>OuterRef</em> in action</p>

<pre><code class="language-python"># you are given a task to get the name of the student whose name starts with *S* and whose fees are due.

from django.db.models import OuterRef, Subquery
fee_objects = Fees.objects.filter(payment_due_gt=0)
student_obj = Student.objects.filter(name__startswith=&#39;S&#39;).filter(id__in=Subquery(fee_objects.values(&#39;student_id&#39;)))

# Get the lastest remarks for the students
remark = Remark.objects.filter(student_id=OuterRef(&#39;pk&#39;)).order_by(&#39;-created_at&#39;)
student_obj = Student.objects.annotate(newest_remark=Subquery(remark.values(&#39;remark_strl&#39;)[:1]))
</code></pre>

<p><strong>Aggregation () Expression</strong></p>

<p>Aggregation Expression is the <em>Func Expression</em> with <em>GroupBy</em> clause in the query filter.</p>

<pre><code class="language-python"># get the total student enrolled in the *Blind Faith* subject.

student_obj = Student.objects.filter(subject_name=&#39;blind_faith&#39;).annotate(total_count=Count(&#39;id&#39;))

</code></pre>

<p><em>Note: All queries mentioned above in the code are not tested. So if you see any typo, a query that does not make sense, feel free to reach out to me at sandeepchoudhary1507[at]gmail[DOT]com.</em></p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:100DaysToOffload" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">100DaysToOffload</span></a>  <a href="/sandeepk/tag:django" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">django</span></a> <a href="/sandeepk/tag:python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">python</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/django-query-expression</guid>
      <pubDate>Wed, 24 Feb 2021 17:25:01 +0000</pubDate>
    </item>
    <item>
      <title>Django- F() Expression</title>
      <link>https://blogs.dgplug.org/sandeepk/django-f-expression</link>
      <description>&lt;![CDATA[What is the F() Expression?&#xA;First let me explain to you what are Query Expressions are, these expressions let you use value or computation to be used in the update, create and filters, order by, annotation, aggregation.&#xA;F() object represent the value of the model fields or annotated columns. It lets you help to not load the value of the field into the python memory rather directly handles in the Database query.&#xA;&#xA;How to use the F() Expression?&#xA;To use the F expression you have to import them from the&#xA;from django.db.models import F and have to pass the name of the field or annotated column as argument, and it will return the value of the field from the database, without letting know the python any value. Let some example.&#xA;&#xA;from django.db.models import F&#xA;&#xA;Documents is the table which have the details of the document submitted by user from the registrey portal for GYM membership&#xA;&#xA;We need update the count of the document submitted by the user with pk=10091&#xA;&#xA;without using F Expression&#xA;&#xA;document = Documents.objects.get(userid=10091)&#xA;document.documentcounts += 1&#xA;document.save()&#xA;&#xA;Using F expression&#xA;document = Documents.objects.get(userid=10091)&#xA;document.documentcounts = F(&#39;documentcounts&#39;) + 1&#xA;document.save()&#xA;&#xA;Benefits of the F() Expression.&#xA;&#xA;With the help of F expression we can make are query clean and concise.&#xA;&#xA;    from django.db.models import F&#xA;  document = Documents.objects.get(userid=10091)&#xA;  document.update(documentcounts=F(&#39;documentcounts&#39;) + 1)&#xA;&#xA;   #Here we also have achieved some performance advantage&#xA;    #1. All the work is done at database level, rather than throwing the value from the database in the python memory to do the computation.&#xA;    #2. Save queries hit on the database.&#xA;  &#xA;F Expression can save you from the race condition. Consider a scenario where multiple user access your database and when bother user access the Document object for the user 10091, the count value is two, when user updates the value and save it and other user does the same the value will be saved as three not Four because when both user fetches the value its two.&#xA;&#xA;  # user A fetch the document object, and value of documentcounts is two.&#xA;  document = Documents.objects.get(userid=10091)&#xA;  document.documentcounts += 1&#xA;  document.save()&#xA;  # after the operation value of documentcounts is three&#xA;&#xA;  # Code running prallerly, User B also fetch the object, and value of documentcounts is two.&#xA;  document = Documents.objects.get(userid=10091)&#xA;  document.documentcounts  += 1&#xA;  document.save()&#xA;  # after the operation value of documentcounts is three&#xA;&#xA;  # But actually value should be Four, but this is not the case using F expression here will save use from this race condition.&#xA;  &#xA;F Expression are persistent, which means the query persist after the save operation, so you have to use the refreshfromdb to avoid the persistence.&#xA;&#xA;    document = Documents.objects.get(userid=10091)&#xA;  document.documentcounts = F(&#39;documentcounts&#39;) + 1&#xA;  document.save()&#xA;&#xA;  document.documentvalidation = 0&#xA;  document.save()&#xA;&#xA;  # This will increase the value of documentcounts by two rather then one as the query presists and calling save will trigger the increment again.&#xA;&#xA;  &#xA;More example of F Expression in action with filter, annotate query.&#xA;&#xA;from django.db.models import F&#xA;&#xA;annotation example&#xA;annotatedocument = Document.objects.filter(createdby=F(&#39;createdbyfirstname&#39;) + F(&#39;createdbylastname&#39;)&#xA;&#xA;filter example&#xA;filterdocument = Documents.objects.filter(totaldocumentscount_gt=F(&#39;validdocuments_count&#39;))&#xA;&#xA;That&#39;s all about the F Expression, it is pretty handy and helps you improve the performance, by reducing value loading in the memory and query hit optimization, but you have to keep an eye over the persistent issue, which I assume will not be the case if you are writing your code in structured way.&#xA;&#xA;Cheers!&#xA;&#xA;#100DaysToOffload #django #python&#xA;]]&gt;</description>
      <content:encoded><![CDATA[<p><strong>What is the F() Expression?</strong>
First let me explain to you what are Query Expressions are, these expressions let you use value or computation to be used in the update, create and filters, order by, annotation, aggregation.
<strong>F()</strong> object represent the value of the model fields or annotated columns. It lets you help to not load the value of the field into the python memory rather directly handles in the <em>Database</em> query.</p>

<p><strong>How to use the F() Expression?</strong>
To use the <strong>F</strong> expression you have to import them from the
<em>from django.db.models import F</em> and have to pass the name of the field or annotated column as argument, and it will return the value of the field from the database, without letting know the python any value. Let some example.</p>

<pre><code class="language-python3">from django.db.models import F

# Documents is the table which have the details of the document submitted by user from the registrey portal for GYM membership

# We need update the count of the document submitted by the user with pk=10091

# without using F Expression

document = Documents.objects.get(user_id=10091)
document.document_counts += 1
document.save()

# Using F expression
document = Documents.objects.get(user_id=10091)
document.document_counts = F(&#39;document_counts&#39;) + 1
document.save()
</code></pre>

<p><strong>Benefits of the <em>F()</em> Expression.</strong></p>
<ul><li>With the help of <strong>F</strong> expression we can make are query clean and concise.</li></ul>

<pre><code class="language-python3">    from django.db.models import F
  document = Documents.objects.get(user_id=10091)
  document.update(document_counts=F(&#39;document_counts&#39;) + 1)

   #Here we also have achieved some performance advantage
    #1. All the work is done at database level, rather than throwing the value from the database in the python memory to do the computation.
    #2. Save queries hit on the database.
</code></pre>
<ul><li><strong>F Expression</strong> can save you from the race condition. Consider a scenario where multiple user access your database and when bother user access the Document object for the user 10091, the count value is two, when user updates the value and save it and other user does the same the value will be saved as three not Four because when both user fetches the value its two.</li></ul>

<pre><code class="language-python3">
  # user A fetch the document object, and value of document_counts is two.
  document = Documents.objects.get(user_id=10091)
  document.document_counts += 1
  document.save()
  # after the operation value of document_counts is three

  # Code running prallerly, User B also fetch the object, and value of document_counts is two.
  document = Documents.objects.get(user_id=10091)
  document.document_counts  += 1
  document.save()
  # after the operation value of document_counts is three

  # But actually value should be Four, but this is not the case using F expression here will save use from this race condition.
</code></pre>
<ul><li><strong>F Expression</strong> are persistent, which means the query persist after the save operation, so you have to use the <em>refresh</em>from<em>db</em> to avoid the persistence.</li></ul>

<pre><code class="language-python3">  document = Documents.objects.get(user_id=10091)
  document.document_counts = F(&#39;document_counts&#39;) + 1
  document.save()

  document.document_validation = 0
  document.save()

  # This will increase the value of *document_counts* by two rather then one as the query presists and calling save will trigger the increment again.

</code></pre>
<ul><li>More example of <strong>F Expression</strong> in action with filter, annotate query.</li></ul>

<pre><code class="language-python3">from django.db.models import F

# annotation example
annotate_document = Document.objects.filter(created_by=F(&#39;created_by_first_name&#39;) + F(&#39;created_by_last_name&#39;)


# filter example
filter_document = Documents.objects.filter(total_documents_count__gt=F(&#39;valid_documents_count&#39;))
</code></pre>

<p>That&#39;s all about the <strong>F Expression</strong>, it is pretty handy and helps you improve the performance, by reducing value loading in the memory and query hit optimization, but you have to keep an eye over the persistent issue, which I assume will not be the case if you are writing your code in structured way.</p>

<p>Cheers!</p>

<p><a href="/sandeepk/tag:100DaysToOffload" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">100DaysToOffload</span></a> <a href="/sandeepk/tag:django" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">django</span></a> <a href="/sandeepk/tag:python" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">python</span></a></p>
]]></content:encoded>
      <guid>https://blogs.dgplug.org/sandeepk/django-f-expression</guid>
      <pubDate>Thu, 18 Feb 2021 17:26:29 +0000</pubDate>
    </item>
  </channel>
</rss>