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?
Best variant: Song.objects.values('title')
Documentaion: https://docs.djangoproject.com/en/1.8/ref/models/querysets/#values
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.