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.
all() Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result.
If you are using Google App Engine or MongoDB as your backend, and you are using the djangoappengine library, there is a built in ListField that does exactly what you want. Further, it's easy to query the Listfield to find all objects that contain an element in the list.
The idea is to use Django's annotate (which is basically running group_by ) to find all the instances that have more than one row with the same my_id and process them as Ned suggests. Then for the remainder (which have no duplicates), you can just grab the individual rows.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With