简体   繁体   中英

convert a django queryset into an array

i would like convert a django queryset into an array like,

firstnames=Users.objects.values('firstnames')

to get a result that looks like

firstnames = ["Nancy", "Andrew", "Janet", "Margaret", "Steven", "Michael", "Robert", "Laura", "Anne"];

Any insights please? Regards Josh

Use QuerySet.values_list and specify flat=True :

firstnames = Users.objects.values_list('firstnames', flat=True)
firstnames = list(firstnames)
def get_array(Table, column):
    rows = Table.objects.values(column)
    return [row[column] for row in rows]

print get_array(Users, 'firstnames')

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM