How can I retrieve a list of field for all objects in Django?
I want to retrieve a list of all of the values for one field from a query in django. For example, I have a query of users, but rather than a queryset (or list) of user objects, I want a list just the usernames (strings). In a sense this is asking to restrict only to one column of data.
Have you tried
list(User.objects.all().values_list('username', flat=True))
If you only pass in a single field, you can also pass in the flat parameter. If True, this will mean the returned results are single values, rather than one-tuples. Additionally, casting it to a list makes the returned value a list instead of a queryset
To get the list of usernames:
>>> User.objects.all().values('username')
>>> [{'username': u'u1'}, {'username': u'u2'}]
>>> User.objects.all().values_list('username')
>>> [(u'u1',), (u'u2',)]
If you want just strings, a list comprehension can do the trick:
>>> usr_names = User.objects.all().values('username')
>>> [u['username'] for u in usr_names]
>>> [u'u1', u'u2']
Using values_list
:
>>> usr_names = User.objects.all().values_list('username')
>>> [u[0] for u in usr_names]
>>> [u'u1', u'u2']
As you wrote:
"but rather than a queryset (or list) of user objects"
Soulution above still queryset
usr_names = User.objects.all().values_list('username')
This solution:
usr_names = [str(elem) for elem in list(User.objects.all().values_list('username'))]
It will return a list of strings
The simplest way you can get the list of objects of an attribute is to first get a query-set of that attribute alone using values_list
then converting the django query-set to a python set using set()
and finally to a list using list()
.
In your scenario:
user_names = list(set(User.objects.all().values_list('username', flat=True)))