2017-09-18 76 views
0

嗯,我想3次:如何更改排序一個ListView的

  1. 顯示圖片與highes排名第一(最佳視圖)
  2. 顯示最新照片第一個(新的視圖)
  3. 秀(趨勢)

我的HTML和視圖正在工作,但我的排序dosn't。 這是我嘗試過的。

我views.py:

class FreshList(SelectRelatedMixin, generic.ListView): 
    model = models.Post.objects.order_by('-created_at') 
    select_related = ("user", "group") 

class BestList(SelectRelatedMixin, generic.ListView): 
    model = models.Post.objects.order_by('ranking') 
    select_related = ("user", "group") 

class TrendingList(SelectRelatedMixin, generic.ListView): 
    model = models.Post.objects.order_by('-created_at','ranking') 
    select_related = ("user", "group") 

這裏是我的models.py:

class Post(models.Model): 
    created_at = models.DateTimeField(auto_now=True) 
    title = models.CharField(max_length=30,default='Titel') 
    bild = models.ImageField(upload_to='images', default='/static/img/Weramemesicon.png') 
    ranking = models.IntegerField(default = 0) 

這是它在Github上,也許它可以幫助:https://github.com/TheOneWayTruth/Weramemes

+0

何不一種觀點認爲這需要其改變排列順序可選參數? –

+0

(另外 - 當定義相同的類名稱兩次 - 你期望發生什麼?) –

+0

這些是我嘗試的方法,而不是我的代碼 –

回答

-1

你可以嘗試ordering

class FreshList(SelectRelatedMixin, generic.ListView): 
    model = models.Post 
    select_related = ("user", "group") 

    ordering = ['-created_at'] 
+0

AttributeError在/ posts /'QuerySet'對象沒有屬性'_default_manager' –

+0

嘗試更新答案 –

0

你需要重寫的ListView的get_ordering()方法,並留下model = models.Postmodel

例如:

class FreshList(SelectRelatedMixin, generic.ListView): 
    model = models.Post 
    select_related = ("user", "group") 

    def get_ordering(self): 
     return "-created_at" 
1

使用queryset在你的列表視圖,而不是model

class FreshList(SelectRelatedMixin, generic.ListView): 
    queryset = models.Post.objects.order_by('-created_at') 

class BestList(SelectRelatedMixin, generic.ListView): 
    queryset = models.Post.objects.order_by('ranking') 

class TrendingList(SelectRelatedMixin, generic.ListView): 
    queryset = models.Post.objects.order_by('-created_at','ranking') 

下面是解釋爲什麼model它不與order_by

指定模型=發佈者實際上只是簡寫爲 queryset = Publisher.objects.all()。

Here you can read rest of Django documentation about model and queryset

Source CCBV ListView

相關問題