On 7/27/15 9:08 AM, [email protected] wrote:
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.

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






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


--
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to