How can I retrieve a list of field for all objects in Django?

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']

Tags:

Django