52 lines
1.9 KiB
Python
52 lines
1.9 KiB
Python
from django.contrib.auth.models import User
|
|
from rest_framework import serializers
|
|
|
|
from .models import Event, EventParticipation
|
|
|
|
|
|
class ParticipationSerializer(serializers.Serializer):
|
|
"""Serializer for EventParticipation that handles username lookup."""
|
|
|
|
event = serializers.PrimaryKeyRelatedField(queryset=Event.objects.all())
|
|
user = serializers.CharField()
|
|
status = serializers.CharField(required=False, default="-")
|
|
comment = serializers.CharField(required=False, allow_blank=True, default="")
|
|
|
|
def to_representation(self, instance):
|
|
"""Serialize an EventParticipation instance."""
|
|
return {
|
|
"event": instance.event.pk,
|
|
"user": instance.user.username,
|
|
"status": instance.status,
|
|
"comment": instance.comment,
|
|
}
|
|
|
|
def validate_user(self, value):
|
|
"""Look up user by username (case-insensitive)."""
|
|
try:
|
|
return User.objects.get(username__iexact=value)
|
|
except User.DoesNotExist:
|
|
raise serializers.ValidationError(f"User '{value}' does not exist")
|
|
|
|
def create(self, validated_data):
|
|
"""Create or update EventParticipation based on event and user."""
|
|
event = validated_data.get("event")
|
|
user = validated_data.get("user")
|
|
status = validated_data.get("status", "-")
|
|
comment = validated_data.get("comment", "")
|
|
|
|
# Use update_or_create to handle both new and existing participations
|
|
participation, created = EventParticipation.objects.update_or_create(
|
|
event=event,
|
|
user=user,
|
|
defaults={"status": status, "comment": comment},
|
|
)
|
|
|
|
return participation
|
|
|
|
def update(self, instance, validated_data):
|
|
instance.status = validated_data.get("status", instance.status)
|
|
instance.comment = validated_data.get("comment", instance.comment)
|
|
instance.save()
|
|
return instance
|