basic.py 703 B

12345678910111213141516171819202122
  1. from typing import Type
  2. from sqlalchemy.orm import Session
  3. import time
  4. from sqlalchemy.orm.attributes import flag_modified
  5. from app.models import BaseModel
  6. def update_to_db(db: Session, item_id: int, update_item, model_cls: Type[BaseModel]):
  7. db_item = db.query(model_cls).filter(model_cls.id == item_id).first()
  8. if not db_item:
  9. raise Exception('未找到该任务')
  10. update_dict = update_item.dict(exclude_unset=True)
  11. for k, v in update_dict.items():
  12. setattr(db_item, k, v)
  13. flag_modified(db_item, k)
  14. if hasattr(db_item, "update_time"):
  15. db_item.update_time = int(time.time())
  16. db.commit()
  17. db.flush()
  18. db.refresh(db_item)
  19. return db_item