Created
July 13, 2011 18:11
-
-
Save asadawan/1080902 to your computer and use it in GitHub Desktop.
A Serializer on top of djano serializer that handels list fields (from djano non-rel)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
@author: Asad K Awan | |
@copyright: Asad K Awan | |
@license: BSD | |
""" | |
from django.core.serializers.python import Serializer as PySerializer | |
class PySer(PySerializer): | |
""" | |
Every thing in django.core.serializers.python is | |
great except for: | |
1. its handling of foreign keys. we dont want to hit db, just get the id out. | |
2. handle list fields. | |
Note this won't be de-serializable. | |
""" | |
def end_object(self, obj): | |
if obj.pk is not None: self._current['id'] = obj.pk | |
self.objects.append(self._current) | |
self._current = None | |
def handle_field(self, obj, field): | |
value = field._get_val_from_obj(obj) | |
if value is None: | |
return # don't even store it. | |
if isinstance(value, list): | |
if len(value) == 0: return | |
v = value[0] | |
if isinstance(v, (int, long, float, Decimal, | |
datetime.datetime, datetime.date, | |
datetime.time, unicode)): | |
self._current[field.name] = value | |
else: | |
ps = PySer() | |
self._current[field.name] = ps.serialize(value) | |
return | |
if is_protected_type(value): | |
self._current[field.name] = value | |
else: | |
self._current[field.name] = field.value_to_string(obj) | |
def handle_fk_field(self, obj, field): | |
fieldName = field.name + '_id' | |
value = getattr(obj, fieldName) | |
if value is not None: | |
self._current[fieldName] = value | |
def handle_m2m_field(self, obj, field): | |
raise NotImplemented |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment