Home > Database > Mysql Tutorial > How to Find Rows with Duplicate Field Values Using Django ORM?

How to Find Rows with Duplicate Field Values Using Django ORM?

Linda Hamilton
Release: 2025-01-05 08:42:41
Original
758 people have browsed it

How to Find Rows with Duplicate Field Values Using Django ORM?

Django Query for Rows with Duplicate Field Values

Suppose we have a Django model with a non-unique field. We need to select all rows from the model that have at least one duplicate value for that field.

Plain SQL Approach

One possible solution is to use plain SQL:

SELECT *
FROM literal
WHERE name IN (
    SELECT name
    FROM literal
    GROUP BY name
    HAVING COUNT(*) > 1
);
Copy after login

Django ORM Approach

Using Django's ORM, we can achieve the same result with a combination of values(), annotate(), order_by(), and filter():

from django.db.models import Count

dupes = Literal.objects.values('name') \
                    .annotate(Count('id')) \
                    .order_by() \
                    .filter(id__count__gt=1)
Copy after login

As the above code returns a ValuesQuerySet, we need to convert it to a regular QuerySet to use it as a filter:

duplicates = Literal.objects.filter(name__in=[item['name'] for item in dupes])
Copy after login

This approach ensures that we only select rows with duplicate name values.

The above is the detailed content of How to Find Rows with Duplicate Field Values Using Django ORM?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template