How to use "CONVERT" function in SqlAlchemy?

func, python, sqlalchemy

Solution

I guess the canonical way to express this is:

func.convert(literal_column('VARCHAR(8)'), Table.datetimefiedld, 8)

Since an expression like `sqlalchemy.sql.func.ANYTHING(arg1, argN)` will be converted to `ANYTHING(arg1, argN)`, you can hack:

func.convert(func.VARCHAR(8), Table.datetimefiedld, 8)

What is the difference?

>>> from sqlalchemy import sql
>>> print sql.func.CONVERT(func.VARCHAR(8), Table.fied, 8)
CONVERT(VARCHAR(:VARCHAR_1), table.field, :CONVERT_1)

>>> print sql.func.CONVERT(
              sql.literal_column('VARCHAR(8)'), 
              Table.fied, 
              sql.literal_column('8')
          )
CONVERT(VARCHAR(8), table.field, 8)

Both should work, but the second is more explicit (more verbose as well). If you are going to use it a lot, you can define:

def date2str(field):
    return sql.func.CONVERT(
               sql.literal_column('VARCHAR(8)'), 
               field, 
               sql.literal_column(8)
           )

An the use just:

date2str(Table.field)

Problem

I tried: ``` from sqlalchemy import VARCHAR result = session.query(Table).filter(func.convert(VARCHAR(8), Table.datetimefiedld, 8) >= some_date).all() ``` I got AttributeError: 'VARCHAR' object has no attribute 'self_group' Can somebody please explain how to use the CONVERT function in sqlalchemy? Thanks!

Original source