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:
from django.db.models import Count dupes = Literal.objects.values('name').annotate(id_count=Count('id'))
dupes = dupes.filter(id_count__gt=1)
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!