2017-07-29 89 views
1

在這種情況下我不知道該如何處理。可能有人知道。Django按訂單排序

我有2種型號:

評論:

class Comments(models.Model): 
    text = models.CharField(max_length=300, null=False) 
    image = models.FileField(upload_to=user_directory_path_comments, validators=[validate_file_extension], blank=True, null=True) 
    articles = models.ForeignKey(Articles, verbose_name="Article", null=False) 
    author = models.ForeignKey(User, verbose_name="Auteur") 
    in_answer_to = models.ForeignKey('self', verbose_name="En réponse au commentaire", blank=True, null=True, on_delete=models.CASCADE) 
    date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") 
    update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") 

並有高達模型:

class Up(models.Model): 
    comments = models.ForeignKey(Comments, verbose_name="Commentaire", null=True, blank=True) 
    user = models.ForeignKey(User, verbose_name="Auteur", null=False) 

用戶可以添加評論,他們可以 「向上」 一些有用的意見。

所以,默認情況下,我想按日期排序評論。不過,我想通過Up的數量優先順序。

爲了給你一個想法,意見和高達如何註冊,這是我的數據庫的截圖:

評論: enter image description here

最多: enter image description here

例如,評論哪裏id是50有2個來自兩個不同的用戶。所以它應該在列表的頂部,而評論49只有1張。

現在,我只是用按日期順序,我需要通過向上的順序:

comments = Comments.objects.all().exclude(in_answer_to__isnull=False).order_by('-date') 

我需要這樣的東西:

comments = Comments.objects.all().exclude(in_answer_to__isnull=False).order_by('-date', 'Up') 
+2

你見過[按外鍵字段計數](https://stackoverflow.com/a/2501178/4974980)? –

+1

我不知道這件事。 – GrandGTO

+1

可能重複的[按外鍵字段計數?](https://stackoverflow.com/questions/2501149/order-by-count-of-a-foreignkey-field) –

回答

1

正如你想想SQL以下訂單問題,你會發現,你可能需要計算引用物體的數量

所以註釋計數和它的順序

comments = Video.objects.all().exclude(
    in_answer_to__isnull=False 
).annotate(
    num_up=Count('up') 
).order_by('-date', 'num_up') 
+0

謝謝,就是這樣的。 – GrandGTO