[Django]-A better way to get only specific attributes from a Django queryset?

9👍

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

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

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

Leave a comment