3

I have a model named Songs and one of its attributes is 'title'.

Let's say I want to get a list of all the song titles stored in a database.

I could do:

titles = []

for song in Song.objects.all():
    titles.append(song.title)

Is there is a simpler way of doing this?

Saša Kalaba
  • 4,241
  • 6
  • 29
  • 52

2 Answers2

9

Best variant: Song.objects.values('title')

Documentaion: https://docs.djangoproject.com/en/1.8/ref/models/querysets/#values

viktor.svirskyy
  • 469
  • 2
  • 8
9

You can use .values_list() to get the list of all the song titles.

It will return list of tuples values. Each tuple contains the value from the respective field passed into the values_list() call.

Song.objects.values_list('title') 
[('title1',), ('title2',), ('title3',), (u'title4',)] # returns list of tuples

If you pass in the flat parameter set to True, it will return the results as single values, rather than one-tuples.

Song.objects.values_list('title', flat=True) # pass 'flat' parameter
['title1', 'title2', 'title3', 'title4'] # returns list of titles 

I think this is what you intended to get in the first place.

But remember, it is an error to pass in flat with more than one field.

You can also use .values() to get all the titles but it will return list of dictionaries with each dictionary representing an object, with the keys corresponding to the attribute names of model objects.

Song.objects.values('title') # using '.values'
[{'title': 'title1'}, {'title': 'title2'}, {'title': 'title3'}, {'title': 'title4'}] # returns list of dictionaries
Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126