django queryset-list-pytho.native.list转换
How do I convert a Django QuerySet into list of dicts?
https://stackoverflow.com/questions/7811556/how-do-i-convert-a-django-queryset-into-list-of-dicts
>>> 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
.
用list()转换一下,才是list instance
listdata= list( User.object.values('name','age'))
The .values()
method will return you a result of type ValuesQuerySet
which is typically what you need in most cases.
But if you wish, you could turn ValuesQuerySet
into a native Python list using Python list comprehension as illustrated in the example below.
result = Blog.objects.values() # return ValuesQuerySet object list_result = [entry for entry in result] # converts ValuesQuerySet into Python list return list_result
If you need native data types for some reason (e.g. JSON serialization) this is my quick 'n' dirty way to do it:
data = [{'id': blog.pk, 'name': blog.name} for blog in blogs]