如何在没有数据库查询的情况下查找 sqlalchemy 远程端对象的类或类名?

发布于 2024-11-26 16:56:50 字数 297 浏览 1 评论 0原文

让我们有一个类 X 和 Y 以及它们之间的关系 x2y 和 y2x。 从 class_mapper(Class).iterate_properties 迭代器中我们可以获得类的所有属性。 所以x2y和y2x是RelationshipProperty,我希望从中获得的是关系远程端对象的类或类名。

我已经尝试制定解决方案。 我找到了 x2y.remote_side[0].table.name,制作了一个tables_map,它将表名映射到类,并且它适用于一对多和一对一。如果我将它用于多对多,则表名称是关联表。

关于如何获得远程端类的任何提示?

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 table name is an association table.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不再让梦枯萎 2024-12-03 16:56:50

X.x2y.property.mapper.class_relatonshipproperty

最终将获得类级别的属性文档,就像mapper现在所做的一样。

编辑。这是一个测试,说明上面从“X”返回“Y”,并且没有反射不会创建关系,因此应该没有效果:

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

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
2024-12-03 16:56:50

我发现关系属性上的方法 argument() 返回远程类。

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

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文