serializers.py 2.45 KB
Newer Older
1 2
from rest_framework import serializers

3
from baquara.users.serializers import SimpleUserSerializer, TimtecUserAdminCertificateSerializer
4 5 6 7

from courses.models import CourseStudent
from courses.serializers import BasicCourseSerializer
from courses.workspaces.serializers import WorkspaceBaseSerializerMixin
8
from courses.certification.serializers import (
9 10 11 12 13 14 15 16 17 18
    CourseCertificationSerializer,
    CertificationProcessSerializer,
    EvaluationSerializer,
)

from .models import Class


class BasicClassSerializer(serializers.ModelSerializer):

19 20
    assistants = SimpleUserSerializer(read_only=True, many=True)

21 22
    class Meta:
        model = Class
23
        fields = ('id', 'name', 'assistants', 'students')
24 25 26 27 28 29 30 31 32 33 34 35 36


class CourseStudentClassSerializer(serializers.ModelSerializer):

    user = TimtecUserAdminCertificateSerializer(read_only=True)

    class Meta:
        model = CourseStudent
        fields = ('id', 'user', 'course_finished',
                  'certificate', 'can_emmit_receipt', 'percent_progress',)


class ClassSerializer(WorkspaceBaseSerializerMixin, serializers.ModelSerializer):
37 38
    enrolled_students = CourseStudentClassSerializer(source='get_students', many=True, read_only=True)
    students_details = SimpleUserSerializer(source='students', many=True, read_only=True)
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
    processes = CertificationProcessSerializer(read_only=True, many=True)
    evaluations = EvaluationSerializer(read_only=True, many=True)
    course = BasicCourseSerializer(read_only=True)
    assistants = SimpleUserSerializer(read_only=True, many=True)

    class Meta:
        model = Class
        fields = "__all__"

    def update(self, instance, validated_data, **kwargs):
        assistants = self.context['request'].data.get('assistants', None)
        updated_class = super(ClassSerializer, self).update(instance, validated_data)
        # If there are assistans to be associated with the class, do it now
        updated_class.assistants.clear()
        for assistant in assistants:
            updated_class.assistants.add(assistant['id'])

        contract = self.context['request'].data.get('contract', None)
        if contract:
            current = updated_class.contract.first()
            if not current or (contract['id'] != current.id):
                c = Workspace.objects.get(pk=contract['id'])
                updated_class.contract.clear()
                updated_class.contract.add(c)
        else:
            updated_class.contract.clear()
        updated_class.save()

        return updated_class