Login

Auto-rename duplicate fields

Author:
christian.oudard
Posted:
August 25, 2009
Language:
Python
Version:
1.1
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. Generate and render HTML Table by LLyaudet 5 days, 9 hours ago
  2. My firs Snippets by GutemaG 1 week, 1 day ago
  3. FileField having auto upload_to path by junaidmgithub 1 month, 2 weeks ago
  4. LazyPrimaryKeyRelatedField by LLyaudet 1 month, 3 weeks ago
  5. CacheInDictManager by LLyaudet 1 month, 3 weeks ago

Comments

Please login first before commenting.