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. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.