2014-02-11 64 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