gpt4 book ai didi

python - 从 sqlalchemy 获取关系元数据

转载 作者:行者123 更新时间:2023-12-01 05:54:15 25 4
gpt4 key购买 nike

我有一个非常简单的用户类定义:

class User(Base):
implements(interfaces.IUser)
__tablename__ = 'users'
#Fields description
id = Column(Integer, primary_key=True)

client_id = Column(Integer, ForeignKey('w2_client.id'))
client = relationship("Client", backref=backref('users', order_by=id))

我想自动生成一个 GUI 来编辑 User 对象(以及其他类型的类)。所以我需要获取表的所有元数据,例如我可以这样做:

    for c in User.__table__.columns:
print c.name, c.type, c.nullable, c.primary_key, c.foreign_keys

但是我无法获得有关“client”关系的任何信息,c.foreign_keys仅向我显示与foreign_keys相关的表,而不是我定义的属性“client”。如果我的问题不清楚,请告诉我

最佳答案

确实,这并不容易获得。经过一些逆向工程后,我必须想出自己的函数。

这是我使用的元数据。我与您正在寻找的内容略有不同,但也许您可以使用它。

# 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)


def get_metadata(class_):
"""Returns a list of MetaDataTuple structures.
"""
return list(get_metadata_iterator(class_))


def get_metadata_map(class_):
rv = {}
for metadata in get_metadata_iterator(class_):
rv[metadata.colname] = metadata
return rv

但它没有主键。我为此使用了一个单独的函数。

mapper = class_mapper(ORMClass)
pkname = str(mapper.primary_key[0].name)

也许我应该将主键名称放入元数据中。

关于python - 从 sqlalchemy 获取关系元数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13234137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com