10

I am trying to get a list of the content of one attribute from all objects in a model.

For now, I am doing this:

titles_list = []
for item in  A.objects.all(): 
   titles_list.append(item.title)

print titles_list

Is there a more interesting solution based on a memory / time economy to do it?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Erwan
  • 1,055
  • 1
  • 12
  • 26

1 Answers1

15

The same can be implemented in one line using values_list() with flat=True:

print A.objects.values_list('title', flat=True)
Yuval Adam
  • 161,610
  • 92
  • 305
  • 395
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 4
    +1 . Just a side note, This would return `ValuesListQuerySet` object, which is fine for most cases. But if you need a python object list, just cast it to a list type `list()`. Also, `.all()` is redundant here. – karthikr Apr 02 '14 at 14:05
  • 1
    Edited and removed redundant `all()` – Yuval Adam Apr 02 '14 at 14:07