Skip to content

Instantly share code, notes, and snippets.

View cammygames's full-sized avatar

Cameron Chilton cammygames

View GitHub Profile
@Bastien-Brd
Bastien-Brd / django_find_duplicate_objects.py
Created October 14, 2016 09:41
Django - ORM - Find duplicate objects based on a specific field
"""
Suppose you have a django model called MyModel with a field called 'name'.
If for some reason you did not set a "unique" constraint on that field but would still like to avoid duplicate objects with teh same name,
here is how to find all the duplicate objects based on that "name" field.
"""
duplicate_names = MyModel.objects.values('name', 'id').annotate(Count('name')).order_by().filter(name__count__gt=1)
# You can then retrieve all these duplicate objects using this query:
duplicate_objects = MyModel.objects.filter(id__in=[item['id'] for item in duplicate_names])