async def test_and(engine: AIOEngine): query = (PersonModel.first_name == "Michel") & (PersonModel.last_name == "Drucker") assert query == and_(PersonModel.first_name == "Michel", PersonModel.last_name == "Drucker") count = await engine.count(PersonModel, query) assert count == 1
def _build_query(*queries: Union[QueryExpression, Dict, bool]) -> QueryExpression: if len(queries) == 0: return QueryExpression() for query in queries: if isinstance(query, bool): raise TypeError("cannot build query using booleans") queries = cast(Tuple[Union[QueryExpression, Dict], ...], queries) if len(queries) == 1: return QueryExpression(queries[0]) return and_(*queries)
async def search( client: AsyncIOMotorClient = Depends(get_odm), dlc: YesNo = None, now_playing: YesNo = None, game_status: GameStatus = None, q: str = None, ): engine = AIOEngine(motor_client=client, database="backlogs") initial_args = { 'dlc': dlc, 'now_playing': now_playing, 'game_status': game_status, } final_args = {k: v for k, v in initial_args.items() if v is not None} if final_args: query_expression_list = [(getattr(BacklogGame, key)) == value for key, value in final_args.items()] combined_query_expression = query.and_(*query_expression_list) else: combined_query_expression = False # change to plain q for OR results. f"\"{q}\"" is an AND search. if combined_query_expression: results = await engine.find( BacklogGame, combined_query_expression, sort=(BacklogGame.dlc, BacklogGame.id), ) elif q == '' or q is None: results = await engine.find( BacklogGame, sort=(BacklogGame.dlc, BacklogGame.id), ) else: results = await engine.find( BacklogGame, {'$text': { '$search': f"\"{q}\"" }}, sort=(BacklogGame.dlc, BacklogGame.id), ) return results
from odmantic import Model, query class Tree(Model): name: str size: float (Tree.name == "Spruce") & (Tree.size <= 2) #> QueryExpression( #> { #> "$and": ( #> QueryExpression({"name": {"$eq": "Spruce"}}), #> QueryExpression({"size": {"$lte": 2}}), #> ) #> } #> ) query.and_(Tree.name == "Spruce", Tree.size <= 2) #> ... same output ...