-
Hello (again)! I'm trying to create a quiz app, I'd like to add a key row to my tables with a generated unique UUID. My model is as follows: class Quiz(Model):
class Meta:
tablename = "quiz"
database = config.database
metadata = config.metadata
id: int = Integer(primary_key=True, autoincrement=True)
key: uuid.UUID = UUID(default=uuid.uuid4(), unique=True)
title: str = String(max_length=100, nullable=False)
class Question(Model):
class Meta:
tablename = "question"
database = config.database
metadata = config.metadata
id: int = Integer(primary_key=True, autoincrement=True)
key: uuid.UUID = UUID(default=uuid.uuid4(), unique=True)
question: str = String(max_length=150, nullable=False)
quiz: Quiz = ForeignKey(Quiz)
class Answer(Model):
class Meta:
tablename = "answer"
database = config.database
metadata = config.metadata
id: int = Integer(primary_key=True, autoincrement=True)
key: uuid.UUID = UUID(default=uuid.uuid4(), unique=True)
text: str = String(max_length=100, nullable=False, index=True)
correct: bool = Boolean(nullable=False)
question: Question = ForeignKey(Question) To create the a new Quiz I have the following endpoint: @config.app.post("/quiz/create", response_model=QuizResponseWithId)
async def create_quiz(quiz: Quiz.get_pydantic(exclude={
"id",
"key",
"questions__id",
"questions__key",
"questions__answers__id",
"questions__answers__key"
})):
"""
Creates a new quiz object with its nested questions and answers
:param quiz: Quiz object to create
:return: Newly created quiz with its generated ids
"""
quiz = Quiz(**quiz.dict())
await quiz.save()
await quiz.save_related(follow=True, save_all=True)
return quiz However if I try to create a quiz with two questions and two answers, I get an error because of the unique constraint on Question and Answer (meaning the default param doesn't generate a new UUID for the nested questions and answers, but only generates one). I've tried using a @pre_save([Question, Answer])
async def before_save(sender, instance, **kwargs):
instance.key = uuid.uuid4() However this only works once, as when repeated the same keys will be re-assigned to questions and answers |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You need to pass a callable to default and not the result of the function call. So pass In your code you set it to one UUID (result of uuid4 function evaluated on script start), same for all model instances. This is equivalent of setting default to constant. |
Beta Was this translation helpful? Give feedback.
You need to pass a callable to default and not the result of the function call. So pass
uuis.uuid4
(note there are no parenthesis).In your code you set it to one UUID (result of uuid4 function evaluated on script start), same for all model instances. This is equivalent of setting default to constant.