39👍
✅
I would go with extending simplejson. Basically, you want to plug in django’s serialization when the JSON encoder encounters a QuerySet. You could use something like:
from json import dumps, loads, JSONEncoder
from django.core.serializers import serialize
from django.db.models.query import QuerySet
from django.utils.functional import curry
class DjangoJSONEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, QuerySet):
# `default` must return a python serializable
# structure, the easiest way is to load the JSON
# string produced by `serialize` and return it
return loads(serialize('json', obj))
return JSONEncoder.default(self,obj)
# partial function, we can now use dumps(my_dict) instead
# of dumps(my_dict, cls=DjangoJSONEncoder)
dumps = curry(dumps, cls=DjangoJSONEncoder)
For more info on default
method, have a look at simplejson documentation. Put that in a python module, then import dumps
and you’re good to go. But note that this function will only help you serializing QuerySet
instances, not Model
instances directly.
13👍
A really flexible way to serialize most structures in django is to use the serializer class found here
- [Django]-How to pass a variable from settings.py to a view?
- [Django]-Different initial data for each form in a Django formset
- [Django]-Django- Get Foreign Key Model
10👍
based on Clement’s answer, I did this to get models into JSON as well.
def toJSON(obj):
if isinstance(obj, QuerySet):
return simplejson.dumps(obj, cls=DjangoJSONEncoder)
if isinstance(obj, models.Model):
#do the same as above by making it a queryset first
set_obj = [obj]
set_str = simplejson.dumps(simplejson.loads(serialize('json', set_obj)))
#eliminate brackets in the beginning and the end
str_obj = set_str[1:len(set_str)-2]
return str_obj
- [Django]-How do you know if memcached is doing anything?
- [Django]-Cancel an already executing task with Celery?
- [Django]-Django – convert a list back to a queryset
Source:stackexchange.com