1
votes

I don't know is this a right platform to ask this question or not. I recently came across Django rest framework. I am using django for one of my projects.I want to use DRF as an api client for my project. I came across this term serializing the model instances and serializers. I went through DRF Tutorial , but I still have no idea of how it actually works.My questions are :

1.Why are serializers used? What purpose they serve?

2.What more can be done using serializers?

3.How do serializers work?

There may be lots of references on this present in the internet but I want a simple and easy-to-understand answer to this. Thanks!!

1

1 Answers

5
votes

1.Why are serializers used? What purpose they serve?

In a very general way:

Imagine you want to invite your friend for a coffee. To inform your friend, you text "what: coffee, time: 12h, where: The fancy coffee bar on the corner". This text is your serialization of your idea.

The DRF does this for your Django models.

Imagine you have a JS client that doesn't (want to) know about your DB or Django models. You serialize your Django objects into JSON to have that data available in a JS compatible way:

data = {
    "address": {
        "street": "Fancy Street 1b"
    }
};

DRF offers an easy way to translate Django model instances into JSON (or other formats). And that is what serializers do. They also offer to deserialize what your JS frontend sends back to your server.

2.What more can be done using serializers?

You can add more fields that are computed at serialization time. For example, instead of adding simple IDs for related objects you can also serialize the related objects and add them nested into the JSON (or XML or whatever format).

You can also add fields that you only need on the frontend side for some view, like things related to paging etc.

3.How do serializers work?

For python, the simplest serializer from python to JSON would be one that takes a python dictionary and simply creates string keys from the python keys, translates Django boolean into true and false strings, python None into null etc.

For more complex translations, you might want to add your own logic. E.g. like resolving related object references on Django models. Or formatting date objects into ISO standard strings (with timezone), localizing (decimal) numbers, localizing texts in general etc.