user8359
user8359

Reputation:

How can I use conditional sorting at Django queries?

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?

Upvotes: 0

Views: 126

Answers (1)

Brandon Henry
Brandon Henry

Reputation: 3720

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.

Upvotes: 1

Related Questions