Skip to content
Snippets Groups Projects
Commit c8696ef4 authored by duyanhehe's avatar duyanhehe
Browse files

update search function

parent 8f960b84
No related branches found
No related tags found
No related merge requests found
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from sqlalchemy.orm import joinedload
from sqlmodel import Session, select
from backend.database import get_session
from backend.models.models import Shop, Product, Category
from typing import List, Union
......@@ -18,20 +17,21 @@ def search(
db: Session = Depends(get_session),
):
results = []
if search_type in ["shops", "both"]:
shop_query = db.query(Shop)
shop_query = select(Shop)
if name:
shop_query = shop_query.filter(Shop.name.ilike(f"%{name}%"))
results.extend(shop_query.all())
shop_query = shop_query.where(Shop.name.ilike(f"%{name}%"))
results.extend(db.exec(shop_query).all())
if search_type in ["products", "both"]:
product_query = db.query(Product).options(joinedload(Product.category))
product_query = (
select(Product).join(Category).where(True)
) # Ensures valid syntax
if name:
product_query = product_query.filter(Product.name.ilike(f"%{name}%"))
product_query = product_query.where(Product.name.ilike(f"%{name}%"))
if category:
product_query = product_query.join(Category).filter(
Category.name.ilike(f"%{category}%")
)
results.extend(product_query.all())
product_query = product_query.where(Category.name.ilike(f"%{category}%"))
results.extend(db.exec(product_query).all())
return results
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment