开发者

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 ha开发者_StackOverflow社区ve 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜