Files
InsightRadar/backend/app/crud/crud_source.py
T
2026-03-11 01:33:21 +08:00

41 lines
1.2 KiB
Python

# app/crud/crud_source.py
from sqlalchemy.orm import Session
from typing import List, Optional
from app.models.models import InfoSource
from app.schemas.source_schema import InfoSourceCreate, InfoSourceUpdate
def get(db: Session, source_id: int) -> Optional[InfoSource]:
"""通过 ID 获取单条信息源"""
return db.query(InfoSource).filter(InfoSource.id == source_id).first()
def get_multi(db: Session, skip: int = 0, limit: int = 100) -> List[InfoSource]:
"""获取所有信息源列表(支持分页)"""
return db.query(InfoSource).offset(skip).limit(limit).all()
def create(db: Session, obj_in: InfoSourceCreate) -> InfoSource:
"""创建新的信息源"""
db_obj = InfoSource(**obj_in.model_dump())
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def update(db: Session, db_obj: InfoSource, obj_in: InfoSourceUpdate) -> InfoSource:
"""更新信息源"""
# 提取前端真正要求更新的字段
update_data = obj_in.model_dump(exclude_unset=True)
# 遍历更新模型对象的属性
for field, value in update_data.items():
setattr(db_obj, field, value)
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj