furayo
furayo

Reputation: 15

Sorting on a count field in web2py

I have the following code in web2py. I am trying to retrieve how many types of items I have in the table and a count of how many of each of them there are.

count = db.table.field1.count()
rows=db((some criteria).select(db.table.field2, count, groupby=db.table.field2)
print rows

The print of this is:

table.field2, COUNT(table.field1)
4,3
6,4
9,2

Now I would like to sort from high to low by the count field, so the outcome would be:

6,4
4,3
9,2

What's the best way to do it? rows=rows.sort(lambda row: row.COUNT(table.field1)) did not work for me.

Upvotes: 0

Views: 1791

Answers (1)

Anthony
Anthony

Reputation: 25536

Instead of row.COUNT(table.field1), use row['COUNT(table.field1)'] or just row[count] (see here).

Note, you can also have the database do the sorting using the orderby argument:

rows = db(query).select(db.table.field2, count,
                        groupby=db.table.field2, orderby=count)

And for descending order: orderby=~count

Upvotes: 1

Related Questions