[Python] How to handle constraint errors like unique or not null from DB in Django

Discussão em 'Python' iniciado por Stack, Junho 28, 2025.

  1. Stack

    Stack Membro Participativo

    I have a write operation which adds a record in rider model. The rider_code is unique in this. Now 1 way is to first check if any record with that rider_code exists then return error else create rider. But it requires 2 db calls when the db can return constraint error on create which would be a single call. But how to catch these constraint errors correctly in Django.

    This is 1 of the solutions I got but it does not seem right:

    def create_rider(request):
    serializer = RiderSerializer(data=request.data, context={"request": request})
    if serializer.is_valid():
    try:
    rider = serializer.save()
    return True, rider
    except IntegrityError as e:
    error_msg = str(e)

    if "ds_riders.ds_riders_rider_code_d4b087a9_uniq" in error_msg:
    return False, {"details": "Rider Code already exists."}
    if "application_users.username" in error_msg:
    return False, {"details": "Username already exists."}

    return False, {"details": error_msg}

    return False, serializer.errors`

    Continue reading...

Compartilhe esta Página