- June 3, 2011
- 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
- Image compression before saving the new model / work with JPG, PNG by Schleidens 6 days, 15 hours ago
- Help text hyperlinks by sa2812 1 month ago
- Stuff by NixonDash 3 months, 1 week ago
- Add custom fields to the built-in Group model by jmoppel 5 months, 1 week ago
- Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 8 months, 3 weeks ago
Django provides native means of serialising it's models:
from django.core import serializers data = serializers.serialize("xml", SomeModel.objects.all())
@siloraptor That won't let you serialise a ValuesQuerySet result
Why not converting to a list?
Didn't know you could do that. Dicts can be useful if you want to create more complex nested JSON.
Please login first before commenting.