Hacker Newsnew | past | comments | ask | show | jobs | submit | norbert_mate's commentslogin

Hi languagehacker, this is not science fiction. It just shows you a way of implementing a serializer that works for all kind of models in Django Rest Framework.


Thanks.


Correct. It's very easy to create a simple model serializer and this is what the general model serializer does. It's no big deal just saves a few line of code.


I agree with you. It is a bit weird that a serializer can interact with the database but what it basically does: hides the database interaction.


The model / model manager layer is the right place at which to design your state changing API. REST framework absolutely you to work with the grain there. Some good practice I'd recommend...

* Write the `create()` and/or `update()` methods explicitly on the serializer class.

* Push logic into the model and model manager where possible and only have the serializer `.save()` as a thin layer on top of that.

That way a serializer class still has all the behavior it needs to map both ways between persisted objects and their corresponding native python representations, but you still have a well separated model API.


Interesting. In practice, I have started following a pattern where I have two Serializer classes - a "serializer" and a "deserializer".

The "deserializer"'s job is to perform validation and type coercion of incoming requests. It returns a "native" dictionary, which the application code then saves to ORM.

The "serializer" is basically a presentation layer. It calls out to other nested serializers [this is awesome!], and it throws in convenience-fields that make the API response easier to consume.

This pattern makes it a little bit less "magical", and it's easier to distinguish between the API's "incoming" behavior and its "outgoing" behavior.


out of curiosity, how often do you find yourself reading the DRF source code to figure out whats happening?


"The best documentation is the source code" :-) . I use to read it but sometimes is really hard to understand what's going on. As you said the serializer does a lot of thing.


In Django Rest Framework (DRF) you need serializer class. Maybe this is because DRF is not tightly coupled with the models from Django framework.

As far as I know DRF does not support PUT/UPDATE operations for nested serializers. But there are cases when you just need to read. Like getting an activity feed which can't be modified directly by the users. I think if you have a good caching system it's better to return all the data for one request instead of creating new requests to get details about each entity.


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: