Skip to content
cristen jones edited this page Jun 22, 2015 · 1 revision

Random tricks.

Delete existing duplicate entries

#delete any existing duplicate records
import Count
from survey.models import Commutersurvey

unique_fields = ['email', 'wr_day_month']

duplicates = (Commutersurvey.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:
    (Commutersurvey.objects.filter(**{x: duplicate[x] for x in unique_fields})
                    .exclude(id=duplicate['max_id'])
                    .delete())
Clone this wiki locally