Skip to content

Instantly share code, notes, and snippets.

@balazs-endresz
Last active August 29, 2015 14:01
Show Gist options
  • Save balazs-endresz/dd31cc5e2dee45829e72 to your computer and use it in GitHub Desktop.
Save balazs-endresz/dd31cc5e2dee45829e72 to your computer and use it in GitHub Desktop.
Find duplicates in queryset
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