给定一个声明式SQLAlchemy类,如何以编程方式检索其作为主键的Column对象列表?

时间:2012-02-22 16:19:05

标签: sqlalchemy

假设我在SQLAlchemy中有一个类

class Note(Base):
    __tablename__ = 'notes'
    slug = Column('short_title', String, primary_key=True)
    date = Column('day', Date, primary_key=True)
    contents = Column(Text, nullable=True)

只给出了对Note类的引用,函数如何构建列表['Note.slug','Note.date'],它们构成相应表的主键?

此外,有没有办法根据列属性过滤类属性? (例如可为空,类型,唯一性,索引中的成员资格等)

3 个答案:

答案 0 :(得分:4)

尝试此操作以查找主要字段。

from sqlalchemy import create_engine

engine = create_engine('sqlite:///:memory:', echo=True)

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Date, Text
from sqlalchemy.orm.attributes import InstrumentedAttribute


Base = declarative_base()

class Note(Base):
    __tablename__ = 'notes'
    slug = Column('short_title', String, primary_key=True)
    date = Column('day', Date, primary_key=True)
    contents = Column(Text, nullable=True)

if __name__ == '__main__':
    import inspect
    predicate = lambda x: isinstance(x, InstrumentedAttribute)

    fields = inspect.getmembers(Note, predicate=predicate)

    fields_vars = [vars(y.property.columns[0]) for x,y in fields]

    primary_fields = [x['name'] for x in fields_vars if x['primary_key']]

    print "All Fields :", fields_vars

    print "Primary Fields :", primary_fields

通过这种方式,您可以在模型中找到任何类型的字段。

答案 1 :(得分:4)

这将为您提供一个列名称为primary_keys的列表:

from sqlalchemy.orm import class_mapper

primary_keys = [key.name for key in class_mapper(Note).primary_key]

答案 2 :(得分:3)

不完全需要什么,但只是使用内部信息的更短的变体:

from sqlalchemy import create_engine

engine = create_engine('sqlite:///:memory:', echo=True)

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Date, Text

Base = declarative_base()

class Note(Base):
    __tablename__ = 'notes'
    slug = Column('short_title', String, primary_key=True)
    date = Column('day', Date, primary_key=True)
    contents = Column(Text, nullable=True)

if __name__ == '__main__':
    print [(i.name, i.primary_key) for i in Note.__table__.columns]

这给了我们以下结果:

[('short_title', True), ('day', True), ('contents', False)]