
- Add Priority enum (low, medium, high) to Todo model with default medium - Create migration to add priority field to existing todos table - Enhance pagination with proper metadata (page, total, has_next, has_prev) - Add search functionality across title and description fields - Add filtering by completion status and priority level - Update API endpoints with query parameters for filtering and search - Add TodoListResponse schema for structured pagination response - Format code with Ruff
67 lines
1.8 KiB
Python
67 lines
1.8 KiB
Python
from typing import List, Optional, Tuple
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models.todo import Todo, Priority
|
|
from app.schemas.todo import TodoCreate, TodoUpdate
|
|
|
|
|
|
def get_todo(db: Session, todo_id: int) -> Optional[Todo]:
|
|
return db.query(Todo).filter(Todo.id == todo_id).first()
|
|
|
|
|
|
def get_todos(
|
|
db: Session,
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
completed: Optional[bool] = None,
|
|
priority: Optional[Priority] = None,
|
|
search: Optional[str] = None,
|
|
) -> Tuple[List[Todo], int]:
|
|
query = db.query(Todo)
|
|
|
|
# Apply filters
|
|
if completed is not None:
|
|
query = query.filter(Todo.completed == completed)
|
|
if priority is not None:
|
|
query = query.filter(Todo.priority == priority)
|
|
if search:
|
|
query = query.filter(
|
|
Todo.title.contains(search) | Todo.description.contains(search)
|
|
)
|
|
|
|
# Get total count before pagination
|
|
total = query.count()
|
|
|
|
# Apply pagination and ordering
|
|
todos = query.order_by(Todo.created_at.desc()).offset(skip).limit(limit).all()
|
|
|
|
return todos, total
|
|
|
|
|
|
def create_todo(db: Session, todo: TodoCreate) -> Todo:
|
|
db_todo = Todo(**todo.model_dump())
|
|
db.add(db_todo)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
def update_todo(db: Session, todo_id: int, todo_update: TodoUpdate) -> Optional[Todo]:
|
|
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
if db_todo:
|
|
update_data = todo_update.model_dump(exclude_unset=True)
|
|
for field, value in update_data.items():
|
|
setattr(db_todo, field, value)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
def delete_todo(db: Session, todo_id: int) -> bool:
|
|
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
if db_todo:
|
|
db.delete(db_todo)
|
|
db.commit()
|
|
return True
|
|
return False
|