Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Sqlalchemy Use Date In Filter Using Postgresql

I'm trying to perform the following query in Sqlalchemy.

Select * from "Mytable" where Date(date_time_field) = "2011-08-16"; 

I have tried several methods. Some here on SO. But none seems "realistic" since some do Casts Other String Formating ?!?! and not a plain simple Date() ( By Date i Mean the Postgresql Date not the Python One) at the ORM Field.

Is it possible at the ORM level to declare a Simple Date() around the queried field ?

Best Regards António

like image 375
PythonWolf Avatar asked Aug 16 '11 09:08

PythonWolf


People also ask

Can I use SQLAlchemy with PostgreSQL?

This SQLAlchemy engine is a global object which can be created and configured once and use the same engine object multiple times for different operations. The first step in establishing a connection with the PostgreSQL database is creating an engine object using the create_engine() function of SQLAlchemy.

What is difference between filter and filter by in SQLAlchemy?

The second one, filter_by(), may be used only for filtering by something specifically stated - a string or some number value. So it's usable only for category filtering, not for expression filtering. On the other hand filter() allows using comparison expressions (==, <, >, etc.)

What does First () do in SQLAlchemy?

first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present). Calling Query. first() results in an execution of the underlying query.


1 Answers

Using @Ants Aasma Comment.

And to Keep it clean for any web search.

from sqlalchemy import Date, cast from datetime import date  my_data = session.query(MyObject).\ filter(cast(MyObject.date_time,Date) == date.today()).all() 

Thank you all who tried to solve this problem :)

like image 76
PythonWolf Avatar answered Oct 06 '22 04:10

PythonWolf