SQLAlchemy的。如何查询结果列表中的两个模型?

时间:2013-06-27 22:01:16

标签: python sqlalchemy

有模特。

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选择单个查询A和B(属性CMixin)< = 5? 这件事         db.session.query(???)。filter(A.x< = 5,B.x< = 5).all()         A和B对象的结果列表 或者是不可能的,只需添加 两个查询的结果?

1 个答案:

答案 0 :(得分:1)

尝试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