money type for Postgresql

9,990 views
Skip to first unread message

dgardner

unread,
Dec 27, 2011, 2:39:01 PM12/27/11
to sqlalchemy
Quick hack, figured I would share since there seemed to be other
people asking about it.

I couldn't get it to work with "autoload=True" for table reflection.

---

from sqlalchemy import types
from decimal import Decimal

class Money(types.UserDefinedType):

def get_col_spec(self):
return 'money'

def result_processor(self, dialect, coltype):
def process(value):
# Strip off the currency symbol
return Decimal(value[1:])
return process

dgardner

unread,
Dec 27, 2011, 3:59:29 PM12/27/11
to sqlalchemy
Looks like I should have accounted for negative numbers, and thousands
separators. I believe the thousands separator is region specific,
which I am not handling here.

---
class Money(types.UserDefinedType):

def get_col_spec(self):
return 'money'

def result_processor(self, dialect, coltype):
def process(value):
# Strip off the currency symbol
if value.startswith('-'):
trimpoint = 2
sign = '-'
else:
trimpoint = 1
sign = ''

return Decimal(sign + value[trimpoint:].replace(',',''))
return process

Julien Cigar

unread,
Dec 27, 2011, 4:01:29 PM12/27/11
to sqlal...@googlegroups.com
don't use the MONEY type in PostgreSQL, use NUMERIC instead.

dgardner

unread,
Dec 28, 2011, 1:30:50 AM12/28/11
to sqlalchemy
While there may be legitimate reasons to choose the numeric type
instead of the money type. This might not always be an option for
people, especially when working with existing database. If a type is
supported by a database back end there is no reason why it couldn't
and shouldn't be supported by SQLAlchemy, especially when features
like TypeDecorators and compiler extensions make doing so easy.

Martijn Moeling

unread,
Dec 28, 2011, 5:48:01 AM12/28/11
to sqlal...@googlegroups.com
I use Float for money at the moment.

I am moving from Mysql to Postgres and have not had any issues but i'm not sure if Float actually works correctly.
Floats are being used for both broken number values and for money values.

should I change to numeric for Postgres as I do not see that Column Type mentioned in this tread.

Martijn

> --
> You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
> To post to this group, send email to sqlal...@googlegroups.com.
> To unsubscribe from this group, send email to sqlalchemy+...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
>

Julien Cigar

unread,
Dec 28, 2011, 6:20:23 AM12/28/11
to sqlal...@googlegroups.com
Using FLOAT for monetary amounts is an extremely bad idea because of the inexactness of storage and arithmetic ..
Using MONEY is discouraged because it is too locale-sensitive

NUMERIC should be used instead

Reply all
Reply to author
Forward
0 new messages