gpt4 book ai didi

python - 在不创建对象的情况下,sqlalchemy 中关系的另一端是什么类型?

转载 作者:行者123 更新时间:2023-11-30 23:58:42 26 4
gpt4 key购买 nike

如何获得应该在关系另一端的类的名称?它是在创建关系时声明的。我想该信息应该在 sqlalchemy.orm.util.class_mapper 中

假设我们有这三个类以及它们之间的关系。
书 * --- 1 架子和
书 * --- * 作者

class Shelf(Base):
__tablename__ = 'shelves'
id = Column(Integer, primary_key = True)
name = Column(String)
#one-to-many books by backref in Book.shelf

def __init__(self, name=""):
self.name = name

class Book(Base):
__tablename__ = 'books'
id = Column(Integer, primary_key = True)
title = Column(String)
#many-to-one shelf
shelf_id = Column(Integer, ForeignKey('shelves.id'))
shelf = relationship(Shelf, backref=backref('books', order_by=id))
def __init__(self, title=""):
self.title = title

author_book = Table('author_book', metadata,
Column('author_id', Integer, ForeignKey('authors.id')),
Column('book_id', Integer, ForeignKey('books.id'))
)

class Author(Base):
__tablename__ = 'authors'
id = Column(Integer, primary_key = True)
name = Column(String)
#many-to-many books
books = relationship('Book', secondary=author_book, backref='authors')

def __init__(self, name=""):
self.name = name

从 class_mapper(Class).iterate_properties 我们可以很容易地得到不同的属性:ColumnProperty 和 RelationshipProperty。
应该有一种方法可以获取相关类的名称。有任何想法吗?

最佳答案

也许更简洁的解决方案。

for prop in class_mapper(Shelf).iterate_properties:
if isinstance(prop, sqlalchemy.orm.RelationshipProperty):
print prop.mapper.class_

双向使用一对多和多对多

关于python - 在不创建对象的情况下,sqlalchemy 中关系的另一端是什么类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3805712/

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