开发者

How to find sqlalchemy remote side object's class or class name without db queries?

开发者 https://www.devze.com 2023-03-23 10:18 出处:网络
Let\'s have a classes X and Y and relations between them x2y and y2x. From class_mapper(Class).iterate_properties iterator we can get all class\'s properties.

Let's have a classes X and Y and relations between them x2y and y2x. From class_mapper(Class).iterate_properties iterator we can get all class's properties. So x2y and y2x are RelationshipProperty and what I hope to get from is a class or a class name of objects on remote side of relation.

I've already tried to make a solution. I've found x2y.remote_side[0].table.name, made a tables_map which maps a table name to a class and it works fine for one-to-many and one-to-one. If I use it for many-to-many the tab开发者_StackOverflow中文版le name is an association table.

Any hints on how can I get the remote side class?


X.x2y.property.mapper.class_

relatonshipproperty will eventually get class-level attribute documentation the same as mapper does now.

edit. Here is a test which illustrates the above returning "Y" from "X", and no reflection doesn't create relationships so should have no effect:

from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
class X(Base):
    __tablename__ = 'x'
    id = Column(Integer, primary_key=True)
    x2y = relationship("Y")

class Y(Base):
    __tablename__ = 'y'
    id = Column(Integer, primary_key=True)
    x_id = Column(Integer, ForeignKey("x.id"))

assert X.x2y.property.mapper.class_ is Y


I've found that a method argument() on relationshipproperty returns remote class.

for prop in class_mapper(X).iterate_properties:
    if isinstance(prop, RelationshipProperty):
        relation = prop
relation.argument()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号