Using ModelSerializers

Our SnippetSerializer class is replicating a lot of information that's also contained in the Snippet model. It would be nice if we could keep our code a bit more concise.

In the same way that Django provides both Form classes and ModelForm classes, REST framework includes both Serializer classes, and ModelSerializer classes.

Let's look at refactoring our serializer using the ModelSerializer class.Open the file snippets/serializers.py again, and replace the SnippetSerializer class with the following.

  1. class SnippetSerializer(serializers.ModelSerializer):
  2. class Meta:
  3. model = Snippet
  4. fields = ['id', 'title', 'code', 'linenos', 'language', 'style']

One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with python manage.py shell, then try the following:

  1. from snippets.serializers import SnippetSerializer
  2. serializer = SnippetSerializer()
  3. print(repr(serializer))
  4. # SnippetSerializer():
  5. # id = IntegerField(label='ID', read_only=True)
  6. # title = CharField(allow_blank=True, max_length=100, required=False)
  7. # code = CharField(style={'base_template': 'textarea.html'})
  8. # linenos = BooleanField(required=False)
  9. # language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...
  10. # style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...

It's important to remember that ModelSerializer classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes:

  • An automatically determined set of fields.
  • Simple default implementations for the create() and update() methods.