SQLAlchemy - How can I make eager loading count property

后端 未结 2 999
北荒
北荒 2021-02-15 02:11

I want to make a property for model which contains count.

Since I always need the property, I want to make query with JOIN like sqlalchemy.orm.relatio

2条回答
  •  伪装坚强ぢ
    2021-02-15 03:12

    I solved it by using sqlalchemy.orm.column_property

    I replaced the foo_count by following

    import sqlalchemy as s, func, select
    from sqlalchemy.orm import relationship, column_property
    
    # ...
    
    class Foo(Base):
        __tablename__ = 'foo'
        id = s.Column(s.Integer, primary_key=True)
        bar_id = s.Column(s.Integer, s.ForeignKey('bar.id'))
        bar = relationship('Bar')
    
    
    class Bar(Base):
        __tablename__ = 'bar'
        id = s.Column(s.Integer, primary_key=True)
    
        foo_count = column_property(
            select([func.count(Foo.id)])
            .where(Foo.bar_id == id)
        )
    

提交回复
热议问题