【问题标题】:Django: Ordering Queryset with a specific filtered fieldDjango:使用特定过滤字段排序查询集
【发布时间】:2012-10-05 12:43:05
【问题描述】:

我需要对项目查询集进行排序,引入过时的内容。 (内容是与 Item 类相关的多对多)。 是否可以通过注释中的 pub_date 过滤内容?

我的代码适用于每个内容发布日期。我需要 annotate 函数来处理“pub_date > '2012-10-10'”(例如)。

self.queryset = Item.objects.all()    
self.queryset = self.queryset.annotate(
                Count("content")).order_by("-content__count")

我尝试使用 extra() 函数进行过滤,但不起作用:

self.queryset = self.queryset.extra(select={
'content': "pub_date > '2012-10-10'"}).annotate(
Count("content")).order_by("-content__count")

【问题讨论】:

    标签: django sorting django-queryset annotate


    【解决方案1】:

    你可以只过滤然后注释。

    self.queryset = Items.objetct.filter(content__pub_date__gt = '2012-10-10')
    self.queryset = self.queryset.annotate(
        Count("content")).order_by("-content__count")
    

    假设您的模型看起来像这样

    class Content(models.Model):
        pub_date = models.DateTimeField()
    
        def __unicode__(self):
            return "%s" % self.id
    
    class Item(models.Model):
        content = models.ManyToManyField(Content)
    
        def __unicode__(self):
            return "%s" % self.id
    

    在我的测试中,我添加了 3 个内容和两个项目。 id 为 1 的项目通过内容多对多与 id 为 1 的内容建立关系。 id 为 2 的项目通过内容多对多与 id 为 2 和 3 的内容建立关系。

    >>> Item.objects.filter(
            content__pub_date__gt ='2012-10-10').annotate(
            Count("content")).order_by("-content__count")
    >>> [<Item: 2>, <Item: 1>]
    

    正如预期的那样。

    【讨论】:

    • 好的,但我的问题有点不同。我想按 pub_date 过滤内容,然后按 content__count 对项目进行排序
    • 对不起,我不明白你的意思。使用我的代码,您可以按 pub_date 过滤,然后按 content__count 排序。我错过了什么吗?
    • Content 和 Item 是具有多对多关系的 2 个不同的类。所以他们的过滤方式不同。
    • @guillaumekal 我编辑原始答案以向您展示它是如何工作的。我认为这是正确的。
    猜你喜欢
    • 2020-08-16
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 2010-12-11
    • 2015-05-06
    • 2012-12-20
    • 2016-07-01
    相关资源
    最近更新 更多