Auto-rename duplicate fields

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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()

More like this

  1. DRY with common model fields (another way) by jmrbcu 6 years, 9 months ago
  2. Automate unique slugs by taojian 6 years, 4 months ago
  3. uuid model field by newspire 5 years, 3 months ago
  4. Duplicate related objects of model instance by johnboxall 5 years, 3 months ago
  5. True Unique Boolean Model Decorator by kunitoki 1 year, 11 months ago

Comments

(Forgotten your password?)