<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Khalid Butt on Medium]]></title>
        <description><![CDATA[Stories by Khalid Butt on Medium]]></description>
        <link>https://medium.com/@im_khalidbutt?source=rss-4e75014dfc9a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gvCp9nrKmm5mcsKck3BJVg.jpeg</url>
            <title>Stories by Khalid Butt on Medium</title>
            <link>https://medium.com/@im_khalidbutt?source=rss-4e75014dfc9a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:44:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@im_khalidbutt/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Exploring Django Migrations]]></title>
            <link>https://medium.com/@im_khalidbutt/exploring-django-migrations-b36584fc1d34?source=rss-4e75014dfc9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b36584fc1d34</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Khalid Butt]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 12:36:26 GMT</pubDate>
            <atom:updated>2025-12-17T12:39:09.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WkIHJq0-Etlx8JXRh9P_sw.png" /></figure><p>First we need to know What is Migration?</p><p><strong>A migration</strong> is a way to track and apply changes to a database schema over time.</p><p>Whenever you add, remove, or modify:</p><ul><li>tables</li><li>columns</li><li>relationships</li><li>constraints</li></ul><p>you create a migration so the database structure stays in sync with your application code.</p><h4>What is Django Migration?</h4><p>In Django, <strong>migrations</strong> are Python files that describe changes to your models and translate them into database operations.</p><p><strong>Django migrations:</strong></p><blockquote>1. are <strong>auto-generated</strong> from your models.py<br>2. store changes in app_name/migrations/<br>3. keep your database schema aligned with your models<br>4. allow you to <strong>move forward and backward</strong> between schema versions</blockquote><h4>Why Django Uses Migrations</h4><p>Django migrations help you:</p><blockquote>1. Avoid manual SQL<br>2. Keep database and models in sync<br>3. Share schema changes with teams<br>4. Roll back changes if something goes wrong<br>5. Support multiple databases (MySQL, PostgreSQL, SQLite, etc.)</blockquote><p>Django supports different types of migrations based on <strong>what kind of change you are making</strong> to your database.</p><h3><strong>1. Model (Schema) Migrations:</strong></h3><p>These migrations handle <strong>structural changes</strong> in the database.</p><h4>How Django Migrations Work</h4><ul><li>You change something in models.py</li></ul><pre>python manage.py makemigrations #Django creates a migration file<br>python manage.py migrate #Django applies those changes to the database</pre><h3>2. Data Migrations</h3><p>Data migrations modify <strong>existing data</strong>, not just structure.</p><p>Used when you need to:</p><ul><li>populate default values</li><li>transform existing data</li><li>move or clean data after a schema change</li></ul><pre>#Creating Data Migration<br><br>python manage.py makemigrations app_name --empty</pre><pre>#Data Migration<br><br>from django.db import migrations<br><br>def add_default_status(apps, schema_editor):<br>    User = apps.get_model(&#39;app_name&#39;, &#39;User&#39;)<br>    User.objects.update(status=&#39;active&#39;)<br><br>class Migration(migrations.Migration):<br>    operations = [<br>        migrations.RunPython(add_default_status),<br>    ]</pre><h3>Squashing Migrations:</h3><p><strong>What is </strong>Squashing Migrations<strong>?</strong><br>Squashing Migrations Combining <strong>multiple migrations into one</strong> to reduce complexity.</p><h3>Why Squash?</h3><ul><li>Too many migrations (100+)</li><li>Old app with stable schema</li><li>Faster setup for new environments</li></ul><h3>How to Squash</h3><pre>python manage.py squashmigrations app_name 0001 0025</pre><p>Django creates: <strong>0001_squashed_0001_0025.py</strong></p><p>Inside:</p><pre>replaces = [<br>    (&#39;app_name&#39;, &#39;0001_initial&#39;),<br>    ...<br>    (&#39;app_name&#39;, &#39;0025_auto&#39;),<br>]</pre><h3>Real-World Example (Senior-Level)</h3><p><strong>Scenario:</strong><br>You add a status field and want existing records updated.</p><h3>Correct Approach</h3><ol><li>Schema migration → add field</li><li>Data migration → populate values</li><li>(Later) squash old migrations</li></ol><p>❌ <strong>Wrong Approach</strong><br> Setting defaults in model and assuming old records update automatically.</p><p>Here is the comparison table between Django Migrations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*adYcTwT6gBhYVMqNPW0K7w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b36584fc1d34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Inheritance Types in Django]]></title>
            <link>https://medium.com/@im_khalidbutt/model-inheritance-types-in-django-0db994f6b73c?source=rss-4e75014dfc9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/0db994f6b73c</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Khalid Butt]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 15:06:45 GMT</pubDate>
            <atom:updated>2025-12-03T15:16:28.240Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Inheritance?</h3><p><strong>Inheritance</strong> means <strong>one class takes (inherits) properties and behavior from another class.</strong></p><h3>Example:</h3><p>Think of a Car.</p><p>All cars have:</p><p>wheels, engine, seats</p><p>So we make a <strong>base class</strong>: <strong>Vehicle</strong><br>Car → inherits from Vehicle<br>Bike → inherits from Vehicle<br>Truck → inherits from Vehicle</p><h3>Why do we use inheritance?</h3><ul><li>To <strong>reuse code</strong></li><li>To avoid writing the same fields/methods again</li><li>To make your code <strong>clean and organized</strong></li><li>To build relationships between classes</li></ul><p>In Django there are <strong>three types</strong> of model inheritance:</p><ol><li><strong>Abstract Base Classes</strong></li><li><strong>Multi-table Inheritance</strong></li><li><strong>Proxy Models</strong></li></ol><h3><strong>Abstract Base Classes</strong></h3><p>ABC share common fields, methods, and metadata between multiple models <strong>without creating a table</strong> for the base class.<br>We use it when we want <strong>code reuse</strong>, not a database relationship.</p><pre>from django.db import models<br><br>class BaseModel(models.Model):<br>    created_at = models.DateTimeField(auto_now_add=True)<br>    updated_at = models.DateTimeField(auto_now=True)<br><br>    class Meta:<br>        abstract = True   # No table created<br><br>class Student(BaseModel):<br>    name = models.CharField(max_length=100)<br><br>class Teacher(BaseModel):<br>    name = models.CharField(max_length=100)</pre><p>Here BaseModel table will not create and Student and Teacher both get created_at and updated_at.</p><h3>Multi-table Inheritance</h3><p>Multi-Table Inheritance gets its own table, and Django creates an implicit OneToOneField linking child → parent. It is useful when child model extends parent’s fields.</p><pre>class Person(models.Model):<br>    name = models.CharField(max_length=100)<br><br>class Student(Person):<br>    roll_no = models.IntegerField()</pre><ul><li>Creates table <strong>person</strong></li><li>Creates table <strong>student</strong></li><li>Adds a hidden OneToOneField: student.person_ptr_id → person.id</li></ul><p>Here ptr stands for <strong>“pointer”. </strong>It is a <strong>hidden OneToOneField</strong> that Django automatically creates in the <strong>child table</strong> to link it to the <strong>parent table</strong>.</p><h3>Proxy Models</h3><p>Proxy model change <strong>behavior only</strong> (methods, default ordering, managers)<br> without creating additional tables. we use it we want to keep the <strong>same schema</strong> but adjust:</p><ul><li>ordering</li><li>custom queryset</li><li>permissions</li><li>methods</li></ul><pre>class Person(models.Model):<br>    name = models.CharField(max_length=100)<br>    age = models.IntegerField()<br><br>class YoungPerson(Person):<br>    class Meta:<br>        proxy = True<br>        ordering = [&#39;age&#39;]<br><br>    def is_minor(self):<br>        return self.age &lt; 18</pre><p>Here, Person table will create only.</p><h3>When to use which one?</h3><h3>✔ Use Abstract Base Class when</h3><ul><li>You want reusable fields/methods (timestamps, soft delete, audit model)</li><li>You don’t care about linking instances</li></ul><h3>✔ Use Multi-table when</h3><ul><li>You need extendable parent-child relations</li><li>Example: User → Student/User → Teacher</li><li>You want polymorphism in models</li></ul><h3>✔ Use Proxy Models when</h3><ul><li>You want different behavior on same DB table</li><li>You want to add custom manager/queryset</li><li>Example: ActiveUser, InactiveUser proxies</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Er0I0X1yx6Ee8Tf52jVfw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0db994f6b73c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Django Request Lifecycle]]></title>
            <link>https://medium.com/@im_khalidbutt/understanding-the-django-request-lifecycle-6ea5ea48caec?source=rss-4e75014dfc9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ea5ea48caec</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[lifecycle]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Khalid Butt]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 09:59:43 GMT</pubDate>
            <atom:updated>2025-04-23T13:00:29.729Z</atom:updated>
            <content:encoded><![CDATA[<p>The Django request lifecycle is the sequence of events that occur when a web request is made to a Django-powered web application.</p><p>1. User sends an HTTP request (via browser/Postman).<br>A user (via browser or client like Postman/cURL) sends an HTTP request to the Django web server.</p><p>2. Web server (e.g., Nginx/Gunicorn) receives the request.<br>The web server (Nginx/Gunicorn) receives the request and forwards it to the WSGI (Web Server Gateway Interface) application.</p><p>3. Request is passed to WSGI application (<a href="http://wsgi.py/">wsgi.py</a>).<br>The WSGI server calls Django’s get_response function from the WSGIHandler class.</p><p>4. Django loads <a href="http://settings.py/">settings.py</a> using DJANGO_SETTINGS_MODULE.<br>Django loads and uses settings internally throughout the entire lifecycle. It acts like the configuration brain of your Django project.</p><p>5. Request passes through middleware (pre-processing).<br>Before the view is called, Django passes the request through the middleware stack (defined in <a href="http://settings.py/">settings.py</a> under MIDDLEWARE).</p><p>Middlewares can:<br>Modify the request (process_request)<br>Stop the request and return a response early<br>Handle exceptions (process_exception)</p><p>6. URL dispatcher (<a href="http://urls.py/">urls.py</a>) matches the request path.<br>The request goes to the URL dispatcher (<a href="http://urls.py/">urls.py</a>) which matches the request path to a URL pattern</p><p>7. The matched view function or class-based view is called.<br>Django calls the matched view function or class-based view (CBV):<br>Business logic runs<br>Database queries are made<br>Context is created for templates<br>A HttpResponse object is returned (or JsonResponse, etc.)</p><p>8. Response goes through middleware again (post-processing).<br>After the view returns a response, Django passes the HttpResponse object back through the middleware stack (in reverse order)</p><p>9. Final response is returned to WSGI.<br>The final HttpResponse is sent back to the WSGI server.</p><p>10. WSGI passes response to the web server.<br>WSGI sends the response to the web server (Gunicorn/Nginx).</p><p>11. Web server sends the response back to the client.<br>The web server returns it to the user’s browser/client.</p><p>Client (Browser/Postman) <br> ↓ <br>Web Server (Nginx/Gunicorn) <br> ↓ <br>WSGI Interface (project/<a href="http://wsgi.py/">wsgi.py</a>) <br> ↓ <br><a href="http://setting.py/">Setting.py</a> <br> ↓ <br>Middleware (Pre-processing) <br> ↓ <br>URL Dispatcher (<a href="http://urls.py/">urls.py</a>) <br> ↓ <br>View Function / CBV <br> ↓ <br>Middleware (Post-processing) <br> ↓ <br>HttpResponse Object <br> ↓ <br>WSGI Server → Web Server → Client</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*pe9AMvwzOTxWG4XfutGqeQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ea5ea48caec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>