Mapping column names

171 views
Skip to first unread message

Larry Martell

unread,
Feb 3, 2022, 8:26:17 PM2/3/22
to sqlal...@googlegroups.com
I normally define a column in a model like this, for example:

jobID = Column(Integer, nullable=False, primary_key=True)

I now have a case where there are columns in the db that have spaces
so I want to map the column name to a variable of a different name.
Googling I found this:

https://docs.sqlalchemy.org/en/14/orm/mapping_columns.html#naming-columns-distinctly-from-attribute-names

class User(Base):
__tablename__ = 'user'
id = Column('user_id', Integer, primary_key=True)
name = Column('user_name', String(50))

How can that work? Is it a different version of Column() from what I
have been using?

Mike Bayer

unread,
Feb 3, 2022, 10:18:18 PM2/3/22
to noreply-spamdigest via sqlalchemy
the names of attributes on your Python class and the names of columns that are emitted in SQL are two separate things.    When you have "jobid = Column(Integer, ...)" , that's a declarative-only format that omits the first argument to Column which is the "name"; the declarative mapping process sets the "name" to be the same as the attribute name.

when you instead have "jobid = Column("somename", Integer ,...)", then you're passing the name argument.

this API grew out of some various legacy patterns which is why it's a little weird looking, but basically Column takes *args and it looks to see if it is getting "str, TypeEngine" or just "TypeEngine".   It also can be passed neither in cases where it derives its type from a ForeignKey() object.
-- 
SQLAlchemy - 
The Python SQL Toolkit and Object Relational Mapper


To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example.  See  http://stackoverflow.com/help/mcve for a full description.
--- 
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.


Larry Martell

unread,
Feb 4, 2022, 8:33:44 AM2/4/22
to sqlal...@googlegroups.com
Thanks for the detailed explanation.
Reply all
Reply to author
Forward
0 new messages