serializers.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # coding=utf-8
  2. from rest_framework import serializers
  3. from .models import *
  4. class PractiseLogSerializer(serializers.ModelSerializer):
  5. begin_answer = serializers.SerializerMethodField()
  6. end_answer = serializers.SerializerMethodField()
  7. next_practise = serializers.SerializerMethodField()
  8. def get_next_practise(self, obj):
  9. # 继续练习的下一题id
  10. next_practise = ''
  11. if obj.end_answer:
  12. now_type = obj.end_answer.question.type
  13. questions = ExamQuestion.objects.filter(type=now_type).order_by('id').values_list('id', flat=True)
  14. now_question_index = list(questions).index(obj.end_answer.question.id)
  15. if now_question_index < (len(questions) -1):
  16. # 该题型未练习完,继续返回该题型下的习题
  17. next_practise = questions[now_question_index + 1]
  18. else:
  19. # 该题型已练习完,返回下一个题型下的习题
  20. while now_type <= ExamQuestion.JUDGMENT:
  21. now_type += 1
  22. questions = ExamQuestion.objects.filter(type=now_type).order_by('id').first()
  23. if questions:
  24. next_practise = questions.id
  25. break
  26. return next_practise
  27. def get_end_answer(self, obj):
  28. if obj.end_answer:
  29. now_type = obj.end_answer.question.type
  30. questions = ExamQuestion.objects.filter(type=now_type).order_by('id').values_list('id', flat=True)
  31. now_question_index = list(questions).index(obj.end_answer.question.id)
  32. name = '{0}/{1} {2}第{3}题'.format(obj.end_answer.question.chapter.name,
  33. obj.end_answer.question.chapter.subject.name,
  34. ExamQuestion.TYPE_CHOICES[obj.end_answer.question.type - 1][1],
  35. now_question_index + 1
  36. )
  37. return name
  38. return ''
  39. def get_begin_answer(self, obj):
  40. if obj.begin_answer:
  41. now_type = obj.begin_answer.question.type
  42. questions = ExamQuestion.objects.filter(type=now_type).order_by('id').values_list('id', flat=True)
  43. now_question_index = list(questions).index(obj.begin_answer.question.id)
  44. name = '{0}/{1} {2}第{3}题'.format(obj.begin_answer.question.chapter.name,
  45. obj.begin_answer.question.chapter.subject.name,
  46. ExamQuestion.TYPE_CHOICES[obj.begin_answer.question.type - 1][1],
  47. now_question_index + 1
  48. )
  49. return name
  50. return ''
  51. class Meta:
  52. model = PractiseLog
  53. fields = '__all__'