2 Interfaces for serializing Django objects.
6 from django.core import serializers
7 json = serializers.serialize("json", some_query_set)
8 objects = list(serializers.deserialize("json", json))
10 To add your own serializers, use the SERIALIZATION_MODULES setting::
12 SERIALIZATION_MODULES = {
13 "csv" : "path.to.csv.serializer",
14 "txt" : "path.to.txt.serializer",
19 from django
.conf
import settings
21 # Built-in serializers
22 BUILTIN_SERIALIZERS
= {
23 "xml" : "django.core.serializers.xml_serializer",
24 "python" : "django.core.serializers.python",
25 "json" : "django.core.serializers.json",
28 # Check for PyYaml and register the serializer if it's available.
31 BUILTIN_SERIALIZERS
["yaml"] = "django.core.serializers.pyyaml"
37 def register_serializer(format
, serializer_module
):
38 """Register a new serializer by passing in a module name."""
39 module
= __import__(serializer_module
, {}, {}, [''])
40 _serializers
[format
] = module
42 def unregister_serializer(format
):
43 """Unregister a given serializer"""
44 del _serializers
[format
]
46 def get_serializer(format
):
49 return _serializers
[format
].Serializer
51 def get_serializer_formats():
54 return _serializers
.keys()
56 def get_public_serializer_formats():
59 return [k
for k
, v
in _serializers
.iteritems() if not v
.Serializer
.internal_use_only
]
61 def get_deserializer(format
):
64 return _serializers
[format
].Deserializer
66 def serialize(format
, queryset
, **options
):
68 Serialize a queryset (or any iterator that returns database objects) using
71 s
= get_serializer(format
)()
72 s
.serialize(queryset
, **options
)
75 def deserialize(format
, stream_or_string
):
77 Deserialize a stream or a string. Returns an iterator that yields ``(obj,
78 m2m_relation_dict)``, where ``obj`` is a instantiated -- but *unsaved* --
79 object, and ``m2m_relation_dict`` is a dictionary of ``{m2m_field_name :
80 list_of_related_objects}``.
82 d
= get_deserializer(format
)
83 return d(stream_or_string
)
85 def _load_serializers():
87 Register built-in and settings-defined serializers. This is done lazily so
88 that user code has a chance to (e.g.) set up custom settings without
89 needing to be careful of import order.
91 for format
in BUILTIN_SERIALIZERS
:
92 register_serializer(format
, BUILTIN_SERIALIZERS
[format
])
93 if hasattr(settings
, "SERIALIZATION_MODULES"):
94 for format
in settings
.SERIALIZATION_MODULES
:
95 register_serializer(format
, settings
.SERIALIZATION_MODULES
[format
])