gpt4 book ai didi

python - 炼金术。如何查询两个模型的结果列表?

转载 作者:太空宇宙 更新时间:2023-11-03 18:55:29 25 4
gpt4 key购买 nike

有模型。

class CMiixin(objects):

@declared_attr
def x(cls):
return Column(Float)


class ABase(Base):
__tablename__ = 'a_base'

@declared_attr
def __mapper_args__(cls):
return {'polymorphic_identity': '%s' % cls.__tablename__,
'polymorphic_on': cls.type,
'with_polymorphic': '*'}

id = Column(Integer, primary_key= True)
type = Column(String)
# other attr

class A(CMixin, ABase):
__tablename__ = 'a'

id = Column(ForeignKey('a_base.id'), primary_key= True)
# other attr

class BBase(Base):
__tablename__ = 'b_base'

@declared_attr
def __mapper_args__(cls):
return {'polymorphic_identity': '%s' % cls.__tablename__,
'polymorphic_on': cls.type,
'with_polymorphic': '*'}

id = Column(Integer, primary_key= True)
type = Column(String)
# other attr

class B(CMixin, ABase):
__tablename__ = 'b'

id = Column(ForeignKey('b_base.id'), primary_key= True)
# other attr

如何选择 x(attribute CMixin) <= 5 的单个查询 A 和 B?东西这个 db.session.query(???).filter(A.x <= 5, B.x <= 5).all() A 和 B 对象的结果列表或者是不可能做到的,只需添加两次查询的结果?

最佳答案

尝试一下union_all :

select1 = Session.query(A.x, <other_columns>).filter(A.x <= 5)
select2 = Session.query(B.x, <other_columns>).filter(B.x <= 5)
result = select1.union_all(select2).all()

更新:

刚刚在我的一个应用程序上进行了测试:

engine = get_database_engine()
Session = sessionmaker(bind=engine)
session = Session()


qa = session.query(User.id).filter(User.id>=0)
print qa.all() # prints [(3,), (4,)]

qb = session.query(Country.id).filter(Country.id>=0)
print qb.all() # prints [(4,), (5,), (6,), (1,)]

print qa.union_all(qb).all() # prints [(3,), (4,), (4,), (5,), (6,), (1,)]

print qa.union_all(qb)

打印的实际查询:

SELECT anon_1.user_id AS anon_1_user_id 
FROM (SELECT "user".id AS user_id
FROM "user"
WHERE "user".id >= %(id_1)s

UNION ALL

SELECT country.id AS country_id
FROM country
WHERE country.id >= %(id_2)s) AS anon_1

关于python - 炼金术。如何查询两个模型的结果列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17353969/

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