Skip to content

Instantly share code, notes, and snippets.

@martinsam
Created September 26, 2017 16:14
Show Gist options
  • Save martinsam/bdadc856c869da763d52281766d9fb4b to your computer and use it in GitHub Desktop.
Save martinsam/bdadc856c869da763d52281766d9fb4b to your computer and use it in GitHub Desktop.
Delete duplicate entry - Django
from django.db import models
unique_fields = ['company_id', 'applicant_id']
duplicates = (CertificationApplicantCompany.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:
(CertificationApplicantCompany.objects.filter(**{x: duplicate[x] for x in unique_fields})
.exclude(id=duplicate['max_id'])
.delete())
@martinsam
Copy link
Author

martinsam commented Sep 27, 2017

for duplicate in duplicates:
    arguments = {}
    for x in unique_fields:
        arguments[x] = duplicate[x]
    CertificationApplicantCompany.objects.filter(**arguments).exclude(id=duplicate['max_id']).delete()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment