Skip to content

Instantly share code, notes, and snippets.

@itmustbejj
Created August 30, 2011 19:20
Show Gist options
  • Save itmustbejj/1181770 to your computer and use it in GitHub Desktop.
Save itmustbejj/1181770 to your computer and use it in GitHub Desktop.
def serialize(self, queryset, **options):
"""
Serialize a queryset.
"""
self.options = options
self.stream = options.get("stream", StringIO())
self.selected_fields = options.get("fields")
self.use_natural_keys = options.get("use_natural_keys", False)
self.start_serialization()
for obj in queryset:
self.start_object(obj)
for field in obj._meta.local_fields:
if field.serialize:
if field.rel is None:
if self.selected_fields is None or field.attname in self.selected_fields:
self.handle_field(obj, field)
else:
if self.selected_fields is None or field.attname[:-3] in self.selected_fields:
self.handle_fk_field(obj, field)
for field in obj._meta.many_to_many:
if field.serialize:
if self.selected_fields is None or field.attname in self.selected_fields:
self.handle_m2m_field(obj, field)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment