history.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. from pydantic import BaseModel
  2. from typing import Optional
  3. from datetime import datetime
  4. from enum import Enum
  5. class GameTypeEnum(str, Enum):
  6. """题目类型枚举,限制为A-E"""
  7. TYPE_A = "A"
  8. TYPE_B = "B"
  9. TYPE_C = "C"
  10. TYPE_D = "D"
  11. TYPE_E = "E"
  12. class History(BaseModel):
  13. """历史记录数据模型
  14. 用于规范历史记录的数据结构,确保数据的一致性和有效性
  15. """
  16. id: Optional[int] = None
  17. game_type: GameTypeEnum
  18. question: str
  19. numbers: str
  20. answers: str
  21. created_at: Optional[datetime] = None
  22. is_favorite: bool = False
  23. is_deleted: bool = False
  24. class Config:
  25. json_encoders = {
  26. datetime: lambda v: v.isoformat()
  27. }
  28. @classmethod
  29. def from_db_record(cls, record: dict):
  30. """从数据库记录创建模型对象"""
  31. return cls(**record)
  32. def to_db_record(self):
  33. """转换为数据库记录格式"""
  34. record = self.model_dump(exclude={'id', 'created_at'} if self.id is None else {'created_at'})
  35. # 确保game_type是字符串值
  36. if isinstance(record['game_type'], GameTypeEnum):
  37. record['game_type'] = record['game_type'].value
  38. return record