PamGram/core/quiz/models.py

93 lines
2.8 KiB
Python
Raw Normal View History

2022-07-26 10:07:31 +00:00
from typing import List, Optional
from sqlmodel import SQLModel, Field
from models.baseobject import BaseObject
from models.types import JSONDict
2022-07-26 10:07:31 +00:00
class AnswerDB(SQLModel, table=True):
__tablename__ = 'answer'
id: Optional[int] = Field(default=None, primary_key=True)
question_id: Optional[int] = Field()
is_correct: Optional[bool] = Field()
text: Optional[str] = Field()
class QuestionDB(SQLModel, table=True):
__tablename__ = 'question'
id: Optional[int] = Field(default=None, primary_key=True)
text: Optional[str] = Field()
2022-07-26 10:07:31 +00:00
class Answer(BaseObject):
def __init__(self, answer_id: int = 0, question_id: int = 0, is_correct: bool = True, text: str = ""):
"""Answer类
:param answer_id: 答案ID
:param question_id: 与之对应的问题ID
:param is_correct: 该答案是否正确
:param text: 答案文本
"""
self.answer_id = answer_id
self.question_id = question_id
self.text = text
self.is_correct = is_correct
__slots__ = ("answer_id", "question_id", "text", "is_correct")
2022-08-23 09:17:54 +00:00
def to_database_data(self) -> AnswerDB:
data = AnswerDB()
data.id = self.answer_id
data.question_id = self.question_id
data.text = self.text
data.is_correct = self.is_correct
return data
@classmethod
def de_database_data(cls, data: Optional[AnswerDB]) -> Optional["Answer"]:
if data is None:
return cls()
return cls(answer_id=data.id, question_id=data.question_id, text=data.text, is_correct=data.is_correct)
2022-07-26 10:07:31 +00:00
class Question(BaseObject):
def __init__(self, question_id: int = 0, text: str = "", answers: List[Answer] = None):
"""Question类
:param question_id: 问题ID
:param text: 问题文本
:param answers: 答案列表
"""
self.question_id = question_id
self.text = text
self.answers = [] if answers is None else answers
2022-08-23 09:17:54 +00:00
def to_database_data(self) -> QuestionDB:
data = QuestionDB()
data.text = self.text
data.id = self.question_id
return data
@classmethod
def de_database_data(cls, data: Optional[QuestionDB]) -> Optional["Question"]:
if data is None:
return cls()
return cls(question_id=data.id, text=data.text)
2022-07-26 10:07:31 +00:00
def to_dict(self) -> JSONDict:
data = super().to_dict()
if self.answers:
data["answers"] = [e.to_dict() for e in self.answers]
2022-07-26 10:07:31 +00:00
return data
@classmethod
def de_json(cls, data: Optional[JSONDict]) -> Optional["Question"]:
data = cls._parse_data(data)
if not data:
return None
data["answers"] = Answer.de_list(data.get("answers"))
2022-07-26 10:07:31 +00:00
return cls(**data)
__slots__ = ("question_id", "text", "answers")