0

I would like to provide Django's queryset only() function with a dynamic list of fields. In a view, you can manually write sth. like

queryset = self.model.objects.only('id', 'name', 'someotherfield')

However, I want to make this view (it's a view which lists all objects of a model in a table, but only the 4 or 5 fields of the model I choose) generic so that other views subclass this view and can provide a parameter with the list of fields of the respective model that should be displayed in the table.

But if I have the above example rewritten like

queryset = self.model.objects.only(self.display_list)

and display_list is given as

display_list = ['id', 'name', 'latitude', 'longitude']

it won't work, I get a "unhashable type: 'list'" TypeError.

It must be somehow possible to provide a list of arguments for the only() function with a parameter, but how?

1 Answer 1

3
queryset = self.model.objects.only(*self.display_list)

The * means "unpack this list and use its items as arguments". See this question for an explanation.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh, now the scales fall from my eyes. Sure! Thanks a lot. I thought I understood *args and **kwargs, now I do better. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.