Documentation for stdnet 0.8.2. For development docs, go here.

Sorting and Ordering

Stdnet can sort instances of a model in three different ways:

Explicit Sorting

Sorting is usually achieved by using the Query.sort_by() method with a field name as parameter. Lets consider the following model:

class SportActivity(odm.StdNet):
    person = odm.SymbolField()
    activity = odm.SymbolField()
    dt = odm.DateTimeField()

models = odm.Router()
models.register(SportActivity)

To obtained a sorted query on dates for a given person:

qs = models.sportactivity.filter(person='pippo').sort_by('-dt')

The negative sign in front of dt indicates descending order.

Implicit Sorting

Implicit sorting is achieved by setting the Metaclass.ordering attribute in the model Meta class. Let’s consider the following Log model example:

class Log(odm.StdModel):
    '''A database log entry'''
    timestamp = odm.DateTimeField(default=datetime.now)
    level = odm.SymbolField()
    msg = odm.CharField()
    source = odm.CharField()
    host = odm.CharField()
    user = odm.SymbolField(required=False)
    client = odm.CharField()

    class Meta:
        ordering = '-timestamp'

models.register(Log)

It makes lots of sense to have the log entries always sorted in a descending order with respect to the timestamp field. This solution always returns Query in this order, without the need to call sort_by method.

Note

Implicit sorting is a much faster solution than explicit sorting, since there is no sorting step involved (which is a N log(N) time complexity algorithm). Instead, the order is maintained by using sorted sets as indices rather than sets.

Incremental Sorting

Table Of Contents

Previous topic

Query your Data

Next topic

Full text search

This Page