0

I am relatively new to Django framework and working on getting my first application running. I am encountering the below issue when i try to pass my queryset from my view to the template.

My view.py:

with connection.cursor() as cursor:
        cursor.execute("SELECT TOP(5) * FROM xxx WHERE sbu = %s", [sbu])
        def dictfetchall(cursor):
            columns = [col[0] for col in cursor.description]
            return [dict(zip(columns,row)) for row in cursor.fetchall()]

 results = dictfetchall(cursor)
 class DecimalEncoder(json.JSONEncoder):
            def _iterencode(self, o, markers=None):
                if isinstance(o, decimal.Decimal):
                    return (str(o) for o in [o])
                    return super(DecimalEncoder, self)._iterencode(o, markers)

 json_result = json.dumps(data, cls=DecimalEncoder)

I end up with the below error:

Decimal('28.80') is not JSON serializable

Any suggestions? Am i missing a step somwhere? I have lot of decimal values in the queryset.

ppv
  • 33
  • 5
  • 1
    It seems like you are having problems with serializing a DecimalField to json. You seem to already have read this related question to your problem: http://stackoverflow.com/questions/1960516/python-json-serialize-a-decimal-object. If you are new to Django I would highly recommend you to use the Django ORM instead of a raw database connection in combination with Django-Rest-Framework if your application should be an API. Django Rest Framework takes care of most of the json encoding and decoding and makes life a lot easier. – matyas May 05 '17 at 12:37
  • I did not want to use Django ORM to avoid django models. All i need to do is take some form input and based on the input query the database. I don't have any model. – ppv May 05 '17 at 21:23

0 Answers0