Serializer/Deserializer with utf-8/timezone support
Sorry, this snippet only tested on Django ver.2.0rc1.
- serializer
- 2.0
Sorry, this snippet only tested on Django ver.2.0rc1.
This is a revised version of https://djangosnippets.org/snippets/2921/
Copy this file into `your_app/serializer.py`, and add this to your settings: SERIALIZATION_MODULES = { 'json': 'your_app.serializer', } Now you can dump your models with the classical `dumpdata -n` command and load it with `loaddata` and get support for natural primary keys and not only with foreign keys and many to many fields.
I find Django's default YAML serializer output too repetitive, so I came up with this customized version that avoids outputting the model name for every single object, and makes the primary key into an index for the object's fields. This allows many simple model instances to be serialized as one-liners. See the module docstring for additional explanation and usage notes.
CSV serialization for models. Can be used via the dumpdata/loaddata management commands or programmatically using the django.core.serializers module. Supports multiple header lines and natural keys. Add the following to settings.py: SERIALIZATION_MODULES = { 'csv' : 'path.to.csv_serializer', } Examples of usage: $ python manage.py dumpdata --format csv auth.user > users.csv from django.core import serializers csvdata = serializers.serialize('csv', Foo.objects.all()) To run the regression tests distributed with the Django tarball: $ cd /path/to/Django-1.2.x/tests $ PYTHONPATH=/path/to/myproject ./runtests.py --settings=myproject.settings serializers_regress
Makes it really easy to return JSON from your views: just return a dict. (Also from [django-webapp](http://code.google.com/p/django-webapp/).)
The Django JSON encoder already extends the `simplejson` encoder a little; this extends it more and gives an example of how to go about further extension. Hopefully `newserializers` (see the community aggregator today) will supercede this, but until then, it's useful.
7 snippets posted so far.