You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
45 lines
1.4 KiB
45 lines
1.4 KiB
from rest_framework import serializers
|
|
|
|
from apps.quiz.models import QuizParticipant, ParticipantAnswer
|
|
|
|
|
|
class ParticipantAnswerSerializer(serializers.ModelSerializer):
|
|
class Meta:
|
|
model = ParticipantAnswer
|
|
fields = ['question', 'option_num', 'at_time', 'answer_timing']
|
|
|
|
|
|
|
|
class QuizParticipantSerializer(serializers.ModelSerializer):
|
|
user = serializers.HiddenField(default=serializers.CurrentUserDefault())
|
|
answers = ParticipantAnswerSerializer(many=True)
|
|
|
|
def validate_quiz(self, obj):
|
|
if QuizParticipant.objects.filter(quiz=obj, user=self.context['request'].user).exists():
|
|
raise serializers.ValidationError('you have already participated in the quiz')
|
|
|
|
return obj
|
|
|
|
class Meta:
|
|
model = QuizParticipant
|
|
fields = [
|
|
'quiz', 'user', 'started_at', 'ended_at', 'total_timing',
|
|
'question_score', 'timing_score', 'total_score',
|
|
'answers',
|
|
]
|
|
|
|
def create(self, validated_data):
|
|
answers = validated_data.pop('answers', [])
|
|
obj = super().create(validated_data)
|
|
answers_objs = []
|
|
for ans in answers:
|
|
answers_objs.append(
|
|
ParticipantAnswer(
|
|
participant=obj,
|
|
**ans,
|
|
)
|
|
)
|
|
|
|
ParticipantAnswer.objects.bulk_create(answers_objs)
|
|
|
|
return obj
|