[Python] How to propagate error on create method in DRF serializer?

Discussão em 'Python' iniciado por Stack, Março 26, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to raise some error based on some business logic as in below

    class ConsultationViewset(BaseModelViewset, ListModelViewsetMixin, RetrieveModelViewsetMixin, CreateModelViewsetMixin, UpdateModelViewsetMixin):
    serializer_class = ConsultationSerializer
    ....


    class ConsultationSerializer(serializers.ModelSerializer):
    def create(self, validated_data):
    consultation = ConsultationService.create_consultation(validated_data.pop('customer', None), validated_data)
    return consultation


    def create_consultation(customer: CustomerFactory.Models.CUSTOMER, validated_data):
    if ticket is None:
    raise exceptions.PermissionDenied("No active ticket found for this customer, request is forbidden")


    My aim is to send the raised message in create_consultation in the response. Yet I keep getting AssertionError: create() did not return an object instance.instead. I could send a custom message if I re-raise the error in the viewset like below, but it felt wrong as the error is AssertionError.

    class ConsultationViewset(...):
    def perform_create(self, serializer):
    try:
    serializer.save()
    except AssertionError as e:
    raise exceptions.PermissionDenied('custom message')


    How to properly raise a PermissionDenied error?

    Continue reading...

Compartilhe esta Página