Reader small image

You're reading from  Django in Production

Product typeBook
Published inApr 2024
Reading LevelIntermediate
PublisherPackt
ISBN-139781804610480
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Arghya Saha
Arghya Saha
author image
Arghya Saha

Arghya (argo) Saha, is a software developer with 8+ years of experience and has been working with Django since 2015. Apart from Django, he is proficient in JavaScript, ReactJS, Node.js, Postgres, AWS, and several other technologies. He has worked with multiple start-ups, such as Postman and HealthifyMe, among others, to build applications at scale. He currently works at Abnormal Security as a senior Site Reliability Engineer to explore his passion in the infrastructure domain. In his spare time, he writes tech blogs. He is also an adventurous person who has done multiple Himalayan treks and is an endurance athlete with multiple marathons and triathlons under his belt.
Read more about Arghya Saha

Right arrow

Serializing Data with DRF

In Chapter 2, we learned how to work with databases and models using Django. All the concepts that we have learned are related to Django and how developers can make the best use of the Django framework to interact with a database. In this chapter, we shall take another step forward to learn how DRF integrates with Django ORM and models to help us create APIs that will be consumed by client applications.

We shall learn in detail the concepts of serialization and deserialization, and how the client interacts with server applications using the JSON data type. Validating every input and fetching data from multiple tables is quite common for developers, so DRF helps to implement a leaner interface for such use cases, with the help of Serializers. DRF provides Serializers that can be customized to work with Django models out of the box. Finally, we shall learn how we can use Serializers in APIViews and Generic Views, which we learned about in the first chapter...

Technical requirements

In this chapter, we shall learn in depth about DRF serializers and how developers can make the best use of serializers in the application code. To follow along with the concepts covered in this chapter, you should have a clear understanding of Django models and ORM. We shall discuss related fields and views, so you should have understood the previous two chapters of the book. Although we shall cover all the concepts of the serializers, it would be helpful to have some understanding of how to create DRF serializers.

Here is the GitHub repository that has all the code and instructions for this chapter: https://github.com/PacktPublishing/Django-in-Production/tree/main/Chapter03.

Understanding the basics of DRF Serializers

In the previous chapter, we learned how to use databases using Django models and ORM. However, in the world of web applications, the interaction between the client and server happens using REST APIs, with the JSON request-response format. Let us see how a client-server API interaction looks.

A client application uses the JSON data format to send information to the server via a ReST API. A Django server running on DRF uses, by default, JSONParser to parse the data from the JSON format to the Python native format. Then, data in the Python native format would be passed to a serializer to save the data in the Database, using the Django ORM. Similarly, when data is retrieved from the database using the Django ORM, it will be passed through a Serializer to deserialize the data into the Python native format. The Python native format data would be passed through JSONRenderer to render the data into the JSON format, finally sending a response to...

Using Model Serializers

The most common use case for Serializer is to save or retrieve data from Django models. DRF provides ModelSerializer, which helps us to integrate DRF serializers to a Django model that can serialize/deserialize fields present in it. ModelSerializers maps between the serializable fields and database fields present in the model definition.

Let’s work with a few basic ModelSerializer examples to understand the concept. We’ll use the same Blog Django model we built in Chapter 2 and create BlogSerializer to serialize the data. We can define our serializers in any place, but to have maintainable code, it is advisable to have an individual serializers.py file for each app that contains all the Serializer definitions:

# blog/models.py
class Blog(BaseTimeStampModel):
    title = models.CharField(max_length=200)
    content = models.TextField()
    author = models.ForeignKey(Author, related_name...

Implementing Serializer relations

Django models have three types of relational fields – ForeignKey, ManyToManyField, and OneToOneField (all of them support reverse relationships too). So far, we have learned how to use model serializers efficiently, but let’s now explore how we can work with related fields in Serializers.

By default, when a model has any related field, ModelSerializer will link the associated field to PrimaryKeyRelatedField in the serializer definition. A DRF serializer will use PrimaryKeyRelatedField for all kinds of related field serializers, with different options passed.

Here, we will learn how to create related field serializers:

  • For ForeignKey, the DRF model serializer assigns PrimaryKeyRelatedField to the serializer
  • For OneToOneField, the DRF model serializer assigns PrimaryKeyRelatedField to the serializer with an additional UniqueValidator attached
  • For ManyToManyField, the DRF model serializer assigns PrimaryKeyRelatedField...

Validating data with serializers

One of the most loved features of DRF serializers is the data validation framework it provides out of the box. By default, whenever a model is defined to the model serializer, it automatically picks the field types and the database field validators, applying them to the serializer. When we pass raw data to the serializer and call the is_valid() method, it evaluates the data against the autogenerated validators and gives us a Boolean value.

Now, let’s investigate a few in-depth concepts and the implementation of validators in DRF Serializers.

Customizing field-level validation

DRF serializer fields can have custom validation logic linked to a particular field. By defining a validate_<field name> method in the serializer class, DRF automatically executes the validator whenever the is_valid() method is called. For example, if we don’t want to have an underscore inside a title, we can use the following snippet:

class BlogCustom7Serializer...

Mastering DRF Serializers

We have learned all the important concepts of DRF serializers, so in this section, we shall learn how we can use DRF serializers efficiently, as well as a few new concepts that can help us master them even further.

Using source

We learned earlier how we can use the source option to perform multiple types of operations, and moving forward, you should use this argument in the serializer field whenever possible. This is because it drastically reduces the need to write manual code for basic tasks such as renaming fields, making a flat response structure, or accessing data from related fields.

Embracing SerializerMethodField

SerializerMethodField gives us a lot of flexibility to perform data manipulation on the fly. We should use method serializers whenever we need to perform computation involving multiple fields of a single object, or to transform data.

Using validators

Always try to add validators so that we don’t need to use custom code...

Using Serializers with DRF views

In real-world application development, DRF Serializers work closely with DRF views to interact with the client application. Let’s learn how we can integrate DRF Serializers to DRF Views by taking blog API examples. In the following example code, we integrate BlogSerializer to APIView for both read and write operations for the blogging model:

class BlogGetCreateView(views.APIView):
    def get(self, request):
        blogs_obj_list = Blog.objects.all()
        blogs = BlogSerializer(blogs_obj_list, many=True)
        return Response(blogs.data)
    def post(self, request):
        input_data = request.data
        b_obj = BlogSerializer(data=input_data)
        if b_obj...

Summary

In this chapter, we learned how to work with DRF Serializers. First, we explored the concept of a basic DRF Serializer, as well as how DRF uses a Renderer and a Parser to transform data from JSON to Python native datatypes (and vice-versa). Then, we learned how to use DRF ModelSerializer with Django models.

DRF Serializers provide data validation support out of the box. In this chapter, we learned different ways to integrate field-level and object-level validation using serializers. We also learned how we can integrate DRF Serializers to work with Django-related fields and use nested Serializers.

Finally, we learned how to integrate DRF Serializers with DRF views to get an end-to-end picture of how Serializers work in the overall application development.

In the next chapter, we shall learn how we can use Django admin and work with Django management commands.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Django in Production
Published in: Apr 2024Publisher: PacktISBN-13: 9781804610480
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at ₹800/month. Cancel anytime

Author (1)

author image
Arghya Saha

Arghya (argo) Saha, is a software developer with 8+ years of experience and has been working with Django since 2015. Apart from Django, he is proficient in JavaScript, ReactJS, Node.js, Postgres, AWS, and several other technologies. He has worked with multiple start-ups, such as Postman and HealthifyMe, among others, to build applications at scale. He currently works at Abnormal Security as a senior Site Reliability Engineer to explore his passion in the infrastructure domain. In his spare time, he writes tech blogs. He is also an adventurous person who has done multiple Himalayan treks and is an endurance athlete with multiple marathons and triathlons under his belt.
Read more about Arghya Saha