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.
65 lines
2.7 KiB
65 lines
2.7 KiB
from rest_framework import serializers
|
|
from apps.course.models import Lesson, CourseLesson, Participant, LessonCompletion
|
|
from apps.quiz.serializers import QuizListSerializer
|
|
|
|
|
|
class LessonSerializer(serializers.ModelSerializer):
|
|
class Meta:
|
|
model = Lesson
|
|
fields = ['id', 'title', 'content_type', 'content_file', 'video_link', 'duration']
|
|
|
|
|
|
class CourseLessonSerializer(serializers.ModelSerializer):
|
|
is_complated = serializers.SerializerMethodField()
|
|
quizs = serializers.SerializerMethodField()
|
|
permission = serializers.SerializerMethodField()
|
|
content_type = serializers.CharField(source='lesson.content_type', read_only=True)
|
|
content_file = serializers.FileField(source='lesson.content_file', read_only=True)
|
|
video_link = serializers.CharField(source='lesson.video_link', read_only=True)
|
|
duration = serializers.IntegerField(source='lesson.duration', read_only=True)
|
|
|
|
class Meta:
|
|
model = CourseLesson
|
|
fields = ['id', 'title', 'priority', 'is_active', 'permission', 'duration', 'content_type', 'content_file', 'video_link', 'is_complated', 'quizs']
|
|
|
|
def get_permission(self, obj):
|
|
if student := self._get_authenticated_user():
|
|
if not self._is_participant(student, obj.course):
|
|
return False
|
|
return True
|
|
return False
|
|
|
|
def _get_authenticated_user(self):
|
|
"""Helper method to retrieve the authenticated user from the context."""
|
|
request = self.context.get('request')
|
|
return request.user if request and request.user.is_authenticated else None
|
|
|
|
def _is_participant(self, student, course):
|
|
"""Helper method to check if a student is a participant in the given course."""
|
|
return Participant.objects.filter(student=student, course=course).exists()
|
|
|
|
def get_is_complated(self, obj):
|
|
request = self.context.get('request')
|
|
if not request or not request.user.is_authenticated:
|
|
return False
|
|
user = request.user
|
|
is_participant = Participant.objects.filter(
|
|
student=user,
|
|
course=obj.course
|
|
).exists()
|
|
|
|
if not is_participant:
|
|
return False
|
|
|
|
return LessonCompletion.objects.filter(
|
|
student=user,
|
|
course_lesson=obj
|
|
).exists()
|
|
|
|
def get_quizs(self, obj):
|
|
# Assuming the related_name for quizzes is now on CourseLesson
|
|
# print(f'--> type:{type(obj)} obj:{obj.lesson.quizzes.all()}')
|
|
quizzes = obj.lesson.quizzes.all() if hasattr(obj.lesson, 'quizzes') else []
|
|
if quizzes:
|
|
return QuizListSerializer(quizzes, many=True, context=self.context).data
|
|
return None
|