Search code examples
pythonapidjango-rest-frameworknandivide-by-zero

Issue handling NaN due to division by zero


I am developing an API with Django-rest-framework. The request are in get(), the user inputs a date and a department number and gets in return a response containing sales indicators about that particular date for that particular department.

Issue: The issue is that in some cases for old data from 2018 most of the fields that I am querying on are zeroes and there is a division to calculate some indicators so you end up by getting NaN and that kinds of breaks the functionning of the API.

This is a sample code from my views.py:

    sql = "select sales_p, sales_c, sales_all from sales where dat_ref = '" + input_date + "'"
    try:
        df = select_vector(sql, DB_CONNECTOR)
    except Exception:
        raise ServiceUnavailable()
    if df is None:
        raise ServiceUnavailable()

    if len(df) > 0:
        sales_1 = df['sales_p'].loc[0]
        sales_2 = df5['sales_c'].loc[0]
        sales_all = df5['sales_all'].loc[0]
    else:
        return Response(status=204)

    percentage = float(("{0:.2f}".format(((sales_all - sales_p)/sales_c)*100)))

    response = {'Percentage': percentage}

I am looking for the best way to handle this and maybe return a message for clarification to the user.


Solution

  • The simplest solution is probably just to put:

    if sales_c == 0:
        #Handle the error however you want, raise an exception print a message or whatever else
    else:
        #Continue with program
    

    Please let me know if this doesn't do the trick for some reason, I may have missed something in the problem statement.