4 Requires PyYaml (http://pyyaml.org/), but that's checked for in __init__.
7 from django
.db
import models
8 from django
.core
.serializers
.python
import Serializer
as PythonSerializer
9 from django
.core
.serializers
.python
import Deserializer
as PythonDeserializer
11 from cStringIO
import StringIO
13 from StringIO
import StringIO
16 class Serializer(PythonSerializer
):
18 Convert a queryset to YAML.
21 internal_use_only
= False
23 def handle_field(self
, obj
, field
):
24 # A nasty special case: base YAML doesn't support serialization of time
25 # types (as opposed to dates or datetimes, which it does support). Since
26 # we want to use the "safe" serializer for better interoperability, we
27 # need to do something with those pesky times. Converting 'em to strings
28 # isn't perfect, but it's better than a "!!python/time" type which would
29 # halt deserialization under any other language.
30 if isinstance(field
, models
.TimeField
) and getattr(obj
, field
.name
) is not None:
31 self
._current
[field
.name
] = str(getattr(obj
, field
.name
))
33 super(Serializer
, self
).handle_field(obj
, field
)
35 def end_serialization(self
):
36 self
.options
.pop('stream', None)
37 self
.options
.pop('fields', None)
38 yaml
.safe_dump(self
.objects
, self
.stream
, **self
.options
)
41 return self
.stream
.getvalue()
43 def Deserializer(stream_or_string
, **options
):
45 Deserialize a stream or string of YAML data.
47 if isinstance(stream_or_string
, basestring
):
48 stream
= StringIO(stream_or_string
)
50 stream
= stream_or_string
51 for obj
in PythonDeserializer(yaml
.load(stream
)):