I have the following model:
172 class ReportRecord(db.Model):
173 __tablename__ = 'tb_report_record' 174 175 id = db.Column(Integer, primary_key=True)
176 report_id = db.Column(ForeignKey('tb_rua_report.id'), index=True)
177 source_ip = db.Column(String(100, 'utf8_bin'))
178 count = db.Column(Integer)
179 disposition = db.Column(String(10, 'utf8_bin'))
180 header_from = db.Column(String(100, 'utf8_bin'))
181 spf_domain = db.Column(String(100, 'utf8_bin'))
182 spf_result = db.Column(String(10, 'utf8_bin'))
183 dkim_domain = db.Column(String(100, 'utf8_bin'))
184 dkim_result = db.Column(String(10, 'utf8_bin'))
185 isActive = db.Column(Integer, nullable=False, server_default=text("'1'")) 186 created_by = db.Column(String(100), nullable=False, server_default=text("'System'"))
187 created_dt = db.Column(DateTime, nullable=False)
188 last_modified_by = db.Column(String(100), nullable=False, server_default=text("'System'"))
189 last_modified_dt = db.Column(DateTime, server_default=text("CURRENT_TIMESTAMP"))
190
191 report = db.relationship('RuaReport', backref=db.backref("record"))
When I am issuing the following query from flasksqlalchemy
ReportRecord.query.filter(or_(ReportRecord.spf_result=="pass", ReportRecord.dkim_result=="pass")).with_entities(func.sum(ReportRecord.count).label('total_passed')).all()
I get the following output:
[(Decimal('930'),)]
Now the value that I get is correct, but I cannot jsonify
it directly. Doing a int(Decimal('930'))
does give me the desired result but what is the default way to get this data converted in the right format?
This worked for me: Include this in your imports:
from sqlalchemy import func
then:
total_passed = db.session.query(func.sum(ReportRecord.count)).scalar()
This returns 930 instead of [(Decimal('930'),)]
Read more about .scalar()
How about converting the decimal while querying it?
Try int(func.sum(ReportRecord.count).label('total_passed'))
try enforcing your db to cast values into integer should solve your problem
I cannot check but there is a cast function which might be useful as well
from sqlalchemy.sql.expression import cast
cast(func.sum(ReportRecord.count).label('total_passed'),sqlalchemy.Integer)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With