Home > Enterprise >  Selecting a column with a slash in SQL Alchemy
Selecting a column with a slash in SQL Alchemy

Time:10-05

I need to select some columns from a table with SQL Alchemy. Everything works fine except selecting the one column with '/' in the name. My query looks like:

query = select([func.sum(Table.c.ColumnName),
                func.sum(Table.c.Column/Name),
                ])

Obviously the issue comes from the second line with the column 'Column/Name'. Is there a way in SQL Alchemy to overcome special characters in a column name?


edit:

I've it all inside some class but simplified version of a process looks like this. I create an engine (all necessary db data is inside create_new_engine() function) and map all tables in db into metadata.

def map(self):
    from sqlalchemy.engine.base import Engine
    # check if engine exist
    if not isinstance(self.engine, Engine):
        self.create_new_engine()
    self.metadata = MetaData({'schema': 'dbo'})
    self.metadata.reflect(bind=self.engine)

Then I map a single table with:

def map_table(self, table_name):

    table = "{schema}.{table_name}".format(schema=self.metadata.schema, table_name=table_name)

    table = self.metadata.tables[table]

    return table

In the end I use pandas read_sql_query to run above query with connection and engine established earlier.

I'm connecting to SQL Server.

CodePudding user response:

Since Table.c points to a plain python obect. Try in pure Python

query = select([func.sum(Table.c.ColumnName),
                func.sum(getattr(Table.c, 'Column/Name')),
                ])

So in your case (from comments above) :

func.sum(getattr(Table.c, 'cur/fees'))
  • Related