1

I have a django template in which I wish to present a table of fields. I want the table to contain different columns based on a subset of fields of a database. Which fields are displayed is based on a GET call (and thus cannot be predetermined).

The difficulty I am having is that I cannot label/order the columns arbitrarily and then get the fields to match up. I am using model.object.values to select the columns I want.

The solutions I have tried are:

  1. Iterating over the dictionary. This returns the fields in a random order, and furthermore in an order that is not guaranteed to be stable across elements of the database, although in practice this seems to be the case.
  2. Using values_list, however I still cannot control the order, but at least it's fixed.
  3. Passing the field names, and using them to access the dictionary, however I cannot work out how to call dict.get with a parameter. I think this is intentionally impossible.
  4. Both 2 and 3 together. There is no obvious way to make this work without some ugly nested string comparisons and indexing hackery.
  5. Iterating over items, this seems to require nested loops to determine which element goes in which cell.

Any help would be appreciated.

N.B. dictsort sorts rows, not columns.

Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
jhoyla
  • 1,191
  • 1
  • 9
  • 26

1 Answers1

0

You can either go with #3 and use the template filter suggested here or just prepare the data in your view instead of attempting to do this in your template. More specifically, you can create a list of column headings in your chosen order and for each object from your database create a tuple of values in the correct order.

Community
  • 1
  • 1
koniiiik
  • 4,240
  • 1
  • 23
  • 28