pythonmysqlsqlalchemyflask-sqlalchemy

Whats the proper way to use date and interval in SQLAlchemy?


I need to implement this filter in SQLalchemy, with a MySQL database

dmb.manifest_date >= (CURDATE() - interval 7 day)

What I did is

date_filter=(datetime.today()-timedelta(days=7)).strftime('%Y-%m-%d')
.filter(DayManifestBatch.manifest_date>= cast(date_filter,DATE))

I imported DATE and cast from SQLALchemy. Also tried with just the string date and datetime format but I always get this error

sqlalchemy.exc.ArgumentError: SQL expression object expected, got object of type <class 'flask_sqlalchemy.model.DefaultMeta'> instead

Solution

  • There is probably a better way but you can use:

    from sqlalchemy import text
    
    .filter(DayManifestBatch.manifest_date >= text('CURDATE() - INTERVAL 7 DAY'))