如何查询满足谓词的相关模型的数量?假设我有一个模型
class Comment(Model):
text = CharField(max_length=100)
parent = ForeignKey('Comment')
created_at = DateTimeField()
我希望选择所有评论,其中包含在特定日期之后创建的子评论数。等同于SQL的东西
select c1.*, count(c2.*) from comments c1
left join comments c2 on c1.id = c2.parent_id and c2.created_at > the_date
group by c1.*
有没有办法使用QuerySet?
答案 0 :(得分:2)
Comment.objects.filter(comment__created_at__gte=the_date).annotate(Count('comment'))