Basic Serializer

We could always define a basic serializer and define all of the fields manually. The documentation has an example of this:

from rest_framework import serializersclass CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()

ModelSerializer

A model serializer has most of what we need built in. We just need to define the model and what fields we want. Here is an example:

class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ['id', 'account_name', 'users', 'created']
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ‘__all__’

HyperlinkedModelSerializer

Very similarly to the model serializer, we also have the option to use a HyperlinkedModelSerializer. The main difference between the two is the ModelSerializer will have an id field as the primary key, the HyperlinkedModelSerializer will use a url field instead of an id. Depending on what you need, you will want to choose one or the other. But it is set up the same way, here is an example:

class AccountSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Account
fields = ['url', 'id', 'account_name', 'users', 'created']

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store