python queryset转字典,如何将Django QuerySet转换为列表?

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.

解决方案

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.

你可能感兴趣的:(python,queryset转字典)