So, let’s get started with this course. The first step is to create Serializers and Deserializers.
What is a Serializer and Deserializer ?
A Serializer is something (in this case it will be a Python class) that knows how to create a streamable representation of a model instance. Django REST Framework contains some code that knows how to take something like this:
into something like this:
A Deserializer does the exact opposite. It will take the JSON format and convert it into the Python object.
Why is this Important to know?
The first thing you need to understand is that you can’t send a Python object through a HTTP Request and have it come out the other end intact. Therefore, we use something like JSON to keep our data from getting lost in translation.
Okay! How do I create a Serializer?
Actually, we aren’t there yet. We have something things that need to be done. We need to add the Django REST Framework code to our Django project. The app for Django REST Framework is called rest_framework. So, bust out your settings.py file and add rest_framework to the end of your INSTALLED_APPS tuple.
Now, we are ready to create some serializers!
Inside the ‘polls’ app, create a file called serializers.py. Edit this file as shown:
Done! Creating models is simple. You create your class subclassing serializers.ModelSerializer and in your Meta class, assign
model = MyModel.
It might seem simple but the
QuestionSerializer has an extra attribute. What is that all about?
If you want your Serializer to automatically include other models that are associated with it, you can assign an attribute with another defined Serializer (in this case —
We can’t use them yet…
Once we create the Serializers, we have to be able to use them. They don’t just work… yet.
The next step is create our views and add to our URLs so we can access our endpoints! That’s what the next lesson is all about!
Lesson 1: Homework
- Add rest_framework to your list of
- Create the 2 Serializers as I did above.
- Compare your work to mine
- If you have questions, reply to this email or reply in the comments section below
This lesson was incredibly easy, but it’s important. If you don’t get Serializers correct, your endpoints won’t work correctly. Next lesson (Lesson 2) you’ll be able to go to your endpoints and actually see the output of your models.
See you soon!