Django Rest Framework -A concrete example of when you would use a serializer class vs a model serializer class


I am learning django rest framework, while I understand what a serializer does and when you would use it, I cannot fully seat the need for a serializer and a model serialzer class. Can one of you please give me a concrete real world example use case of both please?

Yes I have gone through the tutorial on DRF website several times and I still am experiencing fuzziness

Show source
| django   | django-rest-framework   | serialization   2017-01-03 20:01 1 Answers

Answers ( 1 )

  1. 2017-01-03 20:01

    There is an excellent example on the DRF tutorial and it would take too much to cover in an answer, but I would like to make some points.

    First, the DRF documentation explains:

    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.

    The Snippet model is the name of the model used in that example. So as the documentation says, rather than typing again the same fields from the model over to a Serializer, we can use a ModelSerializer as a shortcut, in a similar way that we would use a ModelForm over a simple Form.

    But this leaves the question essentially as "ok, then why is there a simple Serializer class at all?", as you pointed out in your comment.

    In the vast majority of cases where you have models and you need to serialize/deserialize relevant data (usually JSON but not limited to), then ModelSerializer is the way to go. Even if additional fields, related serializers or arbitrary logic is required, a ModelSerializer can be easily tweaked. Personally it has never occured to me with any of my projects that ModelSerializer is not suitable for data related to a model.

    But there may be cases where you need to handle data that do not abide to a model. Such data would be POSTed to a DRF view and a Serializer would handle them. Such cases could be for example to send a mail message, to setup a Celery task, to add data to session, and many others that do not involve a model at all.

◀ Go back