import functools from rest_framework import serializers from users.models import CustomUser from .models import Room, Parcours class RoomSerializer(serializers.ModelSerializer): exo_model = '' class Meta: model = Room fields = ('id', 'name', 'id_code', 'anonymousMembers', 'private', 'public_result') class CreateRoomSerializer(serializers.ModelSerializer): exo_model = '' nick = serializers.SerializerMethodField() class Meta: model = Room fields = ( 'name', 'anonymousMembers', 'private', "public_result", 'nick') def validate_nick(self, value): if value != '': if len(value) > 30: raise serializers.ValidationError('Trop long') return value raise serializers.ValidationError(code='blank') def get_nick(self, obj): return '' class RoomUserSerializer(serializers.ModelSerializer): status = serializers.SerializerMethodField() class Meta: model = Room fields = ('id', 'name', 'id_code', 'status') def get_status(self, obj): try: user = CustomUser.objects.get( id_code=self.context['userId']) return 'administrateur' if user.id_code == obj.owner['code'] else 'membre' except: return None class ParcoursFullSerializer(serializers.ModelSerializer): is_validate = serializers.SerializerMethodField() challenger = serializers.SerializerMethodField() class Meta: model = Parcours fields = ('id', 'name', 'id_code', 'timer', 'exercices', 'success_condition', 'is_validate', 'challenger') # + challenger ? def get_is_validate(self, obj): clientId = self.context.get('clientId', None) if clientId != None: challenger = [ p for p in obj.challenger if p['clientId'] == clientId] if len(challenger) == 0: return False else: return challenger[0]['validate'] return None def get_challenger(self, obj): user_code = self.context.get('user_code', None) challengers = obj.challenger if user_code != None: challengers = [c for c in challengers if c['code'] == user_code] if len(challengers) == 0: return [] return [{**c, 'moyenne': Parcours.objects.getAverage(obj.id_code, c['code']), 'exos': [{'endAt': e['endAt'], 'note': e['note'], "code": e['code'], "timer": e['timer'], 'canCorrige': len(e['result']) != 0} for e in c['exos']]} for c in challengers] class ParcoursSerializer(serializers.ModelSerializer): is_validate = serializers.SerializerMethodField() class Meta: model = Parcours fields = ('id', 'name', 'id_code', 'timer', 'exercices', 'success_condition', 'is_validate') # + challenger ? def get_is_validate(self, obj): clientId = self.context.get('clientId', None) if clientId != None: challenger = [ p for p in obj.challenger if p['clientId'] == clientId] if len(challenger) == 0: return False else: return challenger[0]['validate'] return None class ParcoursCreateSerializer(serializers.ModelSerializer): class Meta: model = Parcours fields = ('name', 'room', 'timer', 'exercices', 'success_condition') # + challenger ? def validate_exercices(self, value): print('EXOS', value) if len(value) == 0: raise serializers.ValidationError('Aucun exercice séléctioné') return value