views:

135

answers:

2

I'm working on a blog application in Django. Naturally, I have models set up such that there are Posts and Comments, and a particular Post may have many Comments; thus, Post is a ForeignKey in the Comments model.

Given a Post object, is there an easy way (ideally, through a method call) to find out how many Comments belong to the Post?

+6  A: 
Comments.objects.filter(post=post).count()

or:

post.comment_set.count()
Daniel
the second one is the canonical way.
Javier
A: 

You can add field CommentCount to you Post model, and update it in pre_save, pre_delete signals. It's a hard for the db to calculate comments count at every view call and number of queries will be grow.

Igorekk