0

I have comment model that references (foreign key) a post model and there is a boolean field in the post model that tells whether this particular post has any comment or not.

  • What I want to do is to update this boolean field of the post whenever a comment is made on that post, for this what do I have to do in the view.

  • Also when I show all the posts on a page, I want to show those first which do not have any comment, so that people can comment on them.

How can I effectively do the following two things

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sachin
  • 3,672
  • 9
  • 55
  • 96

1 Answers1

1

You could use the comment_was_posted signal to update the associated Post once there is a new comment. See this thread to get the general idea: Django notification on comment submission

Although it might be better in this case to create a count_comments() method on your Post model.

To order and filter your Posts by the number of Comments for a given Post check Django's docs on aggregation or this blog post: http://agiliq.com/blog/2009/08/django-aggregation-tutorial/

Community
  • 1
  • 1
arie
  • 18,737
  • 5
  • 70
  • 76
  • Actually I am not using django comments, I have made something similar I needed to do a lot of changes and didn't require all the features provided by django comments hence did not use it... So the point is now since I cannot use comment_was_posted signal what else can I do?? Can't I define something in the comments models, such that when a user posts a comment change can be made in the Post object as referenced by the foreign key – Sachin Nov 12 '11 at 14:26
  • Well, the alternative approach would be to override the save-method of your custom comments-app. Check this for some general info on this topic: http://www.martin-geber.com/thought/2007/10/29/django-signals-vs-custom-save-method/ – arie Nov 12 '11 at 14:33
  • The link that you have given tells me where I can write code for pre and post save but what I want to know how can I refer the parent model in the comments model by making use of the foreign key I have? I hope I have made by question clear? – Sachin Nov 12 '11 at 14:53
  • Hm ... in the save-method you can refer to your model's fields with 'self'. self.title would refer to the title of your current instance / comment. If your comment class has an FK 'post' you can therefore access the related instance with self.post – arie Nov 12 '11 at 15:21