How to get a <class 'float'> back from a SQLAlchemy query?

385 views
Skip to first unread message

c.b...@posteo.jp

unread,
Jul 27, 2015, 9:08:56 AM7/27/15
to sqlal...@googlegroups.com
I have (sqlite3) database with a `Numeric(10, 2)` field. I want to
query for that and work with it as a standard python datatype (for me
this is `<class 'float'>`). In the code below I want a list of floats -
nothing more. How can I do this without manual converting the list?

# Python3 pseudocode
class Model(_Base):
__tablename__ = 'Model'
...
_weight = sa.Column('weight', sa.Numeric(10, 2))
...

query = session.query(Model._weight)
result = query.all()
print(type(result))
print(type(result[0]))
print(type(result[0][0]))

This is the result I can not work with

<class 'list'>
<class 'sqlalchemy.util._collections.result'>
<class 'decimal.Decimal'>

When I use `Numeric(10, 2, asdecimal=False)` and `int` is returned. I
know that sqlite can not handle float numbers.

btw. I want to work with that float numbers in matplotlib.

Mike Bayer

unread,
Jul 27, 2015, 11:11:48 AM7/27/15
to sqlal...@googlegroups.com
the asdecimal=False would be the way to go here. The fact that its
returning 'int' is probably an artifact of the SQLite driver, perhaps
that the numerical values that are stored don't actually have a decimal
portion so it isn't known that these are "float" and not "int" (sqlite
has a per-row tying model). Normally it shouldn't be an issue that
these are ints because Python ints/floats can be used together, but if
you want to force float, use TypeDecorator
(http://docs.sqlalchemy.org/en/rel_1_0/core/custom_types.html?highlight=typedecorator#augmenting-existing-types):

class ForceFloat(TypeDecorator):
impl = Numeric(10, 2, asdecimal=False)

def process_result_value(self, value, dialect):
if value is not None:
value = float(value)
return value
Reply all
Reply to author
Forward
0 new messages