Last active
August 29, 2015 14:01
-
-
Save balazs-endresz/dd31cc5e2dee45829e72 to your computer and use it in GitHub Desktop.
Find duplicates in queryset
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db.models import Count | |
def duplicates_by(model, field): | |
values = model.objects\ | |
.values(field)\ | |
.annotate(Count(field))\ | |
.order_by(field)\ | |
.filter(**{'%s__count__gt' % field: 1})\ | |
.values_list(field, flat=True) | |
return model.objects.filter(**{'%s__in' % field: values}).order_by(field) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment