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

编程入门 行业动态 更新时间:2024-10-25 18:27:05
本文介绍了Django仅选择具有重复字段值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

suppose we have a model in django defined as follows:

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

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

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一样接近。问题是这将返回一个 ValuesQuerySet ,只有 name 和 count 。然而,您可以使用它来构建一个常规的 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:59:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531470.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   Django

发布评论

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

>www.elefans.com

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