gpt4 book ai didi

python - 列名称的 sqlalchemy 别名也保留原始名称

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

我的表定义如下:

class A():
__tablename__ = 'a'
a_id = Column('a_id', INTEGER)

class B():
__tablename__ = 'b'
b_id = Column('b_id', INTEGER)

除了 <tablename>_id 中的差异外,表具有相同的架构列,这是我需要同时查询两者的常见情况。
由于遗留原因,我无法将类属性重命名为 id但我可以添加一个属性。我正在寻找类似的东西

class A():
__tablename__ = 'a'
a_id = Column('a_id', INTEGER)
id = alias_of_column(a_id)

有类似的吗?

最佳答案

sqlalchemy.orm.synonym是在另一个属性上镜像列的最直接方法。

来自文档:

In the most basic sense, the synonym is an easy way to make a certain attribute available by an additional name...

还有:

The synonym() can be used for any kind of mapped attribute that subclasses MapperProperty, including mapped columns and relationships, as well as synonyms themselves.

用法就像您问题中的示例一样简单:

from sqlalchemy.orm import synonym
class B(Base):
__tablename__ = 'b'
b_id = Column('b_id', INTEGER, primary_key=True)
id = synonym('b_id')

此测试代码:

s.add(B(id=1))
s.commit()
print(s.query(B).filter(B.id==1).one())

...发出此 SQL:

2019-03-31 20:54:05,208 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2019-03-31 20:54:05,209 INFO sqlalchemy.engine.base.Engine INSERT INTO b (b_id) VALUES (%(b_id)s)
2019-03-31 20:54:05,209 INFO sqlalchemy.engine.base.Engine {'b_id': 1}
2019-03-31 20:54:05,211 INFO sqlalchemy.engine.base.Engine COMMIT
2019-03-31 20:54:05,218 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2019-03-31 20:54:05,219 INFO sqlalchemy.engine.base.Engine SELECT b.b_id AS b_b_id
FROM b
WHERE b.b_id = %(b_id_1)s
2019-03-31 20:54:05,219 INFO sqlalchemy.engine.base.Engine {'b_id_1': 1}
B(b_id=1)

关于python - 列名称的 sqlalchemy 别名也保留原始名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55439089/

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