Login

Auto-rename duplicate fields

Author:
christian.oudard
Posted:
August 25, 2009
Language:
Python
Version:
1.1
Tags:
rename duplicate south unique-key
Score:
0 (after 0 ratings)

This is useful to run before you add a unique key to a character field that has duplicates in it. It just adds numbers to the end of the contents, so they will be unique.

It takes a model class and a field name. The model class can be a South fake orm object, so this can be used inside data migrations.

 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 7 years, 11 months ago
  2. Automate unique slugs by taojian 7 years, 6 months ago
  3. uuid model field by newspire 6 years, 6 months ago
  4. Duplicate related objects of model instance by johnboxall 6 years, 5 months ago
  5. True Unique Boolean Model Decorator by kunitoki 3 years, 1 month ago

Comments

Please login first before commenting.