Skip to content

Instantly share code, notes, and snippets.

@sandiprb
Forked from victorono/remove_duplicates.py
Created April 15, 2021 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sandiprb/a97cef2c610ab1e9409666ce587ccc9b to your computer and use it in GitHub Desktop.
Save sandiprb/a97cef2c610ab1e9409666ce587ccc9b to your computer and use it in GitHub Desktop.
Django - remove duplicate objects where there is more than one field to compare
from django.db.models import Count, Max
unique_fields = ['field_1', 'field_2']
duplicates = (
MyModel.objects.values(*unique_fields)
.order_by()
.annotate(max_id=Max('id'), count_id=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