Django只选择具有重复字段值的行 [英] Django select only rows with duplicate field values

查看:26
本文介绍了Django只选择具有重复字段值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们在 django 中有一个模型定义如下:

suppose we have a model in django defined as follows:

class Literal:
    name = models.CharField(...)
    ...

名称字段不是唯一的,因此可以有重复的值.我需要完成以下任务:选择模型中name 字段具有至少一个重复值的所有行.

Name field is not unique, and thus can have duplicate values. I need to accomplish the following task: Select all rows from the model that have at least one duplicate value of the name field.

我知道如何使用普通 SQL 来实现(可能不是最好的解决方案):

I know how to do it using plain SQL (may be not the best solution):

select * from literal where name IN (
    select name from literal group by name having count((name)) > 1
);

那么,是否可以使用 django ORM 来选择它?或者更好的 SQL 解决方案?

So, is it possible to select this using django ORM? Or better SQL solution?

推荐答案

尝试:

from django.db.models import Count
Literal.objects.values('name')
               .annotate(Count('id')) 
               .order_by()
               .filter(id__count__gt=1)

这与 Django 最接近.问题是这将返回一个只有 namecountValuesQuerySet.但是,您可以使用它来构造一个常规的 QuerySet,方法是将它反馈给另一个查询:

This is as close as you can get with Django. The problem is that this will return a ValuesQuerySet with only name and count. However, you can then use this to construct a regular QuerySet by feeding it back into another query:

dupes = Literal.objects.values('name')
                       .annotate(Count('id'))
                       .order_by()
                       .filter(id__count__gt=1)
Literal.objects.filter(name__in=[item['name'] for item in dupes])

这篇关于Django只选择具有重复字段值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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