Django只选择具有重复字段值的行

编程入门 行业动态 更新时间:2024-10-25 12:16:43
本文介绍了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 最接近.问题是这将返回一个只有 name 和 count 的 ValuesQuerySet.但是,您可以使用它来构造一个常规的 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只选择具有重复字段值的行

本文发布于:2023-10-26 21:58:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531467.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!