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?

Marc
  • 147
  • 1
  • 2
  • 10

1 Answers1

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.

Community
  • 1
  • 1
spectras
  • 13,105
  • 2
  • 31
  • 53
  • Ahhh, now the scales fall from my eyes. Sure! Thanks a lot. I thought I understood *args and **kwargs, now I do better. :) – Marc Aug 08 '15 at 13:17