问题描述
我怎样才能制作这样的 order_by
....
How can I make an order_by
like this ....
p = Product.objects.filter(vendornumber='403516006')
.order_by('-created').distinct('vendor__name')
问题是我有多个同名供应商,我只想要供应商的最新产品..
The problem is that I have multiple vendors with the same name, and I only want the latest product by the vendor ..
希望它有意义吗?
我收到此数据库错误:
SELECT DISTINCT ON 表达式必须匹配初始 ORDER BY 表达式第 1 行:SELECT DISTINCT ON ("search_vendor"."name")搜索产品"...
推荐答案
根据您的错误消息和 另一个问题,在我看来这可以解决它:
Based on your error message and this other question, it seems to me this would fix it:
p = Product.objects.filter(vendornumber='403516006')
.order_by('vendor__name', '-created').distinct('vendor__name')
也就是说,DISTINCT ON
表达式似乎必须匹配最左边的 ORDER BY
表达式.因此,通过将您在 distinct
中使用的列作为 order_by
中的第一列,我认为它应该可以工作.
That is, it seems that the DISTINCT ON
expression(s) must match the leftmost ORDER BY
expression(s). So by making the column you use in distinct
as the first column in the order_by
, I think it should work.
这篇关于带有 distinct() 的 Django order_by() 过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!