5

Given the following table

class ProductsTable(Table):
  allow_sort=True

  id=Col('ID', show=False)
  price=Col('Price')
  available_online=Col('Available online?')
  available_num=Col('In stock')
  edit=ButtonCol('Edit', url_kwargs=dict(id='id'), endpoint='/products')

  def sort_url(self, col_id, reverse=False):
    if reverse:
      order = 'desc'
    else:
       order = 'asc'
    return '?sort={}&order={}'.format(col_id, order)

From this I get the following example paths:

http://localhost:5000/products?sort=price&order=asc
http://localhost:5000/products?sort=available_num&order=asc

I use the parameters to generate an SQL query, which I execute on my SQLite DB and render the respective sorted table.

Now my issue comes from the reverse argument in my sort_url. I am unable to find any example that doesn't have it as optional argument and hence I'm unable to find anything that tells me how this argument can be set.

Of course I can always alter the URL. For the two examples above this would mean

http://localhost:5000/products?sort=price&order=desc
http://localhost:5000/products?sort=available_num&order=desc

However I want the order to change whenever the user clicks on the head of the specific table column.

How do I do that? Do I have to employ the actual HTML (and also add JavaScript) or is it possible to do it through Flask. Tables I've seen online normally have the arrows up/down symbol

enter image description here

that, whenever clicked, toggle the sorting order.

This involves JS and HTML modifications. I'd like to stick to Flask and Python if possible. The way Flask tables currently seem to work is a click cannot toggle the value of reverse.

Even if I expose the reverse parameter to the constructor of my own table like this

def __init__(self, items, reverse):
  super().__init__(items, sort_reverse=reverse)

so that I can set it depending on the value extracted from the URL, my question how to actually set the value remains unanswered.

rbaleksandar
  • 8,713
  • 7
  • 76
  • 161
  • The thing to bear in mind is that if you try and do this with flask it requires an extra query and therefore round trip to the DB every time the arrow is clicked, which is slow in terms of communication costs. You're much better off using a JS table library so that 1 request can be sent to the DB, the data is then kept is some kind of state/session storage, and the ordering happens in the browser when the button is clicked. – mdmjsh Feb 02 '21 at 14:52

0 Answers0