【问题标题】:Django complex orderingDjango 复杂排序
【发布时间】:2014-06-01 19:43:52
【问题描述】:

我有一个 Django 模型 Document,它可以有 Vote 指向它的对象。 Vote 上有一个整数字段,名为 score

我想根据指向文档的Vote 对象和score=1 的数量来订购文档查询集。即,获得最多赞成票的文档应该是查询集中的第一个。

Django 可以吗?怎么样?

【问题讨论】:

  • 我猜你的意思是score=1
  • @DanielRoseman 正确,已修复。

标签: python django orm


【解决方案1】:

这是一个注释工作。

from django.db.models import Count
Document.objects.filter(score=1).annotate(
             positive_votes=Count('vote__count')).order_by('positive_votes')

编辑

没有过滤就没有办法做到这一点,因为这是底层数据库操作的工作方式。但是一种不太好的方法是对原始文档中未包含的所有文档进行单独查询,并将两个查询集链接在一起:

positive_docs = <query from above>
other_docs = Document.objects.exclude(id__in=positive_docs)
all_docs = itertools.chain(positive_docs, other_docs)

只要您没有数百万个文档,这将起作用,但会破坏分页等内容。

【讨论】:

  • 这是有道理的,但是我们可以在不过滤Document 对象的情况下做到这一点吗?我也想看看没有投票的文件。
  • 漂亮,上面加糖吗?
【解决方案2】:

我是这样做的(在QuerySet 模型上):

def order_by_score(self):
    q = django.db.models.Q(ratings__score=1)
    documents_with_one_positive_rating = self.filter(q) # Annotation sees only
                                                        # the positive ratings
    documents_without_one_positive_rating = self.filter(~q)

    return (documents_with_one_positive_rating |
            documents_without_one_positive_rating).annotate(
                db_score=django.db.models.Count('ratings')
                ).order_by('-db_score')

优点是它仍然显示没有正面评价的文档。

【讨论】:

    猜你喜欢
    • 2010-12-30
    • 2018-01-16
    • 2012-08-13
    • 1970-01-01
    • 2014-06-30
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多