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

Viewed 3687

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.

3 Answers

You can use this approach:

fields = ['FieldA','FieldB']
testQS = list(TestModel.objects.values_list(*fields))
result = {field:[] for field in fields}
counter = 0
for item in testQS:
    result = {field:[*result[field],item[counter]] for field in fields}
    counter +=1

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

You can use TestModel.objects.values_list('FieldA','FieldB', named=True)

Related