Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Alternative Serializers

00:00 In the previous lesson, I showed you how to use permissions with the DRF. In this lesson, I’m going to show you how to use serializers that are not associated with a Django model. Up until now, all of the serialization that I’ve shown you has been associated with a Django database ORM object. You don’t have to do that.

00:19 You can create a serializer from scratch, and it doesn’t have to serialize something from Django. You do this by inheriting from the serializers.Serializer class and combine it with serializer fields.

00:32 Serializer fields are similar to Django model fields. You can explicitly create a serializer specifying field by field—it doesn’t have to be based on that ORM.

00:45 In this lesson and the next lesson, I’m going to use the same app, which is a new one called vehicles. Like always, if you’re coding along with me, you’ll need to add vehicles to your INSTALLED_APPS list.

00:56 You’ll need to update your urls file to include vehicle.urls to pull in anything defined there. And then follow along with any models, serializers, views, and urls that I show you. For this particular lesson, there won’t be anything to migrate.

01:11 I’m going to create stuff inside of the models space, but it is not going to be Django objects, so you won’t have to do the makemigrations and migrate.

01:20 Because I’m going to be using the same vehicles app in this lesson and in the next lesson and I’m going to be creating multiple models, in order to be a little more organized, I’m going to switch over from using a models.py file to a models/ directory.

01:33 If you haven’t seen this before inside of Django, the mechanism’s more or less the same. Instead of creating the models.py file, you create a directory and then create files inside of it.

01:44 There’s one extra step that you have to do to get all this to work, which I’ll show you in a second. Inside of the models/ directory, I’ve created a file called tools.py, and inside of that I’m creating a regular old Python object.

01:57 This object has a couple of attributes, one called .name, the other called .make, and all I’m doing inside of the initialization is assigning those to the object.

02:10 So that that file I just created can be read from the models as a module, I’ve had to create a __init__ file and I’m going to import that Tool object inside of it.

02:23 Now for the serializer. In order to keep the code nice and clean, I’m going to use a serializers/ directory similar to the models/ directory.

02:31 Inside of the serializers/ directory I’m going to create tools.py, which corresponds to the tools.py file inside of the models/ directory.

02:40 Here’s my generic serializer. Notice that it’s inheriting from just Serializer instead of ModelSerializer. I’m specifying each of the fields that I’m going to serialize, and I specify one field for each of the attributes of the Tool object.

02:57 Both of these are CharField, which, similar to Django model.CharField, contain text and have a max_length in this case of 50.

03:09 Continuing on with the pattern, I’ve created a views/ directory and inside of that, I’ve created tools.py. For tools, I’m creating a single view that just lists the tools to give you the idea of how this serialization works. On line 8, I’m using the @api_view decorator in the exact same way as one of the early lessons. And line 9, I’m creating the definition of the list_tools() view. Line 10 through 13, I’m creating two Tool objects.

03:39 These are just generic Python classes that have been instantiated as "hammer" and "wrench". From line 15 on, this method is no different than when it is a Django object being serialized. You create the serializer, you pass in the thing being serialized—in this case, a list of the Tool objects.

03:58 Because it’s multiple objects, I’m setting many=True, and then I create a content dictionary that consists of the serialized data and pass it into a REST Response object.

04:14 Finally, to make it accessible, I need to add "list_tools/" as a path, pointing it to the view.

04:21 To demonstrate this view, I’m going to use the browser and point it at the web interface.

04:28 Going to the list_tools/ view that I just created, and, like before, you get back the same kind of interface showing the serialized data. You can serialize anything you like.

04:38 It doesn’t have to be a Django object. This gives you a fair amount of power. You can serialize the things in your database, or, if you want, you can create your own as needed by your application.

04:50 In the sample code, I showed you how to use the CharField. There are a large number of fields provided by the DRF. There are fields for Boolean, a long list of string fields.

05:02 Most of these are similar, what changes is the validation. So for example, the IPAddressField is still just a string, but the validator makes sure that the string is formatted as a valid IP address.

05:15 There are three numeric fields, fields for date and time, and two fields that allow choices of predetermined selections.

05:25 There are fields for uploaded files, composite fields, which hold groupings of other things like dictionaries or nested JSON, and specialty fields like ReadOnlyField and HiddenField for your forms, or the SerializerMethodField, which is a special field that is read-only that gets mapped to a method inside of the serializer. Every time the field is serialized, that method gets called, which allows you to run arbitrary code anytime serialization happens.

05:54 If all of that’s not enough, you can always write your own. But before you do, you should check out whether or not what you are trying to dream up has already been done for you by someone else.

06:05 There are plenty of third-party libraries out there that contain other kinds of fields that you might find useful.

06:12 When you instantiate a field, you can pass it arguments to control how it behaves. Some of the arguments are whether or not the field is read-only, write-only, required, what its default value is, whether it allows null, what the source attribute of the field is. By default, the Serializer class uses the name of the field to look up the corresponding field in the object being serialized. If you need to rename this, or there’s a reason that mapping won’t work for you, the source argument allows you to specify where to look something up.

06:46 You can specify validators, similar to Django’s model validators, that determine whether or not the values in the field being serialized are valid. And then finally, error_messages, label, help_text, initial, and style are all arguments you can use to specify the presentation. Some of these are specific to certain kinds of renderers.

07:08 For example, if you were using the HTML renderer, the style argument can pass in CSS information to tell the template how to style the field being rendered. As you’ve probably surmised, the ModelSerializer that I’ve been using up until now is built based on top of all these concepts that are already here.

07:29 The Serializer is the beating heart of the DRF—it’s all about how you get that payload and how you use it. For more information on how fields work and how to use the arguments that go with them, see the fields section of the API guide.

07:44 So, I’ve shown you how to serialize things and how to specify specialty fields. In the next lesson, I’ll show you how to do nested Django ORM objects.

Become a Member to join the conversation.