From the course: Building RESTful Web APIs with Django

Creating a Django Rest framework serializer to serialize a model

From the course: Building RESTful Web APIs with Django

Start my 1-month free trial

Creating a Django Rest framework serializer to serialize a model

- [Instructor] Let's get started by writing a serializer to serialize a model. In general, serializing means to convert an object into format like JSON, YAML, or XML. Specifically, we want to take the product model in this project and serialize it to a JSON format that is served through Our REST API. This class will mock the fields from a Django model into the serialization format. We're going to serialize the id, name, price, and product sales dates. Let's create the serializer .py file, and from rest_framework, we import serializers, and we also import our Product model. We create a model serializer and it has a Meta class and the model is set to Product and the fields that we want to serialize. Let's do something a bit more complicated. Let's modify this serialized representation and add a few extra fields to it. To do this, we override the to_representation method. We call the parent classes to_representation implementation, and then we add our extra fields, in this case, is_on_sale, so we know whether the product is on sale or not, and this will just be a Boolean value, true or false. And then we have our current_price, which is either the sale price or the regular price, depending on whether the product is currently on sale. And we return the data. So with that, we've serialized the fields and we've also added two extra customized fields to the serialization representation. So now we can go to the Django shell and try this out and see what happens. So we activate virtual env, and then we get into the Django shell. I'm going to maximize the terminal so that we can focus on the Django shell and testing this out. We're going to import our model and take the first product in the database, and then we're going to import the serializer that we just created, and create it, and then we serialize the product, to_representation. And now to actually get this into a JSON format, we're going to be importing and using the JSONRenderer. We create the renderer and then we actually render the serialized data. So as you can see, we serialized the product and then it became JSON with a JSONRenderer. The Django shell is a very important tool for rapid prototyping and testing. In production environments, it's common to use the Django shell for debugging problems as well.

Contents