serializers.py 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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, delete=False).order_by('id').values_list('id', flat=True)
  14. if obj.chapter:
  15. questions = questions.filter(chapter=obj.chapter)
  16. else:
  17. questions = questions.filter(chapter__subject=obj.subject)
  18. now_question_index = list(questions).index(obj.end_answer.question.id)
  19. if now_question_index < (len(questions) -1):
  20. # 该题型未练习完,继续返回该题型下的习题
  21. next_practise = questions[now_question_index + 1]
  22. else:
  23. # 该题型已练习完,返回下一个题型下的习题
  24. while now_type <= ExamQuestion.JUDGMENT:
  25. now_type += 1
  26. questions = ExamQuestion.objects.filter(type=now_type, delete=False).order_by('id').first()
  27. if obj.chapter:
  28. questions = questions.filter(chapter=obj.chapter)
  29. else:
  30. questions = questions.filter(chapter__subject=obj.subject)
  31. if questions:
  32. next_practise = questions.id
  33. break
  34. return next_practise
  35. def get_end_answer(self, obj):
  36. if obj.end_answer:
  37. now_type = obj.end_answer.question.type
  38. # todo 按id查
  39. questions = ExamQuestion.objects.filter(type=now_type, delete=False).order_by('id').values_list('id', flat=True)
  40. now_question_index = list(questions).index(obj.end_answer.question.id)
  41. name = '{0}/{1} {2}第{3}题'.format(obj.end_answer.question.chapter.name,
  42. obj.end_answer.question.chapter.subject.name,
  43. ExamQuestion.TYPE_CHOICES[obj.end_answer.question.type - 1][1],
  44. now_question_index + 1
  45. )
  46. return name
  47. return ''
  48. def get_begin_answer(self, obj):
  49. if obj.begin_answer:
  50. now_type = obj.begin_answer.question.type
  51. questions = ExamQuestion.objects.filter(type=now_type, delete=False).order_by('id').values_list('id', flat=True)
  52. now_question_index = list(questions).index(obj.begin_answer.question.id)
  53. name = '{0}/{1} {2}第{3}题'.format(obj.begin_answer.question.chapter.name,
  54. obj.begin_answer.question.chapter.subject.name,
  55. ExamQuestion.TYPE_CHOICES[obj.begin_answer.question.type - 1][1],
  56. now_question_index + 1
  57. )
  58. return name
  59. return ''
  60. class Meta:
  61. model = PractiseLog
  62. fields = '__all__'