Merged the queryset-refactor branch into trunk.
[fdr-django.git] / django / core / serializers / __init__.py
blob47dfb0c87a65f2dffcc8b4de86cbc33d6e3e30b3
1 """
2 Interfaces for serializing Django objects.
4 Usage::
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",
17 """
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.
29 try:
30 import yaml
31 BUILTIN_SERIALIZERS["yaml"] = "django.core.serializers.pyyaml"
32 except ImportError:
33 pass
35 _serializers = {}
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):
47 if not _serializers:
48 _load_serializers()
49 return _serializers[format].Serializer
51 def get_serializer_formats():
52 if not _serializers:
53 _load_serializers()
54 return _serializers.keys()
56 def get_public_serializer_formats():
57 if not _serializers:
58 _load_serializers()
59 return [k for k, v in _serializers.iteritems() if not v.Serializer.internal_use_only]
61 def get_deserializer(format):
62 if not _serializers:
63 _load_serializers()
64 return _serializers[format].Deserializer
66 def serialize(format, queryset, **options):
67 """
68 Serialize a queryset (or any iterator that returns database objects) using
69 a certain serializer.
70 """
71 s = get_serializer(format)()
72 s.serialize(queryset, **options)
73 return s.getvalue()
75 def deserialize(format, stream_or_string):
76 """
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}``.
81 """
82 d = get_deserializer(format)
83 return d(stream_or_string)
85 def _load_serializers():
86 """
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.
90 """
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])