Is there a way to pass a list into model.objects.values() in Django?

Viewed 314

I want to only display specific columns from my model, I know this way works:

Transactionlog.objects.values('column1','column2','column3')

But I have a list I need to populate into, I'm using django filters so my code looks like this:

filtered_transactions = transactionFilter(
                request.GET,
                queryset=Transactionlog.objects.values('column1','column2'))

My problem is that I have a dynamic list being populated via a seperate model, and i need to pass this list into values(), but it doesn't take list, from what i can tell anyway.

my solution so far ( horrible for large datasets...and small):

if len(column_list) == 1:
    filtered_transactions = transactionFilter(
            request.GET,
            queryset=Transactionlog.objects.values(column_list[0]))
if len(column_list) == 2:
    filtered_transactions = transactionFilter(
            request.GET,
            queryset=Transactionlog.objects.values(column_list[0],column_list[1]))
...

Please tell me there is another way of doing this, becuase this is driving me up the wall!

1 Answers

You can use an asterisk (*) to unpack an iterable into inividual parameters:

filtered_transactions = transactionFilter(
        request.GET,
        queryset=Transactionlog.objects.values(*column_list)
)

It is however odd to use .values(…) in the first place. Normally one fetches the objects, and then renders certain columns. By using .values(…), one erodes the logical layer a model provides. So properties, etc. defined on the model are no longer accessible.

Related