2014-02-11 66 views
0

我的恢复模式:如何使用两个日期字段来订购查询集?

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... 

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

第一条,第三条,第二条

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

有:

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

我不明白我需要什么。

+0

会发生什么事,当你交换他们在查询与Article1.last_edit设置访问日期? '.order_by(“ - comments__creation_date”,“-creation_date”)' – ptr

+1

http://stackoverflow.com/questions/9512241/django-order-by-foreignkey-set-models – arocks

+0

@PeteTinkler如果我这样做,没有意识的文章到最后。 – Viroide

回答

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) 

然后你就可以通过

+0

我不能做last_edit = date(self)=> NameError:name'self'未定义 – Viroide