How can I query for count of related models satisfying a predicate? Let’s say I have a model
class Comment(Model):
text = CharField(max_length=100)
parent = ForeignKey('Comment')
created_at = DateTimeField()
and I want to select all comments with count of child comments created after certain date. Something equivalent to 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.*
Is there a way to do it using QuerySet?
1 Answer