Search code examples
pythonsqlalchemyintrospection

SQLAlchemy introspection of ORM classes/objects


I am looking for a way to introspect SQLAlchemy ORM classes/entities to determine the types and other constraints (like maximum lengths) of an entity's properties.

For example, if I have a declarative class:

class User(Base):
    __tablename__ = "USER_TABLE"

    id = sa.Column(sa.types.Integer, primary_key=True)
    fullname = sa.Column(sa.types.String(100))
    username = sa.Column(sa.types.String(20), nullable=False)
    password = sa.Column(sa.types.String(20), nullable=False)
    created_timestamp = sa.Column(sa.types.DateTime, nullable=False)

I would want to be able to find out that the 'fullname' field should be a String with a maximum length of 100, and is nullable. And the 'created_timestamp' field is a DateTime and is not nullable.


Solution

  • Something like:

    table = User.__table__
    field = table.c["fullname"]
    print "Type", field.type
    print "Length", field.type.length
    print "Nullable", field.nullable
    

    EDIT:

    The upcoming 0.8 version has a New Class Inspection System:

    New Class Inspection System

    Status: completed, needs docs

    Lots of SQLAlchemy users are writing systems that require the ability to inspect the attributes of a mapped class, including being able to get at the primary key columns, object relationships, plain attributes, and so forth, typically for the purpose of building data-marshalling systems, like JSON/XML conversion schemes and of course form libraries galore.

    Originally, the Table and Column model were the original inspection points, which have a well-documented system. While SQLAlchemy ORM models are also fully introspectable, this has never been a fully stable and supported feature, and users tended to not have a clear idea how to get at this information.

    0.8 has a plan to produce a consistent, stable and fully documented API for this purpose, which would provide an inspection system that works on classes, instances, and possibly other things as well. While many elements of this system are already available, the plan is to lock down the API including various accessors available from such objects as Mapper, InstanceState, and MapperProperty:

    (follow the link for more info)