sqlalchemy dynamic filtering

前端 未结 4 900
花落未央
花落未央 2020-12-16 00:49

I\'m trying to implement dynamic filtering using SQLAlchemy ORM.

I was looking through StackOverflow and found very similar question:SQLALchemy dynamic filter_by

4条回答
  •  情书的邮戳
    2020-12-16 01:18

    For the people using FastAPI and SQLAlchemy, here is a example of dynamic filtering:

    api/app/app/crud/order.py

    from typing import Optional
    
    from pydantic import UUID4
    from sqlalchemy.orm import Session
    
    from app.crud.base import CRUDBase
    from app.models.order import Order
    from app.schemas.order import OrderCreate, OrderUpdate
    
    
    class CRUDOrder(CRUDBase[Order, OrderCreate, OrderUpdate]):
    
        def get_orders(
            self,
            db: Session,
            owner_id: UUID4,
            status: str,
            trading_type: str,
            pair: str,
            skip: int = 0,
            limit: int = 100,
        ) -> Optional[Order]:
            filters = {
                arg: value
                for arg, value in locals().items()
                if arg != "self" and arg != "db" and arg != "skip" and arg != "limit" and value is not None
            }
            query = db.query(self.model)
            for attr, value in filters.items():
                query = query.filter(getattr(self.model, attr) == value)
            return (
                query
                .offset(skip)
                .limit(limit)
                .all()
            )
    
    
    order = CRUDOrder(Order)
    
    

提交回复
热议问题