去重复数据。
仅在 PostgreSQL 上,可以传递位置参数(*fields),以指定DISTINCT应适用的字段名称。
这相当于一个SELECTDISTINCTON的 SQL 查询。
这其中的区别是,对于普通的distinct()调用,数据库在确定哪些行是不同的时候,会比较每行中的每个字段。
对于带有指定字段名的distinct()调用,数据库将只比较指定的字段名。
若指定order_by:distinct的字段,必须包含在order_by中,且为order_by的先头字段。
单独写distinct,则不受限制。
theDISTINCT ONexpression(s) must match the leftmostORDER BYexpression(s).
report_list = OrderReport.objects.select_related('appl') \
.prefetch_related('appl__pl_set') \
.filter(conds).all().distinct('appl_id', 'id').order_by('-appl_id', '-id')
# 以下写法 OK
.filter(conds).all().distinct('appl_id').order_by('-appl_id', '-id')
.filter(conds).all().distinct('appl_id').order_by('-appl_id')
# 以下写法 NG (必须为order_by的先头)
.filter(conds).all().distinct('id').order_by('-appl_id', '-id')
# order_by: -id = id DESC ,id = id ASC
# 无 order_by OK
.filter(conds).all().distinct('appl_id', 'id')打印SQL log:
# 执行语句
.filter(conds).all().distinct('id').order_by('-id', 'appl_id')
SELECT DISTINCT
ON ("purchase_order"."id") "purchase_order"."id" AS Col1
, "purchase_order"."locked" AS Col2
, "purchase_order"."locked_by" AS Col3
FROM
"purchase_order"
WHERE
"purchase_order"."created_by" = 'admin'
ORDER BY
"purchase_order"."id" DESC
, "purchase_order"."appl_id" ASC
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。