1
0

ticket.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from django.shortcuts import get_object_or_404
  2. from rest_framework import serializers
  3. from tickets.models import Ticket, TicketList
  4. class BaseTicketSerializer(serializers.ModelSerializer):
  5. status = serializers.IntegerField(read_only=True)
  6. def validate(self, data):
  7. user = self.context['request'].user
  8. ticket_list = data.get("ticket_list")
  9. if ticket_list:
  10. if not (user.is_superuser or ticket_list.group in user.groups.all()):
  11. raise serializers.ValidationError("You don't have access to this list.")
  12. return data
  13. class TicketSerializer(BaseTicketSerializer):
  14. note = serializers.CharField(write_only=True, required=False)
  15. json = serializers.CharField(write_only=True, required=False)
  16. ticket_list = serializers.PrimaryKeyRelatedField(queryset=TicketList.objects.all(), write_only=True)
  17. class Meta():
  18. model = Ticket
  19. fields = "__all__"
  20. class TicketDetailSerializer(BaseTicketSerializer):
  21. ticket_type = serializers.IntegerField(read_only=True)
  22. available_statuses = serializers.SerializerMethodField()
  23. def get_available_statuses(self, obj):
  24. return obj.get_available_statuses()
  25. class Meta():
  26. model = Ticket
  27. fields = "__all__"
  28. class TicketStatusSerializer(BaseTicketSerializer):
  29. status = serializers.IntegerField(read_only=False, required=True)
  30. available_statuses = serializers.SerializerMethodField()
  31. def get_available_statuses(self, obj):
  32. return obj.get_available_statuses()
  33. def validate_status(self, status):
  34. valid_statuses = self.get_available_statuses(self.instance)
  35. if not valid_statuses or status not in valid_statuses:
  36. raise serializers.ValidationError("Invalid value for the status field")
  37. return status
  38. class Meta():
  39. model = Ticket
  40. fields = ["id", "available_statuses", "status"]