Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

474
Views
Use to_char in Flask SqlAlchemy query

In my Flask model I have this column:

datetime = db.Column(db.DateTime, nullable=False, default=datetime.now)  

When I populate the rows from a PostgreSql database I get this:

2020-07-03 18:12:49.362271
2020-07-04 09:21:34.644202

Now, I want to format those results using the to_char function from Postgresql. The query shoudl be this:

select to_char(datetime, 'YYYY-MM-DD HH24:MI:SS') as datetime from order_detail;

And the result is this:

---------------------
 2020-07-03 18:12:49
 2020-07-04 09:21:34
(2 rows)

How can I tell Flask-SqlAlchemy to execute that function when it queries the order_detail table?.

Important: I don't want to do the formatting in my Flask app, I want to let Postgresql format the results.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Use column_property() and func(). Assuming your model is named Foo:

from sqlalchemy import func
from sqlalchemy.orm import column_property

class Foo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    datetime = db.Column(db.DateTime, nullable=False, default=datetime.now)
    formatted_datetime = column_property(func.to_char(datetime, 'YYYY-MM-DD HH24:MI:SS'))

# print(Foo.query.all()[0].formatted_datetime)
# ->'2020-07-04 06:59:09'

If it's important that the model's attribute name be datetime, you'll need to give the underlying column a different attribute name and reference the column using it's name kwarg.

class Foo2(db.Model):
    __tablename__ = 'foo'
    id = db.Column(db.Integer, primary_key=True)
    orig_datetime = db.Column(db.DateTime, name='datetime', nullable=False, default=datetime.now)
    datetime = column_property(func.to_char(orig_datetime, 'YYYY-MM-DD HH24:MI:SS'))

# print(Foo2.query.all()[0].datetime)
# ->'2020-07-04 06:59:09'
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!