Login

Convert a ValuesQuerySet to an array of dicts (useful for serializing)

Author:
waitinforatrain
Posted:
June 3, 2011
Language:
Python
Version:
1.3
Tags:
json serialization valuesqueryset
Score:
1 (after 1 ratings)

Perhaps this is blindingly obvious but I spent a while trying to get this, before figuring out that when a each item of an iterated ValuesQuerySet is a dict.

Useful for serialising to JSON or XML etc.

1
2
3
4
5
6
7
def ValuesQuerySetToDict(vqs):
    return [item for item in vqs]

# Usage
data=MyModel.objects.values('id','title','...','...')
data_dict = ValuesQuerySetToDict(data)
data_json = simplejson.dumps(data_dict)

More like this

Comments

siloraptor (on June 3, 2011):
<p>Django provides native means of serialising it's models:</p> <p>from django.core import serializers data = serializers.serialize("xml", SomeModel.objects.all())</p> <p>https://docs.djangoproject.com/en/dev/topics/serialization/</p>

#

waitinforatrain (on June 3, 2011):
<p>@siloraptor That won't let you serialise a ValuesQuerySet result</p>

#

rix (on June 3, 2011):
<p>Why not converting to a list?</p> <p>list(MyModel.objects.values('id','title','...','...'))</p>

#

waitinforatrain (on June 5, 2011):
<p>Didn't know you could do that. Dicts can be useful if you want to create more complex nested JSON.</p>

#

Please login first before commenting.