如何使用两个日期字段订购查询集?

时间:2014-02-11 16:22:27

标签: django django-queryset

我恢复了模特:

class Article (models.Model):
    text = models.CharField(max_length=1500)
    creation_date = models.DateTimeField(auto_now_add=True)

class Comment (models.Model):
    text = models.CharField(max_length=500)
    article = models.ForeignKey(Article,related_name='comments')
    creation_date = models.DateTimeField(auto_now_add=True)

所以我想要的是使用展位日期订购我的文章。

如果我有:

Article1.creation_date= 01/01/2014
Article2.creation_date= 01/15/2014
Article3.creation_date= 01/20/2014

(from Article1) Comment1.creation_date= 01/30/2014
(from Article2) Comment2.creation_date= 01/16/2014

* dates are datetimes but for the example...

所需的顺序将是(最新的):

第1条,第3条,第2条

所以,我想要的是按最新订购文章,但考虑他们的评论日期时间。

使用:

Article.objects.all().order_by("-creation_date", "-comments__creation_date")

我得不到我需要的东西。

1 个答案:

答案 0 :(得分:0)

我认为实现这一目标的最佳方法是在模型中添加一个函数,该函数接受文章创建日期,然后将该日期与最新评论进行比较并返回最新日期,然后按该字段排序

def date(self):
    newest_comment = Comment.objects.filter(article=self).order_by(-creation_date)[0].creation_date
    if newest_comment > self.creation_date:
        return newest_comment
    else:
        return self.creation_date
last_edit = date(self)

然后,您可以通过使用Article1.last_edit

的查询集访问该日期
相关问题