views:

33

answers:

1

I'm implementing a basic forum app. I would like to sort the questions by their last reply time. I have the following line:

    questions = Question.objects.filter(deleted=False).order_by("last_comment__created_at")

However, this query ignores the new questions with no answers. What would be the best way to fix this without creating a new field at Question model?

+1  A: 

in your Question model, add a datetimefield called last_update. Then place a timestamp in there when the question is created, and also update self.question.last_update in the comment save method as well. that way you can sort by:

    questions = Question.objects.filter(deleted=False).order_by("-last_update")

the - means newer will be first in the queryset.

Brandon H
Thanks for the answer. As I mentioned in the question, I'm trying to do this without modifying the Question model.
Boolean
whoops. guess i missed that part. can you add a method instead of a field? although it would be slower, you could query all the Question objects and then use the sorted() function with a lambda. i'll keep thinking about this one, but really i think the best way involves modifying the model.
Brandon H