4

我想根据不区分大小写的字段值获取所有重复项。

基本上是重写这个 SQL 查询

SELECT count(*), lower(name)
FROM manufacturer
GROUP BY lower(name)
HAVING count(*) > 1;

使用 Django ORM。我希望这样的事情可以解决问题

from django.db.models import Count
from django.db.models.functions import Lower

from myapp.models import Manufacturer


qs = Manufacturer.objects.annotate(
    name_lower=Lower('name'),
    cnt=Count('name_lower')
).filter('cnt__gt'=1)

但当然它没有用。

知道怎么做吗?

4

1 回答 1

9

你可以试试:

qs = Manufacturer.objects.annotate(lname=Lower('name')
     ).values('lname').annotate(cnt=Count(Lower('name'))
     ).values('lname', 'cnt').filter(cnt__gt=1).order_by('lname', 'cnt')

为什么要添加order_by ordering-or-order-by

sql 查询如下所示:

SELECT 
    LOWER("products_manufacturer"."name") AS "lname",
    COUNT(LOWER("products_manufacturer"."name")) AS "cnt"
FROM "products_manufacturer"
GROUP BY LOWER("products_manufacturer"."name")
HAVING COUNT(LOWER("products_manufacturer"."name")) > 1
ORDER BY "lname" ASC, "cnt" ASC
于 2017-10-25T14:01:44.720 回答