Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a list inside values_list() in django?

I am new to python and django.I am having a list obtained dynamically containing database table fieldnames. How do I use this list within values_list() in django queryset while fetching results from database?

fieldList=['field1','field2'] #list containing table fields
obj=sampletable.objects.filter(somecondition).values_list(fieldlist) #--->want like this

I came to know that we can't use lists simply as it is inside values_list().So I converted it into a string like this and then tried it but in vain.

fieldListstr=','.join(repr(e) for e in fieldList)

This is the error which I got

Cannot resolve keyword "'field1','field2'" into field. Choices are: field1, field2

Please help me with your solutions. And thanks in advance

like image 407
Ashwin Kanna Avatar asked Dec 04 '22 20:12

Ashwin Kanna


2 Answers

You can use argument list unpacking to pass the values of a list as arguments to a function like so:

values_list(*fieldlist)
like image 45
Increasingly Idiotic Avatar answered Dec 06 '22 09:12

Increasingly Idiotic


Simply unpack them,

.values_list(*fieldlist)
like image 75
Sayse Avatar answered Dec 06 '22 09:12

Sayse