Friday, 7 October 2022

Python3, django avoid get query exception

https://stackoverflow.com/questions/50453337/how-to-handle-an-exception-in-django-moving-from-get-to-filter

 Get query will result exception, if record does not exist

  try:
        record = Record.objects.get(name__iexact=record_name)
    except Record.DoesNotExist:
        logging.debug("Error: Record does not exist")
        return Response({"Error": "Record does not exist"}, status=status.HTTP_404_NOT_FOUND)


to avoid exception use
filter().first() :

record = Record.objects.filter(name__iexact=record_name).first()
if record is None:
    # record does not exist - handle this



or you can use get_or_create
https://stackoverflow.com/questions/1941212/correct-way-to-use-get-or-create

No comments:

Post a Comment