from django.shortcuts import get_object_or_404 from rest_framework import serializers from tickets.models import Ticket, TicketList class BaseTicketSerializer(serializers.ModelSerializer): status = serializers.IntegerField(read_only=True) def validate(self, data): user = self.context['request'].user ticket_list = data.get("ticket_list") if ticket_list: if not (user.is_superuser or ticket_list.group in user.groups.all()): raise serializers.ValidationError("You don't have access to this list.") return data class TicketSerializer(BaseTicketSerializer): note = serializers.CharField(write_only=True, required=False) json = serializers.CharField(write_only=True, required=False) ticket_list = serializers.PrimaryKeyRelatedField(queryset=TicketList.objects.all(), write_only=True) class Meta(): model = Ticket fields = "__all__" class TicketDetailSerializer(BaseTicketSerializer): ticket_type = serializers.IntegerField(read_only=True) available_statuses = serializers.SerializerMethodField() def get_available_statuses(self, obj): return obj.get_available_statuses() class Meta(): model = Ticket fields = "__all__" class TicketStatusSerializer(BaseTicketSerializer): status = serializers.IntegerField(read_only=False, required=True) available_statuses = serializers.SerializerMethodField() def get_available_statuses(self, obj): return obj.get_available_statuses() def validate_status(self, status): valid_statuses = self.get_available_statuses(self.instance) if not valid_statuses or status not in valid_statuses: raise serializers.ValidationError("Invalid value for the status field") return status class Meta(): model = Ticket fields = ["id", "available_statuses", "status"]