|
12 | 12 |
|
13 | 13 | @router.get("/", response_model=ItemsPublic) |
14 | 14 | def read_items( |
15 | | - session: SessionDep, current_user: CurrentUser, skip: int = 0, limit: int = 100 |
| 15 | + session: SessionDep, |
| 16 | + current_user: CurrentUser, |
| 17 | + skip: int = 0, |
| 18 | + limit: int = 100, |
| 19 | + category: str | None = None |
16 | 20 | ) -> Any: |
17 | 21 | """ |
18 | 22 | Retrieve items. |
19 | 23 | """ |
20 | | - |
| 24 | + |
| 25 | + # Base query |
21 | 26 | if current_user.is_superuser: |
22 | | - count_statement = select(func.count()).select_from(Item) |
23 | | - count = session.exec(count_statement).one() |
24 | | - statement = select(Item).offset(skip).limit(limit) |
25 | | - items = session.exec(statement).all() |
| 27 | + query = select(Item) |
| 28 | + count_query = select(func.count()).select_from(Item) |
26 | 29 | else: |
27 | | - count_statement = ( |
28 | | - select(func.count()) |
29 | | - .select_from(Item) |
30 | | - .where(Item.owner_id == current_user.id) |
31 | | - ) |
32 | | - count = session.exec(count_statement).one() |
33 | | - statement = ( |
34 | | - select(Item) |
35 | | - .where(Item.owner_id == current_user.id) |
36 | | - .offset(skip) |
37 | | - .limit(limit) |
38 | | - ) |
39 | | - items = session.exec(statement).all() |
| 30 | + query = select(Item).where(Item.owner_id == current_user.id) |
| 31 | + count_query = select(func.count()).select_from(Item).where(Item.owner_id == current_user.id) |
| 32 | + |
| 33 | + # Apply category filter if provided |
| 34 | + if category: |
| 35 | + query = query.where(Item.category == category) |
| 36 | + count_query = count_query.where(Item.category == category) |
| 37 | + |
| 38 | + # Apply pagination |
| 39 | + query = query.offset(skip).limit(limit) |
| 40 | + |
| 41 | + # Execute queries |
| 42 | + count = session.exec(count_query).one() |
| 43 | + items = session.exec(query).all() |
40 | 44 |
|
41 | 45 | return ItemsPublic(data=items, count=count) |
42 | 46 |
|
43 | 47 |
|
| 48 | +@router.get("/categories", response_model=list[str]) |
| 49 | +def get_item_categories( |
| 50 | + session: SessionDep, current_user: CurrentUser |
| 51 | +) -> Any: |
| 52 | + """ |
| 53 | + Get all unique item categories. |
| 54 | + """ |
| 55 | + if current_user.is_superuser: |
| 56 | + statement = select(Item.category).distinct() |
| 57 | + else: |
| 58 | + statement = select(Item.category).where( |
| 59 | + Item.owner_id == current_user.id |
| 60 | + ).distinct() |
| 61 | + |
| 62 | + categories = session.exec(statement).all() |
| 63 | + # Filter out None values and return unique non-empty categories |
| 64 | + return [cat for cat in categories if cat] |
| 65 | + |
| 66 | + |
44 | 67 | @router.get("/{id}", response_model=ItemPublic) |
45 | 68 | def read_item(session: SessionDep, current_user: CurrentUser, id: uuid.UUID) -> Any: |
46 | 69 | """ |
|
0 commit comments