def rename_dupes(model, field_name): """ Rename duplicate character fields, by adding numbers to duplicates. example: contents2, contents3, etc. """ changed = set() for obj in model.objects.all(): value = getattr(obj, field_name) duplicates = model.objects.filter(**{field_name: value}).exclude(pk=obj.pk) for i, dupe in enumerate(duplicates): if dupe.pk in changed: continue changed.add(obj.pk) changed.add(dupe.pk) print 'Fixing duplicate %s.%s:' % (obj.__class__.__name__, field_name), obj.pk, obj.name, '-', dupe.pk, dupe.name setattr(dupe, field_name, value + str(i+2)) dupe.save()