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