Сериализаторы:
class AnswerSerializer(serializers.ModelSerializer):
class Meta:
model = QuestionAnswer
exclude = ('question', )
class QuestionSerializer(serializers.ModelSerializer):
answers = AnswerSerializer(many=True, read_only=True)
class Meta:
model = Question
exclude = ('quiz', )
class QuizSerializer(CommonContentDataModelSerializer):
questions = QuestionSerializer(many=True, read_only=True)
class Meta:
model = Quiz
fields = '__all__'
Методы, которые выдают данные, get_model_name и get_content_model_name выдают одно и тоже:
CONTENT_SERIALIZERS = {
get_model_name(QuizSerializer): QuizSerializer,
get_model_name(VideoContentSerializer): VideoContentSerializer,
get_model_name(PDFContentSerializer): PDFContentSerializer,
get_model_name(WebResourceContentSerializer): WebResourceContentSerializer,
get_model_name(SCORMPackageSerializer): SCORMPackageSerializer,
}
@staticmethod
def serialize_content_object(content_obj):
"""Сериализует материал учебной программы"""
model_name = get_content_model_name(content_obj)
return CONTENT_SERIALIZERS[model_name](instance=content_obj).data
def get_serialized_content_object(self):
"""Получаем сериализованные материалы учебной программы"""
content_obj = self.get_content_object_by_content_type()
data = self.serialize_content_object(content_obj)
return data
Результат без вопросов опросника:
{
"id": 19,
"content_type": "quiz | Опрос",
"ed_program": "new",
"name": "test-quiz",
"description": null,
"time_create": "2022-09-30T09:56:35.091519+03:00",
"time_update": "2022-09-30T10:07:10.505290+03:00",
"deadline": null,
"available_questions": 25,
"show_answers": false
}
Нужно типо такого, как в доке
https://www.django-rest-framework.org/api-guide/re...:
{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
{'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
{'order': 2, 'title': 'What More Can I Say', 'duration': 264},
{'order': 3, 'title': 'Encore', 'duration': 159},
...
],
}