<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Aman Bothra</title>
    <description>The latest articles on DEV Community by Aman Bothra (@amanbothra).</description>
    <link>https://dev.to/amanbothra</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1047268%2F045f0028-afa5-40cf-b350-c19ac6421ecd.jpg</url>
      <title>DEV Community: Aman Bothra</title>
      <link>https://dev.to/amanbothra</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/amanbothra"/>
    <language>en</language>
    <item>
      <title>Optimizing Python Code in Django Using ORM: Best Practice</title>
      <dc:creator>Aman Bothra</dc:creator>
      <pubDate>Fri, 01 Sep 2023 06:00:45 +0000</pubDate>
      <link>https://dev.to/amanbothra/optimizing-python-code-in-django-using-orm-best-practice-412k</link>
      <guid>https://dev.to/amanbothra/optimizing-python-code-in-django-using-orm-best-practice-412k</guid>
      <description>&lt;p&gt;Web development is just one of the many applications for the potent computer language Python. Python-based web framework Django offers a robust Object-Relational Mapping (ORM) technology for interacting with databases. We'll go over some best practises for using Django's ORM to optimise your Python code in this blog article.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Avoid using global variables
&lt;/h2&gt;

&lt;p&gt;Performance in Python can be significantly impacted by global variables, especially in more complex applications. In Django, variables can also be defined as instance or class variables. Here is an illustration of how a Django model uses a class variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=50)
    age = models.IntegerField()

    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, a &lt;code&gt;Person&lt;/code&gt; model with the fields &lt;code&gt;name&lt;/code&gt; and &lt;code&gt;age&lt;/code&gt; was defined. The &lt;code&gt;name&lt;/code&gt; and &lt;code&gt;age&lt;/code&gt; of the person are used in the welcoming message that the &lt;code&gt;greet&lt;/code&gt; method returns.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Use list comprehension
&lt;/h2&gt;

&lt;p&gt;List comprehension is a shorter method of iterating over a list and producing a new list in Python. Django users can use this method to make it easier to iterate over a queryset and generate new lists. Here is an illustration of how list comprehension is used in Django:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.shortcuts import render
from .models import Person

def get_people(request):
    people = Person.objects.all()
    names = [person.name for person in people]
    return render(request, 'people.html', {'names': names})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we used &lt;code&gt;Person.objects.all()&lt;/code&gt; to retrieve every person from the database, and list comprehension to produce a list of names from the queryset.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Use generators
&lt;/h2&gt;

&lt;p&gt;Python has a feature called generators that let you iterate over big data sets without putting them all in memory at once. You can use generators in Django to make your code run faster. Here is an illustration of how to use a generator in Django:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.shortcuts import render
from .models import Person

def get_people(request):
    def get_names():
        for person in Person.objects.all():
            yield person.name
    return render(request, 'people.html', {'names': get_names()})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The name of each individual in the individual queryset is produced by the generator function &lt;code&gt;get_names&lt;/code&gt;, which was defined in this example. The render function was then passed the generator function.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Use appropriate data structures
&lt;/h2&gt;

&lt;p&gt;Your code's performance can be enhanced by using the suitable data structures. Lists, tuples, sets, dictionaries, and other data structures are all available in Python. These data structures can be used in Django to convert database fields into Python objects. Here is an illustration of how to use a dictionary in Django:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.shortcuts import render
from .models import Person

def get_people(request):
    people = Person.objects.all().values('name', 'age')
    data = {}
    for person in people:
        data[person['name']] = person['age']
    return render(request, 'people.html', {'data': data})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we retrieved all the people from the database using &lt;code&gt;Person.objects.all().values('name', 'age')&lt;/code&gt; and then used a dictionary to map each name to the corresponding age.&lt;/p&gt;

&lt;p&gt;In conclusion, Django's ORM provides a powerful toolset for implementing the best practices of code optimization in a web application. By using instance variables or class variables, list comprehension, generators, and appropriate data structures&lt;/p&gt;

</description>
      <category>django</category>
      <category>database</category>
      <category>python</category>
      <category>developer</category>
    </item>
    <item>
      <title>Understanding the to_representation and to_internal_value Methods in the Django Rest Framework</title>
      <dc:creator>Aman Bothra</dc:creator>
      <pubDate>Mon, 05 Jun 2023 06:06:38 +0000</pubDate>
      <link>https://dev.to/amanbothra/understanding-the-torepresentation-and-tointernalvalue-methods-in-the-django-rest-framework-naa</link>
      <guid>https://dev.to/amanbothra/understanding-the-torepresentation-and-tointernalvalue-methods-in-the-django-rest-framework-naa</guid>
      <description>&lt;p&gt;The Django Rest Framework makes it simpler to create APIs with Django. It offers a variety of powerful capabilities that enable it straightforward to convert Python objects into a format that can be broadcast over the internet, like serializers. The two most important options provided by serializers are &lt;strong&gt;&lt;code&gt;to_internal_value&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;to_representation&lt;/code&gt;&lt;/strong&gt;. We'll look at these two methods in this article and see how the Django Rest Framework applies them.&lt;/p&gt;

&lt;p&gt;What are &lt;strong&gt;&lt;code&gt;to_representation&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;to_internal_value&lt;/code&gt;&lt;/strong&gt;?&lt;/p&gt;

&lt;p&gt;Serializers in the Django Rest Framework offer two methods: &lt;strong&gt;&lt;code&gt;to_representation&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;to_internal_value&lt;/code&gt;&lt;/strong&gt;. These techniques are used to translate between an object's internal representation and its serialised representation.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;&lt;code&gt;to_representation&lt;/code&gt;&lt;/strong&gt; method is used to convert the internal representation of an object into its serialized representation. This is used when serializing an object to be sent over the wire.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;&lt;code&gt;to_internal_value&lt;/code&gt;&lt;/strong&gt; method is used to convert the serialized representation of an object back into its internal representation. This is used when deserializing an object that has been received over the wire.&lt;/p&gt;

&lt;p&gt;How are &lt;strong&gt;&lt;code&gt;to_representation&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;to_internal_value&lt;/code&gt;&lt;/strong&gt; used?&lt;/p&gt;

&lt;p&gt;Let's say we have a &lt;strong&gt;&lt;code&gt;Person&lt;/code&gt;&lt;/strong&gt; model with the following fields:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    birthdate = models.DateField()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can create a serializer for this model using Django Rest Framework like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ['first_name', 'last_name', 'birthdate']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, let's say we want to customize the serialized representation of the &lt;strong&gt;&lt;code&gt;Person&lt;/code&gt;&lt;/strong&gt; object. We can do this by defining a &lt;strong&gt;&lt;code&gt;to_representation&lt;/code&gt;&lt;/strong&gt; method in the serializer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ['first_name', 'last_name', 'birthdate']

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['full_name'] = f"{instance.first_name} {instance.last_name}"
        return data
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we are adding a &lt;strong&gt;&lt;code&gt;full_name&lt;/code&gt;&lt;/strong&gt; field to the serialized representation of the &lt;strong&gt;&lt;code&gt;Person&lt;/code&gt;&lt;/strong&gt; object. We do this by calling the &lt;strong&gt;&lt;code&gt;super().to_representation(instance)&lt;/code&gt;&lt;/strong&gt; method to get the default serialized representation of the object, and then add our own custom field to the data.&lt;/p&gt;

&lt;p&gt;Now, let's say we want to customize the deserialization of the &lt;strong&gt;&lt;code&gt;Person&lt;/code&gt;&lt;/strong&gt; object. We can do this by defining a &lt;strong&gt;&lt;code&gt;to_internal_value&lt;/code&gt;&lt;/strong&gt; method in the serializer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ['first_name', 'last_name', 'birthdate']

    def to_internal_value(self, data):
        full_name = data.pop('full_name', None)
        if full_name:
            first_name, last_name = full_name.split()
            data['first_name'] = first_name
            data['last_name'] = last_name
        return super().to_internal_value(data)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we are customizing the deserialization of the &lt;strong&gt;&lt;code&gt;Person&lt;/code&gt;&lt;/strong&gt; object by allowing the user to provide a &lt;strong&gt;&lt;code&gt;full_name&lt;/code&gt;&lt;/strong&gt; field instead of separate &lt;strong&gt;&lt;code&gt;first_name&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;last_name&lt;/code&gt;&lt;/strong&gt; fields. We do this by popping the &lt;strong&gt;&lt;code&gt;full_name&lt;/code&gt;&lt;/strong&gt; field from the data, splitting it into &lt;strong&gt;&lt;code&gt;first_name&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;last_name&lt;/code&gt;&lt;/strong&gt;, and then adding those fields back to the data. We then call the &lt;strong&gt;&lt;code&gt;super().to_internal_value(data)&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
 method to get the default internal representation of the object.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>django</category>
      <category>python</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
