<?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 Srujan Gowda on Medium]]></title>
        <description><![CDATA[Stories by Srujan Gowda on Medium]]></description>
        <link>https://medium.com/@srujangowda762?source=rss-80384113374c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*R4EgVPK4MlgZl6MM</url>
            <title>Stories by Srujan Gowda on Medium</title>
            <link>https://medium.com/@srujangowda762?source=rss-80384113374c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 14:04:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srujangowda762/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[Types of Views in Django DRF (CBVs and FBVs)]]></title>
            <link>https://medium.com/@srujangowda762/types-of-views-in-django-drf-cbvs-and-fbvs-76d6303a2578?source=rss-80384113374c------2</link>
            <guid isPermaLink="false">https://medium.com/p/76d6303a2578</guid>
            <dc:creator><![CDATA[Srujan Gowda]]></dc:creator>
            <pubDate>Wed, 19 Jun 2024 16:36:38 GMT</pubDate>
            <atom:updated>2024-06-20T02:39:30.517Z</atom:updated>
            <content:encoded><![CDATA[<h3>Types of Views in Django DRF</h3><p>Before entering the types of views in django. Let’s understand what a view is in django.</p><p>In the Django framework, views are Python <strong>functions </strong>or<strong> classes</strong> that receive a web <strong>request </strong>and return a web <strong>response.</strong></p><p>Django views are divided into two major categories:</p><ol><li><strong>Class </strong>Based Views</li><li><strong>Function </strong>Based Views</li></ol><h3>What is the main objective of views?</h3><ol><li><strong>C</strong>REATE (POST)</li><li><strong>R</strong>EAD (GET)</li><li><strong>U</strong>PDATE (PUT, PATCH)</li><li><strong>D</strong>ELETE (DELETE)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*voDNWE9Idqy6H24N" /><figcaption><strong><em>fig 1.</em></strong> CRUD</figcaption></figure><p>Before starting, I assume that you already have a clear understanding of django <a href="https://medium.com/@srujangowda762/understand-a-to-z-about-migrations-in-django-631e29a605b">models and migrations</a>.</p><p>So let’s begin!! In this article, I have created a project called <strong>college</strong> and an application called as <strong>students. </strong>We are trying to store student data in the database.<br>This is my table definition in models.py</p><pre>class StudentData(models.Model):<br>    srn = models.CharField(max_length=100, primary_key=True)<br>    name = models.CharField(max_length=100)<br>    email = models.EmailField()<br>    address = models.TextField()<br><br><br>    class Meta:<br>        db_table = &#39;student_data&#39;</pre><p>Once we define the models, to apply this to our SQLite database we need to run two commands</p><pre>python manage.py makemigrations<br>python manage.py migrate</pre><p>After running these commands, the below migration file is created in <strong>/students/migrations</strong> folder as 0001_initial.py.</p><pre>class Migration(migrations.Migration):<br><br><br>    initial = True<br><br><br>    dependencies = [ ]<br><br><br>    operations = [<br>        migrations.CreateModel(<br>            name=&#39;StudentData&#39;,<br>            fields=[<br>                (&#39;srn&#39;, models.CharField(max_length=100, primary_key=True, serialize=False)),<br>                (&#39;name&#39;, models.CharField(max_length=100)),<br>                (&#39;email&#39;, models.EmailField(max_length=254)),<br>                (&#39;address&#39;, models.TextField()),<br>            ],<br>            options={<br>                &#39;db_table&#39;: &#39;student_data&#39;,<br>            },<br>        ),<br>    ]</pre><p>Lets inspect this in the database, I am using SQLiteStudio to view my database, you can download <a href="https://www.sqlitestudio.pl/">SQLiteStudio</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/0*lltl_9QCs5XnOSbJ" /><figcaption><strong>fig 2.</strong> Migrated Tables</figcaption></figure><p>As you can see in the above image, the table <strong>student_data </strong>is present with columns <strong>srn, name, email, address </strong>in our database.</p><p>Lets implement class based views on this table to have CRUD functionalities.</p><p>Before writing the views we need to design our serializer.</p><h3>What is a serializer?</h3><p>Serializers allow complex data such as querysets and model instances to be converted to native Python data types that can then be easily rendered into JSON, XML or other content types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*_GKg2iFYR2u8EX0f" /><figcaption><strong>fig 3. </strong>Django Rest framework serializers</figcaption></figure><p>I have defined my model’s serializer in my /students/serializers.py file</p><pre>from .models import StudentData<br>from rest_framework import serializers<br><br><br>class StudentDataSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = StudentData<br>        fields = &quot;__all__&quot;</pre><p>Let’s write class based CRUD views on this.</p><h4><strong>Class based Views</strong></h4><ol><li><strong>APIView</strong></li></ol><pre>from .models import StudentData<br>from rest_framework.response import Response<br>from .serializers import StudentDataSerializer<br>from rest_framework import status<br>from django.shortcuts import get_object_or_404<br>from rest_framework.views import APIView<br><br><br>class StudentAPIView(APIView):<br><br><br>    def post(self, request):<br>        serializer = StudentDataSerializer(data=request.data)<br>        if serializer.is_valid():<br>            serializer.save()<br>            return Response(serializer.data, status=status.HTTP_201_CREATED)<br>        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br>   <br>    def get(self, request, pk=None):<br>        if pk:<br>            student = get_object_or_404(StudentData, pk=pk)<br>            serializer = StudentDataSerializer(student)<br>            return Response(serializer.data)<br>        else:<br>            students = StudentData.objects.all()<br>            serializer = StudentDataSerializer(students, many=True)<br>            return Response(serializer.data)<br><br><br>    def put(self, request, pk=None):<br>        student = get_object_or_404(StudentData, pk=pk)<br>        serializer = StudentDataSerializer(student, data=request.data)<br>        if serializer.is_valid():<br>            serializer.save()<br>            return Response(serializer.data)<br>        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br><br><br>    def patch(self, request, pk=None):<br>        student = get_object_or_404(StudentData, pk=pk)<br>        serializer = StudentDataSerializer(student, data=request.data, partial=True)<br>        if serializer.is_valid():<br>            serializer.save()<br>            return Response(serializer.data)<br>        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br><br><br>    def delete(self, request, pk=None):<br>        student = get_object_or_404(StudentData, pk=pk)<br>        student.delete()<br>        return Response(status=status.HTTP_204_NO_CONTENT)</pre><p>We can inherit <strong>APIView </strong>from<strong> rest_framework.views</strong> and define a class called <strong>StudentAPIView.</strong></p><p><strong>APIView </strong>by default provides methods for CRUD.</p><p>Let’s try to override these methods according to our use case</p><ol><li><strong>post </strong>method:</li></ol><p>→ Handles POST requests.</p><p>→ Creates a new student record with the data provided in the request if valid according to the serializer.</p><p><strong>2. get </strong>method:</p><p>→ Handles GET requests.</p><p>→ If a primary key (pk) is provided, it retrieves a specific student record.</p><p>→ If no primary key is provided, it retrieves a list of all student records.</p><p><strong>3. put </strong>method:</p><p>→ Handles PUT requests.</p><p>→ Updates the entire student record specified by the primary key with the data provided in the request.</p><p><strong>4. patch </strong>method:</p><p>→ Handles PATCH requests.</p><p>→ Partially updates the student record specified by the primary key with the data provided in the request.</p><p><strong>5. delete </strong>method:</p><p>→ Handles DELETE requests.</p><p>→ Deletes the student record specified by the primary key.</p><p>Lets define the endpoints for these methods in urls.py of our application</p><pre>from django.urls import path<br>from .views import StudentAPIView<br><br><br>urlpatterns = [<br>    path(&#39;class_based/students/&#39;, StudentAPIView.as_view(), name=&#39;student_list_create&#39;),<br>    path(&#39;class_based/students/&lt;str:pk&gt;/&#39;, StudentAPIView.as_view(), name=&#39;student_detail&#39;),<br>]<br></pre><h4><strong>Function Based Views</strong></h4><p><strong>@ api_view</strong></p><pre>from rest_framework.decorators import api_view<br><br><br>@api_view([&#39;GET&#39;, &#39;POST&#39;, &#39;PUT&#39;, &#39;PATCH&#39;, &#39;DELETE&#39;])<br>def student_data_api(request, pk=None):<br>    if request.method == &#39;GET&#39;:<br>        if pk:<br>            student = get_object_or_404(StudentData, pk=pk)<br>            serializer = StudentDataSerializer(student)<br>            return Response(serializer.data)<br><br><br>        else:<br>            students = StudentData.objects.all()<br>            serializer = StudentDataSerializer(students, many=True)<br>            return Response(serializer.data)<br><br><br>    elif request.method == &#39;POST&#39;:<br>        serializer = StudentDataSerializer(data=request.data)<br>        if serializer.is_valid():<br>            serializer.save()<br>            return Response(serializer.data, status=status.HTTP_201_CREATED)<br>        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br><br><br>    elif request.method in [&#39;PUT&#39;, &#39;PATCH&#39;]:<br>        student = get_object_or_404(StudentData, pk=pk)<br>        if request.method == &#39;PUT&#39;:<br>            serializer = StudentDataSerializer(student, data=request.data)<br>        elif request.method == &#39;PATCH&#39;:<br>            serializer = StudentDataSerializer(student, data=request.data, partial=True)<br><br><br>        if serializer.is_valid():<br>            serializer.save()<br>            return Response(serializer.data)<br>        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br><br><br>    elif request.method == &#39;DELETE&#39;:<br>        student = get_object_or_404(StudentData, pk=pk)<br>        student.delete()<br>        return Response(status=status.HTTP_204_NO_CONTENT)</pre><p>To develop CRUD APIs using function based views we need to <strong>import </strong>api_view from decorators <br>Pass the list of methods that your API need to respond to [‘GET’, ‘POST’, ‘PUT’, ‘PATCH’, ‘DELETE’]</p><p>Based on request.method we write the login for post, get, put , patch and delete as above.</p><p>The entire logic is same as I had explained in class-based views</p><p>Lets define the endpoints for this function in urls.py of our application</p><pre><br>from django.urls import path<br>from .views import StudentAPIView, student_data_api<br><br>urlpatterns = [<br>    path(&#39;class_based/students/&#39;, StudentAPIView.as_view(), name=&#39;student_list_create&#39;),<br>    path(&#39;class_based/students/&lt;str:pk&gt;/&#39;, StudentAPIView.as_view(), name=&#39;student_detail&#39;),<br><br>    path(&#39;func_based/students/&#39;, student_data_api, name=&#39;student-data-list-create&#39;),<br>    path(&#39;func_based/students/&lt;str:pk&gt;/&#39;, student_data_api, name=&#39;student-data-detail&#39;),<br>]</pre><p>Major Differences between<strong> FBVs </strong>and <strong>CBVs</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*okVqDEszhXtf474jNhTkog.png" /><figcaption><strong>fig4.</strong> Major Differences</figcaption></figure><p>In this article, we understood the difference between FBVs and CBVs. I will be explaining about CBVs in the upcoming articles stay-tuned</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76d6303a2578" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand A to Z about migrations in Django]]></title>
            <link>https://medium.com/@srujangowda762/understand-a-to-z-about-migrations-in-django-631e29a605b?source=rss-80384113374c------2</link>
            <guid isPermaLink="false">https://medium.com/p/631e29a605b</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[django-migrations]]></category>
            <dc:creator><![CDATA[Srujan Gowda]]></dc:creator>
            <pubDate>Mon, 03 Apr 2023 09:23:36 GMT</pubDate>
            <atom:updated>2023-04-03T09:23:36.225Z</atom:updated>
            <content:encoded><![CDATA[<p>What is a migration?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*9JmFD0FfM2xihQOD" /></figure><p>Movement from one part of something to another.</p><h3>What is Migration in Django?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*njUjO1HxIyBFgYmZ" /></figure><p>Django’s way of propagating changes you make to your models into your database schema</p><p><strong>Why</strong> migrations?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*1Iui1XT8MtANiE5c" /></figure><p>They help developers plan, validate, and safely apply schema changes to their environments without confusions.</p><p><strong>How </strong>are migrations designed in django?</p><p>Before understanding migrations lets understand the structure of django</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*anKWk2ssNOJAwtkDYt6thQ.png" /></figure><p>As the above figure represents the hierarchy in Django, i.e.,</p><p>Every model is under an application and every application is under a project.</p><p>Each Model will be creating a migration (.py) file that is responsible to create table in the Database</p><p>Let’s Discuss about the creation of migration file later.</p><p>Suppose you have to create a backend system to store employee details of a company</p><p><strong>Requirements:</strong></p><p>These below fields needs to be saved in the database:</p><ul><li>employee_id</li><li>first_name</li><li>last_name</li><li>age</li><li>gender</li></ul><p><strong>Solution:</strong></p><p>Lets see how can we achieve this using Django</p><p>Switch to the virtual environment created in your system using</p><p>source &lt;env&gt;/bin/activate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/0*JvloMoPt3U4ocU8A" /></figure><p>Create a django project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UW0pX-6YJTk60W1n" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*lu3wUNBQwZn42ZhM" /></figure><p>As you can see it creates one more file called manage.py which is Django’s command-line utility for administrative tasks like migration, runserver, createsuperuser (etc.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/0*0gKlpzrMUNXy0G0x" /></figure><p>Create a django application inside django project folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g9X8WeHQX9MOFSoA" /></figure><p>Once the application is created lets see what is inside it.</p><p>It has migrations folder which contains empty __init__.py file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/0*zp3mImF_O0nboBSO" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/0*JDJfLf1FIgARry70" /></figure><p>Before creating the models lets run showmigrations command to see the migrations that needs to be applied to the database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BMZrluOV3A9bUDIv" /></figure><p>As shown in the above diagram these apps admin, auth,contenttypes, sessions need to be migrated and get converted as tables. Along with columns creations/updations as shown in the migration files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/0*hy00ii2RYkXpcz_z" /></figure><p>Since the migrations were done by default after running makemigrations it detects no change we need to migrate them to the database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F2ZcHkVCqE3lySRR" /></figure><p>Lets run Migrate command which creates Database tables and columns in their respective table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HbEFLsaERh1LfNMS" /></figure><p>These migration files will create the tables in the database according to the specifications mentioned by Django.</p><p>Below are the default django tables created after migrating</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/0*wEgNwMH8Z4D4AOtI" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*ZGFRtJ5DV4g4WAPVXPspng.png" /></figure><p>As highlighted there is a table called django_migrations which stores the complete details of the migrations made in your project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/0*FLvTxMJb2CYd0w91" /></figure><p>This is the data in django_migrations which contains id(autofill), app(application name), name(migration command name), applied(timestamp of the migration done)</p><p>These are default tables that get created for every django project. Now let’s see how to create custom tables in Django.</p><p>Earlier, we had a requirement of creating employee database</p><ul><li>employee_id</li><li>first_name</li><li>last_name</li><li>age</li><li>gender</li></ul><p>To create the table we need to create a class called EmployeeData and inherit Model from models (models.Model)</p><p>And define the class variables in it, which will be created as columns in the table</p><p>Mention the data type and data length that needs to be stored in the respective columns according to the specifications</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/0*ELEkti1ZCM88xPro" /></figure><p>Now to apply these migrations in to your database we need to create migration files in our system. Before that we need to mention our application name in INSTALLED_APPS= [ ] in settings.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*8uTt11qywDhXD3EA" /></figure><p>Now switch back to the terminal to create the migrations of the django application by mentioning its name in the command</p><p>python3 manage.py makemigrations <strong>datastore</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/0*DOQXXpvHRvmSakQQ" /></figure><p>After running the makemigrations command as you can see the response. There is a file being created in the folder migrations of application datastore named 0001_initial.py.</p><p>Now, Let’s inspect what’s being created in this python file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9mWnbpYv6a3rv6G3" /></figure><p>This has created a default class called migration, inheriting from django.db.migrations.Migration which is the base class for all the migrations.</p><p>What does these 3 variables initial, dependencies, operations actually mean and why are they defined?</p><ol><li>initial</li></ol><p>Since it is the initial migration of the application <strong>datastore </strong>the variable initial is marked as True</p><p>2. dependencies</p><p>This defines a list of tuples which defines the other migrations that need to be run before running the migration file.</p><p>Since this is our initial migration to the application there are no dependent migrations from other migrations.</p><p>3. operations</p><p>This defines the list of auto-generated operations to be applied during this migration process (in sequence).In our case there is an operation that needs to be performed i.e creation of model with specified fields and field specifications</p><p>‘id’ is the Auto generated field that gets created during the creation of every entry (Employee) in the Database.</p><p>verbose_name is the human understandable name set by the django if not given in the models.py</p><p>Now let’s try to run the server</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d_lLS7K0iE0RZ9A8" /></figure><p>As it is mentioned in the response of the command we have one migration that is created in the folder but not applied to the database.</p><p>Now let’s apply the migration to the database using</p><p>python3 manage.py migrate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3afmb-UYFRVqkWHv" /></figure><p>This migration will be saved in django_migrations and using it the migration will be applied in the Database</p><p>Let’s check django_migrations table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*mImrYLoUxaK3GJbSbE8ZXA.png" /></figure><p>As you can see the migration 0001_initial of datastore application was saved in the table with id 19 on 03 Apr 2023, 07:44 UTC Time</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/0*CIERDueswrkUQIHA" /></figure><p>There is a table called “datastore_emplyeedata” created in the DB</p><p>Lets rename the table name in models.py and migrate again and see what happens</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*8wEmug_uejAhVS9g" /></figure><p>As it is a code change in models.py, we need to run makemigrations command to reflect in the DB as it creates one more migration file in the migrations folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TDVVlxmvynC_9Xvb" /></figure><p>The migration was created with the name 0002_rename_emplyeedata_employeedata.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/0*4TqZSQbXh3ROxJPG" /></figure><p>Now, let’s inspect the migration file to know more about it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*ZdO1Mw4JXwezBgUV" /></figure><p>Since, it is not an initial migration initial variable is not defined in the class</p><p>And the dependencies of this migration file is 0001_initial.py file of datastore application.</p><p>Operations defined in this file is Renamemodel which takes two params i.e old_name and new_name</p><p>Lets migrate this file so that we can see this in the database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sifWbR3F29l2kIF0" /></figure><p>This has created a new entry in the django_migrations with id 20</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*EIfQaILst2zlBFfxakrqJA.png" /></figure><p>The changes are reflected in the Database</p><p>I would suggest you to go through every migration file created after running the makemigrations command.</p><p><strong><em>Important:</em></strong> If there is a conflict in creation of migration files in your project instead of merging the migrations or dropping the Database we can just delete the migration of the particular app and run the makemigrations command again.</p><p><strong>Conclusion:</strong> This brings to the conclusion of django migrations.Hope I have explained the django migrations in detail and cleared the confusions if any in this article. Stay tuned for more articles in the near future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=631e29a605b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>