gpt4 book ai didi

django - 使用distinct后如何执行order_by?

转载 作者:行者123 更新时间:2023-12-04 17:44:16 27 4
gpt4 key购买 nike

在基于两个字段获取唯一结果之后,我想对结果进行排序。我遇到的问题是我不能在Django中使用两个ord​​er_by。 Django clears the previous order_by() whenever you use this function.

Each order_by() call will clear any previous ordering.



型号示例:
class Product(models.Model):
price = models.FloatField()
name = models.CharField(max_length=100)
group = models.CharField(max_length=100)

我想得到同一组中价格最低的产品。然后,我想按价格对它们进行排序。像这样的东西:
Product.objects.order_by('group','price').distinct('group').order_by('price')
Product.objects.order_by('group','price').distinct('group').order_by('-price')

问题是,如果仅按一阶使用,我会得到不同的产品。

--

编辑

表示例:
id | name | group | price
0 | aaa | aaa | 10.0
1 | aaa | aaa | 1.0
2 | aaa | aaa | 2.0
3 | aaa | aaa | 1.0
4 | bbb | bbb | 2.0
5 | bbb | bbb | 2.1
6 | bbb | bbb | 10.0

按价格排序:
1  | aaa  | aaa  | 1.0
4 | bbb | bbb | 2.0

按价格排序:
4  | bbb  | bbb  | 2.0
1 | aaa | aaa | 1.0

我的问题是,当我使用order_by进行排序时,返回的产品是不同的。

在sql语句中将是这样的:
SELECT * 
FROM product
WHERE id IN (
SELECT DISTINCT ON
(group) id
FROM product
ORDER BY group ASC, price ASC
)
ORDER BY price DESC

我正在使用PostgreSQL

最佳答案

好的,这是我所做的:

products = Product.objects.order_by('group','price').distinct('group')
result = Product.objects.filter(id__in=products).order_by('-price')

我认为这不是最有效的方法,但是它正在起作用...

关于django - 使用distinct后如何执行order_by?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41700650/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com