Issue
How can I convert a Django QuerySet into a list of dicts? I haven't found an answer to this so I'm wondering if I'm missing some sort of common helper function that everyone uses.
Solution
Use the .values()
method:
>>> Blog.objects.values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]
Note: the result is a QuerySet
which mostly behaves like a list, but isn't actually an instance of list
. Use list(Blog.objects.values(…))
if you really need an instance of list
.
Answered By - David Wolever
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.