Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 358
askvictor Avatar asked Feb 01 '13 03:02

askvictor


People also ask

What does objects all () return in Django?

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.

Is there a list field in Django?

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.

How do I get all rows in Django?

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.


2 Answers

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

like image 129
akotian Avatar answered Oct 06 '22 10:10

akotian


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'] 
like image 35
santiagobasulto Avatar answered Oct 06 '22 10:10

santiagobasulto