【问题标题】:Recent entries from each category in django modeldjango 模型中每个类别的最新条目
【发布时间】:2017-01-17 08:36:59
【问题描述】:

我需要在模板中显示每个类别的最新条目是 Instarama、Facebook、Twitter。这是我的解决方案,但它不起作用。

我的 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']

【问题讨论】:

  • 什么不起作用?
  • @arcegk 我收到所有帖子或一个帖子,但我需要每个社交频道的最后一个帖子
  • 你试过循环吗?
  • @cycle?这是什么?
  • forloop for i in ....

标签: python django model django-queryset categories


【解决方案1】:
def get_queryset(self):
    super(OnlineManager, self).get_queryset().filter(is_online=True).order_by('- id')annotate(Count('social_channel'))[‌​0]

【讨论】:

  • 解释一下就好了。
【解决方案2】:

试试这个:

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 的最新条目

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-18
    • 2011-02-04
    • 2014-11-18
    • 2016-02-20
    • 2015-08-02
    • 2010-11-29
    • 2019-01-17
    相关资源
    最近更新 更多