ORM class attributes that are mapped to database table: provide as built-in method. Generally, provide ORM class-level info.

Issue #3290 resolved
taibit created an issue

I wanted a list of ORM class attributes that are mapped to db columns.

I found the built-in (private) function _orm_columns() in the source code file /lib/sqlalchemy/orm/base.py which worked when my ORM class attributes were not re-named.

But when I made an ORM attribute different from the db column, the _orm_columns() no longer worked.

Generally, there seems to be a need for info about the ORM class that is distinct from the mapping of that class to a db table. There does not seem to be a place for that info that is provided out-of-the-box as far as I can tell.

My a solution for my particular issue that includes my code is posted on stackoverflow at: http://stackoverflow.com/questions/27947294/when-the-sqlalchemy-orm-class-attributes-are-different-from-database-columns-ho

BTW, is there a reason that the function _orm_columns() is private and not documented? Otherwise, users struggle to come up with their own solution as in: http://stackoverflow.com/questions/1958219/convert-sqlalchemy-row-object-to-python-dict/24748320#24748320

On the positive side, it's nice that sqlalchemy and python provide the flexible structure for me to create a simple solution for my particular need as is documented in Mixin and Custom Base Classes http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/declarative/mixins.html

Comments (3)

  1. Mike Bayer repo owner

    this is already implemented:

    from sqlalchemy import *
    from sqlalchemy.orm import *
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import inspect
    
    Base = declarative_base()
    
    class A(Base):
        __tablename__ = 'a'
        id = Column(Integer, primary_key=True)
        x = Column(Integer)
        y = Column(Integer)
    
    print inspect(A).c
    print inspect(A).c.x
    print inspect(A).column_attrs
    print inspect(A).column_attrs.x
    print inspect(A).column_attrs.x.expression
    

    http://docs.sqlalchemy.org/en/rel_0_9/core/inspection.html

    http://docs.sqlalchemy.org/en/rel_0_9/orm/mapping_api.html#sqlalchemy.orm.mapper.Mapper.all_orm_descriptors

    http://docs.sqlalchemy.org/en/rel_0_9/orm/mapping_api.html#sqlalchemy.orm.mapper.Mapper.columns

    http://docs.sqlalchemy.org/en/rel_0_9/orm/mapping_api.html#sqlalchemy.orm.mapper.Mapper.column_attrs

    http://docs.sqlalchemy.org/en/rel_0_9/orm/mapping_api.html#sqlalchemy.orm.mapper.Mapper.c

  2. Log in to comment