async def test_sort_embedded_field(engine: AIOEngine): class E(EmbeddedModel): field: int class M(Model): e: E instances = [M(e=E(field=0)), M(e=E(field=1)), M(e=E(field=2))] await engine.save_all(instances) results = await engine.find(M, sort=desc(M.e.field)) assert results == sorted(instances, key=lambda instance: -instance.e.field)
async def test_find_sort_multiple_descriptors(engine: AIOEngine): class TestModel(Model): a: int b: int c: int persisted_models = [ TestModel(a=1, b=2, c=3), TestModel(a=2, b=2, c=3), TestModel(a=3, b=3, c=2), ] await engine.save_all(persisted_models) results = await engine.find( TestModel, sort=( desc(TestModel.a), TestModel.b, TestModel.c.asc(), # type: ignore ), ) assert results == sorted( persisted_models, key=lambda test_model: (-test_model.a, test_model.b, test_model.c), )
from odmantic import AIOEngine, Model, query engine = AIOEngine() class Tree(Model): name: str average_size: float # The following queries are equivalent, # they will sort `Tree` by descending `average_size` await engine.find(Tree, sort=Tree.average_size.desc()) await engine.find(Tree, sort=query.desc(Tree.average_size))
async def get_top(limit: int = 10): result = await engine.find(Graph, sort=desc(Graph.profit), limit=limit) return result
async def get_all(skip: int = 0, limit: Optional[int] = None): result = await engine.find(Graph, sort=desc(Graph.timestamp), skip=skip, limit=limit) return result
from odmantic import AIOEngine, EmbeddedModel, Model from odmantic.query import desc class CapitalCity(EmbeddedModel): name: str population: int class Country(Model): name: str currency: str capital_city: CapitalCity engine = AIOEngine() await engine.find(Country, sort=desc(Country.capital_city.population))
def desc(self) -> SortExpression: return desc(self)