Filtering the Aggregate in the Django ORM

后端 未结 5 849
误落风尘
误落风尘 2021-02-08 14:49

I have a function that looks like this:

def post_count(self):
        return self.thread_set.aggregate(num_posts=Count(\'post\'))[\'num_posts\']
<
5条回答
  •  执笔经年
    2021-02-08 15:20

    Yes. Just do it. This should work as expected:

    self.thread_set.filter(active_status=1).aggregate(num_posts=Count('post'))['num_posts']
    

    Any original query returns a QuerySet, so any available methods that return QuerySets can be can be pretty much indefinitely chained together for complex criteria matches. Since aggregate() does not return a QuerySet, you want to make sure that it is last in the chain.

提交回复
热议问题