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
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)
)