Return selection of fields from a Model in django
Hay guys, i want to use something like this
users = User.objects.all()
but i only want to return a couple of fields for each result, say 'name' and 'email'. This data is going t be turned into JSON da开发者_开发知识库ta, and some fields in my model are sensitive.
How would i do this in django?
Use values
or values_list
:
>>> User.objects.values('name', 'email')
[{'name': 'Daniel', 'email':'daniel@whatever.com'}, ...]
>>> User.objects.values_list('name', 'email')
[['Daniel', 'daniel@whatever.com'], ...]
See the documentation.
精彩评论