1. Alberto Valverde González
  2. rum


Clone wiki

rum / SortByRelation

It is also possible to sort the index view, by a field, which represents a relation, so usually no column of the db table itself.

There exists a default ordering for table view, which is usually generated by primary keys, but can be overriden. Using the generic function apply default ordering. We provide a use case later.

Tables can be resorted clicking on the table headers, where the field is sortable.

Handling by a relation is a little bit difficult, as we can usually only sort by columns properties of the object. The relation doesn't fit into that.

But instead, we add a ColumnProperty to our class (which is called Participation in our example). In our example, we will call it sort_name.

    mapper(Participation, t_participation, properties=dict(
        sort_name=column_property(select([t_person.c.sort_name], t_person.c.person_id==t_participation.c.person_id).label("sort_name")))

Then we make the set the sortable tag for the Relation field (e.g. by registering a modified field).


In our case the field definition is

Relation(name="person", other=Person, sortable=True)

Finally, we map the "column" person (representing the relation) to the column property sort_name.

This can be done, using then generic function: remap_sort_column from rumalchemy.query

@remap_sort_column.when("isinstance(self, SAQuery) and col=='person' and self.resource is Participation")
def _make_person_field_criterium(self, col):
    return 'sort_name'

That is all, what is needed to sort by an related object.

A similar extension could be possible made for searching...