61 lines
1.6 KiB
Python
61 lines
1.6 KiB
Python
from typing import Any, Dict, List, Optional, Union
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models.product import Product
|
|
from app.schemas.product import ProductCreate, ProductUpdate
|
|
|
|
|
|
def get(db: Session, product_id: int) -> Optional[Product]:
|
|
return db.query(Product).filter(Product.id == product_id).first()
|
|
|
|
|
|
def get_by_sku(db: Session, sku: str) -> Optional[Product]:
|
|
return db.query(Product).filter(Product.sku == sku).first()
|
|
|
|
|
|
def get_multi(
|
|
db: Session, *, skip: int = 0, limit: int = 100, active_only: bool = False
|
|
) -> List[Product]:
|
|
query = db.query(Product)
|
|
if active_only:
|
|
query = query.filter(Product.is_active == True)
|
|
return query.offset(skip).limit(limit).all()
|
|
|
|
|
|
def create(db: Session, *, obj_in: ProductCreate) -> Product:
|
|
db_obj = Product(
|
|
name=obj_in.name,
|
|
sku=obj_in.sku,
|
|
description=obj_in.description,
|
|
weight=obj_in.weight,
|
|
dimensions=obj_in.dimensions,
|
|
price=obj_in.price,
|
|
is_active=obj_in.is_active,
|
|
)
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
|
|
def update(
|
|
db: Session, *, db_obj: Product, obj_in: Union[ProductUpdate, Dict[str, Any]]
|
|
) -> Product:
|
|
if isinstance(obj_in, dict):
|
|
update_data = obj_in
|
|
else:
|
|
update_data = obj_in.dict(exclude_unset=True)
|
|
for field in update_data:
|
|
setattr(db_obj, field, update_data[field])
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
|
|
def remove(db: Session, *, product_id: int) -> Product:
|
|
obj = db.query(Product).get(product_id)
|
|
db.delete(obj)
|
|
db.commit()
|
|
return obj |