Comparing Numerics in SQLAlchemy

Question:

I want to store non-integer numbers in my database, and be able to compare them in order to spot duplicates. Obviously, the comparison should be done to within a preset number of decimals (say, 2). So my question in a nutshell: What is the most efficient way to do this?

My first attempt was to store them as Numeric, in SQLAlchemy that would be:

class MyTable(Base):
    __tablename__ = 'mytable'
    x = Column(Numeric(2, 2))

and then do the comparison as

session = Session()  # this was configured elsewhere
query = session.query(MyTable)
query = query.filter(MyTable.x == y)  # y is a float
return session.query(query.exists()).scalar()

Now, this failed, the condition seems to turn out false if I input y as a float.

Can I fix the above approach?
If not, what is the cleanest way to do what I want? (What is the tradeoff between fast and clean here?) Do I have to resort to converting my data to strings or integers? Or work with inequalities..?

Asked By: Emil Lundh

||

Answers:

I think I solved it. It seems that the numbers will be compared as strings, so I should convert my reference value to a string before comparing:

session = Session()  # this was configured elsewhere
query = session.query(MyTable)
query = query.filter(MyTable.x == f'{y:.2f}')  # y is a float
return session.query(query.exists()).scalar()
Answered By: Emil Lundh
from sqlalchemy import cast, Numeric
query = session.query(my_table).filter(cast(my_table.columns['col_a'], Numeric()) == 2100025895.0).count()

use cast function from sqlalchemy to transfer field to numeric type data

Answered By: haibara1997
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.