Skip to content

Instantly share code, notes, and snippets.

@kangfend
Forked from victorono/remove_duplicates.py
Created January 7, 2020 05:32
Show Gist options
  • Select an option

  • Save kangfend/351083ee29a1d2c53f8340a36a0b965f to your computer and use it in GitHub Desktop.

Select an option

Save kangfend/351083ee29a1d2c53f8340a36a0b965f to your computer and use it in GitHub Desktop.
Django - remove duplicate objects where there is more than one field to compare
unique_fields = ['field_1', 'field_2']
duplicates = (
MyModel.objects.values(*unique_fields)
.order_by()
.annotate(max_id=models.Max('id'), count_id=models.Count('id'))
.filter(count_id__gt=1)
)
for duplicate in duplicates:
(
MyModel.objects
.filter(**{x: duplicate[x] for x in unique_fields})
.exclude(id=duplicate['max_id'])
.delete()
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment