Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: values_list(flat=True) but for multiple fields

I have a model, TestModel

As far as I know, if I were to implement

TestModel.objects.values_list('FieldA', flat=True)

This results in [A,B,C,(...)] (a list)

And doing this TestModel.objects.values_list('FieldA','FieldB')

results in [(A,1),(B,2),(C,3),(...)] (a list of querysets)

But is it possible to get a similar result to Flat=True but for multiple fields? So, if I were to use something like

testQS = TestModel.objects.values_list('FieldA','FieldB')

and call testQS['FieldA'], this will return [A,B,C,(...)]

Likewise, calling testQS['FieldB'] will return [1,2,3,(...)]

Basically, I want to get all the data from a certain field in a values_list with multiple fields without resorting to for loop or creating values_list multiple times for each field.

like image 410
Erik Avatar asked Nov 07 '25 10:11

Erik


1 Answers

You can use itertools chain approach. It will flatten your list.

import itertools

qs = TestModel.objects.values_list('FieldA','FieldB')
qs = list(itertools.chain(*qs))
return qs
like image 88
Arzu Huseynov Avatar answered Nov 10 '25 08:11

Arzu Huseynov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!