from sqlalchemy_utils import aggregated
class Thread(Base):
__tablename__ = 'thread'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.Unicode(255))
@aggregated('comments', sa.Column(sa.Integer))
def comment_count(self):
return sa.func.count('1')
comments = sa.orm.relationship(
'Comment',
backref='thread'
)
class Comment(Base):
__tablename__ = 'comment'
id = sa.Column(sa.Integer, primary_key=True)
content = sa.Column(sa.UnicodeText)
thread_id = sa.Column(sa.Integer, sa.ForeignKey(Thread.id))
active = sa.Column(sa.Boolean)
我希望
comment_count
字段仅统计活跃评论,而不是所有评论。可以吗?
该示例基于文档:https://sqlalchemy-utils.readthedocs.io/en/latest/aggregates.html
您需要 declerative_base 和 sa 才能执行此操作,您可以在此处找到有关它们的更多信息。
from sqlalchemy_utils import aggregated
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Thread(Base):
__tablename__ = 'thread'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.Unicode(255))
@aggregated('comments', sa.Column(sa.Integer))
def comment_count(self):
return sa.func.count(sa.case([(Comment.active == True, 1)]))
comments = sa.orm.relationship(
'Comment',
backref='thread'
)
class Comment(Base):
__tablename__ = 'comment'
id = sa.Column(sa.Integer, primary_key=True)
content = sa.Column(sa.UnicodeText)
thread_id = sa.Column(sa.Integer, sa.ForeignKey(Thread.id))
active = sa.Column(sa.Boolean)
1- sa.case([(Comment.active == True, 1)]) 创建一个 case 语句,如果评论处于活动状态,则返回 1,否则返回 NULL。
然后,2-sa.func.count 仅计算 case 语句返回 1 的行,从而有效地仅计算活动评论。 这应该为您提供 comment_count 作为与每个线程关联的活动评论的数量。