> > I'm Trying to serialize a dict which have a list of Model's instance.
> > The format that i need is json. Something like that:
>
> > people = Person.objects.all()
> > res = {'res':0, 'msg':'Ok','data': people}
>
> > .... but, i need that result:
> > {'res':0, 'msg':'Ok','data': [{'id':1,'name':'Sean'},
> > {'id':1,'name':'Steve'}]}
>
> > When I tried:
> > simplejson.dump(res)
> > I had this error:
>
> > [<Person: Person object>, <Person: Person object>] is not JSON
> > serializable
>
> Indeed. It needs a custom, model aware encoder.
>
> > When I tried:
> > json_serializer = serializers.get_serializer("json")()
> > json_serializer.serialize(object,
> > ensure_ascii=False)
> > I had this error:
> > 'str' object has no attribute '_meta'
>
> Django's json serializer takes a queryset as argument.
>
> > please, help
>
> Had the same problem, my solution is here:
>
> http://www.djangosnippets.org/snippets/1374/
Bruno, Thank you for your reply.
I tried your snipper, but I had the same error.
Finally, I solved it using this:
def api_serialize(objects):
res = []
for el in objects['data'] :
fields = map( lambda f: f.name, el._meta.fields)
values = dict([ (n, getattr( el,n) if not isinstance(getattr
( el,n), Model) else getattr( el,n).__str__() ) for n in
fields])
res.append(values)
objects['data'] = res
return simplejson.dumps(objects, ensure_ascii=False )
Regards
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to
django-users+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---