2016-09-09 35 views
3

我需要在模板中顯示來自每個類別的最新條目是Instarama,Facebook,Twitter。在這裏我的解決方案,但它不起作用。django模型中每個類別的最近條目

我get_queryset方法,但不工作:

def get_queryset(self): 
    return super(OnlineManager, self).get_queryset().filter(is_online=True).order_by('-date').annotate(Count('social_channel'))[:1] 

這是我的模型:

class Social(models.Model): 
    social_channel = models.CharField(max_length=25, choices=SOCIAL_CHANNELS, 
             default=SOCIAL_CHANNELS[0][0], blank=True) 
    text = models.TextField(max_length=5000, blank=True, default='') 
    is_online = models.BooleanField(default=True) 
    position = models.PositiveIntegerField(default=0) 
    date = models.DateTimeField(auto_now_add=True) 

    def __str__(self): 
     return self.social_channel 

    class Meta: 
     ordering = ['position'] 
+0

什麼不起作用? – arcegk

+0

@arcegk我得到的所有文章或一個,但我需要每個社交頻道 –

+0

最後一篇文章,你嘗試了一個循環? – arcegk

回答

1
def get_queryset(self): 
    super(OnlineManager, self).get_queryset().filter(is_online=True).order_by('- id')annotate(Count('social_channel'))[‌​0] 
+1

解釋會很好。 – IanS

0

試試這個:

def get_queryset(self): 
    query = super(OnlineManager, self).get_queryset() 
    query = query.filter(is_online=True).order_by('social_channel', '-id').distinct('social_channel') 
    return query 

它應該返回最最近的每個social_chanel

相關問題