Using Django’s serialization framework to serialize data into the most popular formats, i.e. xml, json or yaml is quite straightforward. This can be quite useful if you’re e.g. trying to pass some json encoded data to the client-side and you don’t really want to add the entire django-rest-framework to your list of dependencies.
Concrete scenario
I’m often using select2jQuery component in my Django projects when I want a powerful yet simple autocomplete select widgets. If I just need to render a mostly static list of options for the select autocomplete, most of the time I find it easiest to simply pass a json encoded QuerySet and initialize the select2 component with the passed json object.
Problem
Using the built-in serializers from the core module is pretty easy:
And even though you can pass the fields argument to only serialize a specified subset of the model fields:
It is not possible to pass the list of model class properties:
Solution
The solution is to write a custom Serializer, inheriting from a couple of Django core serializers to make things DRY:
The usage is now straightforward, e.g. in your views:
Adding a bit shorter wrapper function
I usually add a helper function to the serializers.py as well to have a bit more concise serialize step:
And now you can use it within your views e.g.:
Or, not passing fields at all:
Conclusion
To include model class properties in the serialization output:
write a custom Serializer class within your serializers.py;
use that serializer to pass the props argument to specify the subset of class properties to serialize;
optionally, write a bit shorter wrapper function to save a few letters when serializing data.