如何在SQLAlchemy ORM中打印所有列

时间:2011-05-18 02:45:25

标签: python sqlalchemy

使用SQLAlchemy,我试图以类似于以下的方式打印出每个模型的所有属性:

SELECT * from table;

但是,我想对每个模型实例信息做一些事情。到目前为止,我能够提出的最好的是:

for m in session.query(model).all():
    print [getattr(m, x.__str__().split('.')[1]) for x in model.__table__.columns]
    # additional code 

这会给我我正在寻找的东西,但这是一个相当迂回的方式来获得它。我有点希望得到一个属性:

m.attributes 
# or 
m.columns.values

我觉得我错过了一些东西,并且有更好的方法可以做到这一点。我这样做是因为我将打印所有内容到.CSV文件,我不想指定我感兴趣的列/属性,我想要一切(很多列都有很多要打印的模型。)

10 个答案:

答案 0 :(得分:17)

这是一篇旧帖子,但我遇到的问题是实际的数据库列名与实例上的映射属性名不匹配。我们结束了这个:

from sqlalchemy import inspect
inst = inspect(model)
attr_names = [c_attr.key for c_attr in inst.mapper.column_attrs]

希望能帮助有同样问题的人!

答案 1 :(得分:11)

以罗德尼的答案为基础:

model = MYMODEL
columns = [m.key for m in model.__table__.columns]

答案 2 :(得分:8)

可能是最短的解决方案(参见最近的documentation):

from sqlalchemy.inspection import inspect
table = inspect(model)
for column in table.c
    print column.name

答案 3 :(得分:5)

我相信这是最简单的方法:

print [cname for cname in m.__dict__.keys()]

编辑:使用sqlalchemy.inspection.inspect()的上面的答案似乎是一个更好的解决方案。

答案 4 :(得分:4)

查看SQLAchemy的metadata reflection功能。

答案 5 :(得分:2)

把它放在一起,发现它很有帮助:

for row in probables:
    if '/' in row[1]:
        a = row[0] #Name from probables list
        b = row[1] #Abbrev. of team
        for row in salaries:
            if row[1] == a:
                c = row[3] #First team involved in game
                d = row[5] #Second team involved in game
        if b == c:
            row[1] = c
        elif b == d:
            row[1] = d

然后:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('mysql+pymysql://testuser:password@localhost:3306/testdb')
DeclarativeBase = declarative_base()
metadata = DeclarativeBase.metadata
metadata.bind = engine


# configure Session class with desired options
Session = sessionmaker()

# associate it with our custom Session class
Session.configure(bind=engine)

# work with the session
session = Session()

示例输出d = {k: metadata.tables[k].columns.keys() for k in metadata.tables.keys()}

print(d)

OR然后:

{'orderdetails': ['orderNumber', 'productCode', 'quantityOrdered', 'priceEach', 'orderLineNumber'], 
'offices': ['addressLine1', 'addressLine2', 'city', 'country', 'officeCode', 'phone', 'postalCode', 'state', 'territory'],
'orders': ['comments', 'customerNumber', 'orderDate', 'orderNumber', 'requiredDate', 'shippedDate', 'status'],
'products': ['MSRP', 'buyPrice', 'productCode', 'productDescription', 'productLine', 'productName', 'productScale', 'productVendor', 'quantityInStock'],
'employees': ['employeeNumber', 'lastName', 'firstName', 'extension', 'email', 'officeCode', 'reportsTo', 'jobTitle'], 
'customers': ['addressLine1', 'addressLine2', 'city', 'contactFirstName', 'contactLastName', 'country', 'creditLimit', 'customerName', 'customerNumber', 'phone', 'postalCode', 'salesRepEmployeeNumber', 'state'],
'productlines': ['htmlDescription', 'image', 'productLine', 'textDescription'],
'payments': ['amount', 'checkNumber', 'customerNumber', 'paymentDate']}

答案 6 :(得分:2)

我在Python 3.5.2上使用SQL Alchemy v 1.0.14

假设您可以使用create_engine()连接到引擎,我可以使用以下代码显示所有列。用适当的值替换“我的连接字符串”和“我的表名”。

from sqlalchemy import create_engine, MetaData, Table, select

engine = create_engine('my connection string')

conn = engine.connect()
metadata = MetaData(conn)
t = Table("my table name", metadata, autoload=True)
columns = [m.key for m in t.columns]
columns

最后一行只显示上一个语句中的列名。

答案 7 :(得分:2)

print repr(model.__table__)

或者只是列:

print str(list(model.__table__.columns))

答案 8 :(得分:1)

你可能对我想出的事情感兴趣。

from sqlalchemy.orm import class_mapper
import collections

# structure returned by get_metadata function.
MetaDataTuple = collections.namedtuple("MetaDataTuple", 
        "coltype, colname, default, m2m, nullable, uselist, collection")


def get_metadata_iterator(class_):
    for prop in class_mapper(class_).iterate_properties:
        name = prop.key
        if name.startswith("_") or name == "id" or name.endswith("_id"):
            continue
        md = _get_column_metadata(prop)
        if md is None:
            continue
        yield md


def get_column_metadata(class_, colname):
    prop = class_mapper(class_).get_property(colname)
    md = _get_column_metadata(prop)
    if md is None:
        raise ValueError("Not a column name: %r." % (colname,))
    return md


def _get_column_metadata(prop):
    name = prop.key
    m2m = False
    default = None
    nullable = None
    uselist = False
    collection = None
    proptype = type(prop)
    if proptype is ColumnProperty:
        coltype = type(prop.columns[0].type).__name__
        try:
            default = prop.columns[0].default
        except AttributeError:
            default = None
        else:
            if default is not None:
                default = default.arg(None)
        nullable = prop.columns[0].nullable
    elif proptype is RelationshipProperty:
        coltype = RelationshipProperty.__name__
        m2m = prop.secondary is not None
        nullable = prop.local_side[0].nullable
        uselist = prop.uselist
        if prop.collection_class is not None:
            collection = type(prop.collection_class()).__name__
        else:
            collection = "list"
    else:
        return None
    return MetaDataTuple(coltype, str(name), default, m2m, nullable, uselist, collection)

答案 9 :(得分:0)

我使用它是因为它略短:

for m in session.query(*model.__table__.columns).all():
    print m