If you're dealing with a list of model instances the best you can do is using serializers.serialize()
, it gonna fit your need perfectly.
However, you are to face an issue with trying to serialize a single object, not a list
of objects. That way, in order to get rid of different hacks, just use Django's model_to_dict
(if I'm not mistaken, serializers.serialize()
relies on it, too):
from django.forms.models import model_to_dict
# assuming obj is your model instance
dict_obj = model_to_dict( obj )
You now just need one straight json.dumps
call to serialize it to json:
import json
serialized = json.dumps(dict_obj)
That's it! :)