1

有模型。

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(Ax <= 5, Bx <= 5).all() 结果列表在 A 和 B 对象或者是不可能做的,只需添加两个的结果查询?

4

1 回答 1

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
于 2013-06-27T22:15:53.937 回答