0

Hi I have a table thus:

class MyTable(tables.Table):

    brand = tables.Column(verbose_name='Brand')
    market = tables.Column(verbose_name='Market')
    date = tables.DateColumn(format='d/m/Y')
    value = tables.Column(verbose_name='Value')

I'm populating the table with a list of dicts and then I'm configuring it and rendering it in my view in the usual django-tables2 way:

data = [
    {'brand': 'Nike', 'market': 'UK', 'date': <datetime obj>, 'value': 100},
    {'brand': 'Django', 'market': 'FR', 'date': <datetime obj>, 'value': 100},    
]

table = MyTable(data)

RequestConfig(request, paginate=False).configure(table)

context = {'table': table}

return render(request, 'my_tmp.html', context)

This all renders the table nicely with the correct data in it. However, I can sort by the date column and the value column on the webpage, but not by the brand and market. So it seems non-string values can be sorted but strings can't. I've been trying to figure out how to do this sorting, is it possible with non-queryset data?

I can't populate the table with a queryset, as I'm using custom methods to generate the value column data. Any help appreciated! I guess I need to specify the order_by parameter in my tables.Column but haven't found the correct setting yet.

1 Answer 1

-1

data.sort(key = lambda item: item["brand"].lower()) will sort the list in place (so it will return None; the original 'data' list is edited) based on brand (alphabetically). The same can be done for any key.

Alternatively, sorted(data, key = lambda item: item["brand"].lower()) returns a sorted copy of the list.

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

9 Comments

where would I put this piece of code, in the table or the view?
after you get the information as a list, inser the list into this code :)
also any idea why the Column objects support sorting the datetime objects and non-string values natively, but not strings?
(where data is the list)
No, I am not familiar with django
|

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.