Search code examples
sql-order-byweb2py

How to sort web2py Grid rows by multiple fields?


Web2py newbie here.

Given the below Web2py model controller and view, how would I make Web2py display in the resulting view (index.html) the grid ordered by manufacturer first and by commercial_name second?

Model: dy.py

db.define_table('item',
    Field('manufacturer', db.business_partner, label = 'manufacturer'),
    Field('commercial_name', required=True, label = 'commercial name'),
    Field('technical_data_sheet', 'upload', label = 'tds'),
    format='%(manufacturer)s %(commercial_name)s')

Controller: default.py

def item():
    grid = SQLFORM.grid(db.item)
    return dict(grid=grid)

View: item.html

{{extend 'layout.html'}}
<h2>items and manufcaturer</h2>
{{=grid}}

Solution

  • Use orderby option of SQLFORM.grid(). And you can sort multiple fields by concatenating them with a "|".

    So in your case, grid definition will be:

    grid = SQLFORM.grid(db.item, orderby=db.item.manufacturer|db.item.commercial_name)
    

    Read Grid Signature and orderby