How do you serialize a model instance in Django?
You can easily use a list to wrap the required object and that's all what django serializers need to correctly serialize it, eg.:
from django.core import serializers# assuming obj is a model instanceserialized_obj = serializers.serialize('json', [ obj, ])
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 instancedict_obj = model_to_dict( obj )
You now just need one straight json.dumps
call to serialize it to json:
import jsonserialized = json.dumps(dict_obj)
That's it! :)
To avoid the array wrapper, remove it before you return the response:
import jsonfrom django.core import serializersdef getObject(request, id): obj = MyModel.objects.get(pk=id) data = serializers.serialize('json', [obj,]) struct = json.loads(data) data = json.dumps(struct[0]) return HttpResponse(data, mimetype='application/json')
I found this interesting post on the subject too:
http://timsaylor.com/convert-django-model-instances-to-dictionaries
It uses django.forms.models.model_to_dict, which looks like the perfect tool for the job.