| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- from pydantic import BaseModel
- from typing import Optional
- from datetime import datetime
- from enum import Enum
- class GameTypeEnum(str, Enum):
- """题目类型枚举,限制为A-E"""
- TYPE_A = "A"
- TYPE_B = "B"
- TYPE_C = "C"
- TYPE_D = "D"
- TYPE_E = "E"
- class History(BaseModel):
- """历史记录数据模型
-
- 用于规范历史记录的数据结构,确保数据的一致性和有效性
- """
- id: Optional[int] = None
- game_type: GameTypeEnum
- question: str
- numbers: str
- answers: str
- created_at: Optional[datetime] = None
- is_favorite: bool = False
- is_deleted: bool = False
-
- class Config:
- json_encoders = {
- datetime: lambda v: v.isoformat()
- }
-
- @classmethod
- def from_db_record(cls, record: dict):
- """从数据库记录创建模型对象"""
- return cls(**record)
-
- def to_db_record(self):
- """转换为数据库记录格式"""
- record = self.model_dump(exclude={'id', 'created_at'} if self.id is None else {'created_at'})
- # 确保game_type是字符串值
- if isinstance(record['game_type'], GameTypeEnum):
- record['game_type'] = record['game_type'].value
- return record
|