How to obtain a name of the class that should be on the other end of the relation? It was declared when creating relationship. I guess that information should be somwhere in sqlalchemy.orm.util.class_mapper
Let's say we have these three classes and a relations between them. Book * --- 1 Shelf and Book * --- * Author
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 boo开发者_运维技巧ks
books = relationship('Book', secondary=author_book, backref='authors')
def __init__(self, name=""):
self.name = name
From class_mapper(Class).iterate_properties we can easily get different properties: ColumnProperty and RelationshipProperty. There should be a way to get at leat the name of the class that is in relation. Any ideas?
Maybe a little bit neater solution.
for prop in class_mapper(Shelf).iterate_properties:
if isinstance(prop, sqlalchemy.orm.RelationshipProperty):
print prop.mapper.class_
works with one-to-many and many-to-many in both directions
As of sqlalchemy 0.8 this can be done with:
from sqlalchemy import inspect
inspect(Shelf).relationships['books'].mapper.class_
I found a sort of solution, but I'm not 100% sure if it works always.To find a class (type ) expected on the other end of relation
class_mapper(Shelf)._props['books'].mapper.class_
We may not know the names of attributes (like books in this case), but it isn't much trouble to go through dictionary *_props* with looking for values witch are instances of sqlalchemy.orm.properties.RelationshipProperty
精彩评论