Spaces:
Sleeping
Sleeping
| from rest_framework import serializers | |
| from .models import Skill, UserSkill | |
| from .utils import proficiency_to_level | |
| class SkillSerializer(serializers.ModelSerializer): | |
| class Meta: | |
| model = Skill | |
| fields = ['id', 'skill_name', 'category', 'description', 'difficulty_level'] | |
| class UserSkillSerializer(serializers.ModelSerializer): | |
| skill = SkillSerializer(read_only=True) | |
| class Meta: | |
| model = UserSkill | |
| fields = ['id', 'skill', 'proficiency', 'user_level', 'updated_at'] | |
| class UserSkillCreateUpdateSerializer(serializers.Serializer): | |
| skill_id = serializers.IntegerField() | |
| proficiency = serializers.IntegerField() | |
| def validate_proficiency(self, value): | |
| if not 0 <= value <= 100: | |
| raise serializers.ValidationError("Proficiency must be between 0 and 100.") | |
| return value | |
| def validate_skill_id(self, value): | |
| if not Skill.objects.filter(id=value).exists(): | |
| raise serializers.ValidationError("Skill with this ID does not exist.") | |
| return value | |
| def create(self, validated_data): | |
| skill_id = validated_data['skill_id'] | |
| proficiency = validated_data['proficiency'] | |
| user = self.context['request'].user | |
| user_level = proficiency_to_level(proficiency) | |
| user_skill, _ = UserSkill.objects.update_or_create( | |
| user=user, | |
| skill_id=skill_id, | |
| defaults={'proficiency': proficiency, 'user_level': user_level} | |
| ) | |
| return user_skill | |
| def update(self, instance, validated_data): | |
| # skill_id is immutable on update — a UserSkill binds a user to a | |
| # specific skill; reassigning it would corrupt that identity. | |
| proficiency = validated_data.get('proficiency', instance.proficiency) | |
| instance.proficiency = proficiency | |
| instance.user_level = proficiency_to_level(proficiency) | |
| instance.save() | |
| return instance | |