Generate sql with subquery as a column in select statement using SQLAlchemy

后端 未结 2 1097
太阳男子
太阳男子 2020-11-30 13:55

Is there a way to make SQLAlchemy generate a query with a custom column that is a subquery that correlates with current row:

SELECT
 tab1.id,
 tab1.col1, 
 .         


        
2条回答
  •  渐次进展
    2020-11-30 14:18

    You can do this, but it works in a quite different way to how you have written it. You can create a property of Tab1 which depends on the relationship to tab2 (assuming that tab2.tab1_id is a foreign key, which it should be.

    Your models look like this:

    class Parent(Base):
        __tablename__ = 'parent'
        id = Column(Integer, primary_key=True)
        children = relationship("Child")
    
    class Child(Base):
        __tablename__ = 'child'
        id = Column(Integer, primary_key=True)
        parent_id = Column(Integer, ForeignKey('parent.id'))
    

    as per the docs on relationships

    Then you can add something like

    @hybrid_property
    def number_of_children(self):
        if self.children:
            return len(self.children)
        return 0
    
    @number_of_children.expression
    def number_of_children(cls):
        return (select([func.count(Child.id)])
                .where(Child.cover_id == cls.id))
    

    to the Parent model, as per this answer and more docs.

    Once you've done this, you can filter on this property the same as any other column-based one.

提交回复
热议问题