假设我们在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仅选择具有重复字段值的行
发布评论