Django order_by()过滤器具有distinct() [英] Django order_by() filter with distinct()

查看:219
本文介绍了Django order_by()过滤器具有distinct()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何制作这样的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") 搜索产品" ...

SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("search_vendor"."name") "search_product"...

推荐答案

基于您的错误消息和另一个问题,在我看来这将解决该问题:

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.

这篇关于Django order_by()过滤器具有distinct()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆