Sorting functions

class metapensiero.sqlalchemy.proxy.sorters.Direction

Sort direction.

ASC = '<'

Ascending order.

DESC = '>'

Descending order.

class metapensiero.sqlalchemy.proxy.sorters.Sorter

Represent a single field ordering specification.

classmethod make(property, direction=<Direction.ASC>)

Helper to create a new instance.

The direction argument defaults to Direction.ASC and gets coerced to a Direction instance using its Direction.make() class method.

metapensiero.sqlalchemy.proxy.sorters.apply_sorters(query, args)

Order a given query.

Parameters:
  • query – an SQLAlchemy Query
  • args – a dictionary
Return type:

an SQLAlchemy Query

query may be either a SQL statement or an ORM query.

The args dictionary may contain some special keys, that will be used to build an set of ordering specifications.

Important

All these keys will be consumed, that is removed from the args dictionary.

sort_col
the name of the field to sort the result by: it may be a single name or a comma-separated-list of column names
sort_dir
when sort_col is specified, the direction to sort with: it may be either "ASC", the default, or "DESC" to specify a DESCending order
sort_by_name-of-the-field
specify both the name-of-the-field and the sorting direction
sorters

either a single or a list of sort specifications (possibly as a JSON encoded string): each one may be either

  • a Sorter instance
  • a plain string, the name of a field
  • a comma-separated-list of field names
  • a sequence of two values, respectively the field name and the sort direction
  • a mapping with a slot property and an optional direction slot

The function extract_sorters() is used to extract the specifications.

metapensiero.sqlalchemy.proxy.sorters.extract_sorters(args)

Extract sort specification.

Parameters:args – a dictionary
Return type:a list of Sorter instances

Recognize different kinds of specification:

  1. the “old” way: ?sort_col=fieldname or ?sort_col=fieldname&sort_dir=DESC; sort_col may also be a comma-separated-list of field names
  2. the “new” way: the sorters argument is a (possibly JSON encoded) list of dictionaries, each containing a property slot and a direction slot, respectively the field name and the ordering direction
  3. a custom syntax: ?sort_by_fieldname=DESC

The different syntaxes may be specified together, and they will be applied in the order above.

Note

the args parameter is modified in place!