Django models are not ajax serializable
You just need to add, in your .dumps
call, a default=encode_myway
argument to let simplejson
know what to do when you pass it data whose types it does not know -- the answer to your "why" question is of course that you haven't told poor simplejson
what to DO with one of your models' instances.
And of course you need to write encode_myway
to provide JSON-encodable data, e.g.:
def encode_myway(obj): if isinstance(obj, User): return [obj.username, obj.firstname, obj.lastname, obj.email] # and/or whatever else elif isinstance(obj, OtherModel): return [] # whatever elif ... else: raise TypeError(repr(obj) + " is not JSON serializable")
Basically, JSON knows about VERY elementary data types (strings, ints and floats, grouped into dicts and lists) -- it's YOUR responsibility as an application programmer to match everything else into/from such elementary data types, and in simplejson
that's typically done through a function passed to default=
at dump
or dumps
time.
Alternatively, you can use the json
serializer that's part of Django, see the docs.