It is my guess that you must already have some table which contains some information about the type
or row. And if you do not, maybe you should have such a look-up table. In case this ordering is always the same, I would then add a column to this table to indicate the ordering, join on it and use it.
class TypeInfo(Base):
__tablename__ = 'typeinfo'
id = Column(Integer, primary_key=True)
sort_order = Column(Integer)
# assiming the database contains values like:
tis = [ TypeInfo(id=1, sort_order=50),
TypeInfo(id=2, sort_order=20),
TypeInfo(id=3, sort_order=30),
TypeInfo(id=4, sort_order=10),
TypeInfo(id=5, sort_order=40),
]
# your query might look like below:
q = session.query(SomeTable)
q = q.join(TypeInfo, SomeTable.type == TypeInfo.id).order_by(TypeInfo.sort_order)
In case when you cannot change the database, or the ordering might be different, you can solve this with the case
expression, although it might not be quick performer on large datasets:
_whens = {4: 1, 2: 2, 3: 3, 5: 4, 1: 5}
sort_order = case(value=SomeTable.type, whens=_whens)
q = session.query(SomeTable)
q = q.order_by(sort_order)