Override sorting behavior

This is the official documentation of the forestadmin-agent-django and forestadmin-agent-flask Python agents.

Depending on the data source, not all fields may be sortable, or you may want to change how the native sorting works.

By using the replace_field_sorting and emulate_field_sorting methods, you can change a single column's sorting behavior.

Substitution

You can also provide replacement sort clauses. In this example, we're telling Forest Admin "When a user sorts by full name, I want to sort by the last name, and then by the first name".

collection.replace_field_sorting(
    "fullName",
    [
        {"field": "lastName", "ascending": True},
        {"field": "firstName", "ascending": True},
    ],
)

Another very common reason is performance. For instance, with auto-incrementing ids, sorting by creationDate is equivalent to sorting by the primary key in reverse order.

Using sort substitution where needed can save you from adding many indexes to your database.

collection.replace_field_sorting(
    "creationDate",
    [
        {"field": "id", "ascending": False},
    ],
)

Emulation

Sorting emulation allows making any field automatically sortable. It will sort records by lexicographical order. It is a convenient way to get things working quickly for Collections that have a low number of records (in the thousands at most).

This emulation forces the Agent to retrieve all the Collection records and compute the field values for each one of them. As a consequence, sorting emulation performance cost is linear with the number of records in the Collection, so activate it sparingly and with great care.

collection.emulate_field_sorting("fullName")

Last updated