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.