Derekzs
Derekzs

Reputation: 117

Django error: conversion from bytes to Decimal is not supported

So I have the following model

class Stock(models.Model):
    name = models.CharField(max_length=50)
    unit_measure = models.CharField(max_length=10)
    unit_price = models.DecimalField(max_digits=10, decimal_places=2)

When I try to add an instance of that model in Django's admin site, it gives me the following error

(<class 'TypeError'>, TypeError('conversion from bytes to Decimal is not supported',))

Exception Location: /Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/PyMySQL-0.5-py3.3.egg/pymysql/connections.py in defaulterrorhandler, line 209

But the data was inserted into the table successfully as I look up my database using phpmyadmin.

I am using Django1.5+Python3.3+MySQL5.5+PyMySQL

Anybody have ideas about what has gone wrong here?

Upvotes: 4

Views: 2745

Answers (2)

NotARobot
NotARobot

Reputation: 11

I had the same problem in SQLite 3, the solution I have found was mentioned in a Book (https://books.google.de/books?id=eLKdDwAAQBAJ&lpg=PA394&ots=xBGSOLY4Ue&dq=python%20sqlite%20byte%20to%20decimal&hl=de&pg=PA394#v=onepage&q&f=false)

def convert_decimal(bytes)
     return decimal.Decimal(bytes.decode())

Upvotes: 1

geewiz
geewiz

Reputation: 2206

After 11 months I hope the original poster found a workaround (better than switching to python 2).

The OP did not list his db connection string, but maybe he was using the "use_unicode=0" setting for his connection?

I was, and I hit the same type conversion error recently. Seems like it should be possible to convert from a byte string to a Decimal, maybe that is on someone's todo list :), but until then I can share what worked around the problem for me:

When connecting to mysql (through pymysql and python 3.4.1) set the charset=utf8 property (assuming you want that property, which you probably should) but do NOT set the use_unicode=0 property. I set that property on the advice of the current (0.9) sqlalchemy docs which said it would be "much faster." Faster but broken ain't an improvement :(. Maybe that advice was intended only for python2.x users? It's a bit confusing given how pymysql tries to be hot-swappable MySqlDB for python 3.x, but python's unicode & string handling has changed between 2.x and 3.x so...

Without diving deep into pymysql, I assume that with python3 "use_unicode" means that char fields are returned as python native (unicode) strings rather than "byte strings", with contents encoded as utf8. Set "use_unicode=0" and you get byte strings and thus the TypeError.

Anway, this works for me; hope this helps someone else who sees this error.

Upvotes: 4

Related Questions