Home >Database >Mysql Tutorial >How to Select Rows with Duplicate Field Values in Django?

How to Select Rows with Duplicate Field Values in Django?

Susan Sarandon
Susan SarandonOriginal
2025-01-04 11:09:35753browse

How to Select Rows with Duplicate Field Values in Django?

Selecting Rows with Duplicate Field Values in Django

To select all rows from a model that have at least one duplicate value for a given field, you can use a combination of Django's aggregation and filtering capabilities:

  1. Aggregate values: Use the annotate() method to calculate the count of duplicate values for the specified field. For example, for a model with a name field:
from django.db.models import Count
dupes = Literal.objects.values('name').annotate(id_count=Count('id'))
  1. Filter based on count: Use the filter() method to select rows where the count exceeds 1. This will return a ValuesQuerySet containing the duplicated values:
dupes = dupes.filter(id_count__gt=1)
  1. Fetch complete records: To obtain the complete records, use the in filter to select rows where the name field matches the duplicated values:
dupes = Literal.objects.filter(name__in=[item['name'] for item in dupes])

Alternative SQL Solution:

If preferred, you can also use a subquery to achieve the same result:

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

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

Statement:
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