Django:在外键上是不同的,然后排序

2024-09-30 14:23:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个模型,Track和{}。每个Pair都有一个track1track2和{}。我试图通过对的流行程度(降序)得到一个有序列表,没有两个对具有相同的track1。以下是我目前所做的尝试:

lstPairs = Pair.objects.order_by('-popularity','track1__id').distinct('track1__id')[:iNumPairs].values_list('track1__id', 'track2__id', 'popularity')

这给了我以下错误:

^{pr2}$

……所以我试了一下:

lstPairs = Pair.objects.order_by('-popularity','track1__id').distinct('popularity', 'track1__id')[:iNumPairs].values_list('track1__id', 'track2__id', 'popularity')

这给了我重复的track1__ids的条目。有人知道解决这个问题的方法吗?我想我将不得不使用raw()或类似的东西,但我不知道如何处理这样的问题。我使用PostgreSQL作为数据库后端,因此DISTINCT应该受到支持。在


Tags: 模型idbyobjectsordertracklistvalues
2条回答

参见documentation on distinct。在

第一个:

On PostgreSQL only, you can pass positional arguments (*fields) in order to specify the names of fields to which the DISTINCT should apply.

你不能指定什么是你的数据库后端,如果它不是PostrgreSQL你就没有机会让它工作。在

第二:

When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.

我认为您应该使用raw(),或者获取按流行程度排序的完整对列表,然后在Python中按track1唯一性进行过滤。在

首先,让我们澄清一下:DISTINCT是标准SQL,而{}是PostgreSQL扩展。在

错误(DISTINCT ON expressions must match initial ORDER BY expressions)表示,您应该修复ORDER BY子句,而不是DISTINT ON(如果这样做,您将得到不同的结果,就像您已经经历过的那样)。在

The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s). The ORDER BY clause will normally contain additional expression(s) that determine the desired precedence of rows within each DISTINCT ON group.

这将为您提供预期结果:

lstPairs = Pair.objects.order_by('track1__id','-popularity').distinct('track1__id')[:iNumPairs].values_list('track1__id', 'track2__id', 'popularity')

在SQL中:

^{pr2}$

可能是顺序错误。

如果您想要原始订单,可以在此处使用子查询:

SELECT *
FROM (
  SELECT DISTINCT ON (track1__id) track1__id, track2__id, popularity
  FROM pairs
  ORDER BY track1__id
    LIMIT here, if necessary
)
ORDER BY popularity DESC, track1__id

相关问题 更多 >