# coding=utf-8 from rest_framework import serializers from .models import * class PractiseLogSerializer(serializers.ModelSerializer): begin_answer = serializers.SerializerMethodField() end_answer = serializers.SerializerMethodField() next_practise = serializers.SerializerMethodField() def get_next_practise(self, obj): # 继续练习的下一题id next_practise = '' if obj.end_answer: now_type = obj.end_answer.question.type questions = ExamQuestion.objects.filter(type=now_type, delete=False).order_by('id').values_list('id', flat=True) now_question_index = list(questions).index(obj.end_answer.question.id) if now_question_index < (len(questions) -1): # 该题型未练习完,继续返回该题型下的习题 next_practise = questions[now_question_index + 1] else: # 该题型已练习完,返回下一个题型下的习题 while now_type <= ExamQuestion.JUDGMENT: now_type += 1 questions = ExamQuestion.objects.filter(type=now_type, delete=False).order_by('id').first() if questions: next_practise = questions.id break return next_practise def get_end_answer(self, obj): if obj.end_answer: now_type = obj.end_answer.question.type # todo questions = ExamQuestion.objects.filter(type=now_type, delete=False).order_by('id').values_list('id', flat=True) now_question_index = list(questions).index(obj.end_answer.question.id) name = '{0}/{1} {2}第{3}题'.format(obj.end_answer.question.chapter.name, obj.end_answer.question.chapter.subject.name, ExamQuestion.TYPE_CHOICES[obj.end_answer.question.type - 1][1], now_question_index + 1 ) return name return '' def get_begin_answer(self, obj): if obj.begin_answer: now_type = obj.begin_answer.question.type questions = ExamQuestion.objects.filter(type=now_type, delete=False).order_by('id').values_list('id', flat=True) now_question_index = list(questions).index(obj.begin_answer.question.id) name = '{0}/{1} {2}第{3}题'.format(obj.begin_answer.question.chapter.name, obj.begin_answer.question.chapter.subject.name, ExamQuestion.TYPE_CHOICES[obj.begin_answer.question.type - 1][1], now_question_index + 1 ) return name return '' class Meta: model = PractiseLog fields = '__all__'