Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

475
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda