

Django Rest Framework general model serializer - norbert_mate
http://blog.hipwerk.com/django-rest-framework-general-model-serializer/

======
mercnet
For anyone looking for argument parsing and serialization with Flask, I
recommend webargs
([http://webargs.readthedocs.org/](http://webargs.readthedocs.org/)),
marshmallow
([http://marshmallow.readthedocs.org](http://marshmallow.readthedocs.org)),
and flask-marshmallow ([http://flask-
marshmallow.readthedocs.org/](http://flask-marshmallow.readthedocs.org/)).

~~~
ddorian43
what rest-framework do you use with flask ? or build one yourself using what
components (except these 2)?

~~~
plq
You can use Spyne[1]'s HttpRpc and JsonDocument protocols via Flask-Spyne[2].

You can actually use Spyne with Django as well[3] (and Spyne has a "general
model serializer" that can be used with a lot less boilerplate than what's
shown here).

Spyne supports a lot of protocols as well as persisting to a relational
database via SQLAlchemy.

Disclaimer: I'm the author of spyne.

[1]: [http://spyne.io](http://spyne.io)

[2]: [https://pypi.python.org/pypi/Flask-
Spyne](https://pypi.python.org/pypi/Flask-Spyne)

[3]:
[https://github.com/arskom/spyne/tree/master/examples/django/...](https://github.com/arskom/spyne/tree/master/examples/django/rpctest)

------
kayoone
I am quite amazed this has to be done manually in Django. I work a lot with
Symfony2 in PHP and that kind of Object serialization thing is pretty much
built in. I just return my model from the controller and it gets serialized to
JSON including child objects with pretty fine grained controls about what to
serialize.

Besides, after working a lot with REST webservices and AngularJS, i don't know
if serializing child objects is really a good idea vs just getting the id and
then using the api endpoint for the specific children separately. Having child
objects serialized creates problems when doing PUT/UPDATE requests and you can
also end up with fairly large sets of JSON. Of course doing dozens of requests
instead (especially for lists) is also not the best of ideas, so i am not
really sure how others handle this ?

~~~
andybak
Django does this out of the box:
[https://docs.djangoproject.com/en/1.7/topics/serialization/](https://docs.djangoproject.com/en/1.7/topics/serialization/)

But DRF adds lots of extra functionality. Even with DRF it's as simple as
adding:

    
    
        class UserSerializer(serializers.ModelSerializer):
            class Meta:
                model = User
    

to get full automatic serialization of a model.

> I don't know if serializing child objects is really a good idea

Depends on the specific case. For internal APIs I tend to create endpoints
that give a view what it needs in a single request.

~~~
whalesalad
You say "out of the box" but it's not that simple... 'blah blah DateTime is
not JSON serializable'

~~~
andybak
Just tried it:

    
    
        from django.core import serializers
        print serializers.serialize("json", StockCount.objects.all()[:2])
        >> [{"fields": {"timestamp": "1900-01-02T00:00:00Z", "version": 0, "item_instance": null, "item_model": 408, "stock_level": 999, "location": 2}, "model": "stocklevels.stockcount", "pk": 1}, {"fields": {"timestamp": "1900-01-02T00:00:00Z", "version": 0, "item_instance": null, "item_model": 409, "stock_level": 999, "location": 2}, "model": "stocklevels.stockcount", "pk": 2}]

------
skatenerd
I really have a problem with the concept of the Serializer in DRF. It handles
so much that has nothing to do with serialization. It performs something like
de-serialization, where it takes an incoming dictionary and turns it into an
ORM object. The docs even recommend using its ".save()" method. Save? on a
Serializer?

I think it's a really cool concept if you think of it as more of a Lens. The
so-called serializer lets you declare properties of "fields", and these
properties will influence both the native-to-ORM conversion, as well as the
ORM-to-native conversion.

~~~
norbert_mate
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.

~~~
tomchristie
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.

~~~
skatenerd
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.

------
numlocked
I think it's somewhat rare to have generic relations (content type + model id)
popping up this way in serializers. I tend to use generic FKs for things like
"tags" or or "comments" that can apply to multiple objects. As a result, I'm
almost always requesting the parent object ("post") and want the model with
the generic FK serialized in that response ("post.comments"), not the other
way around.

Just looking through largish DRF codebase, I'm not sure there are many places
I could use this, thought it seems like a good idea if your code has a lot of
these scenarios.

~~~
norbert_mate
Thanks.

------
languagehacker
Nice to see Django Rest Framework getting some press, but I don't understand
how this provides value beyond the existing documentation on readthedocs.

~~~
norbert_mate
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.

