Last active
August 28, 2015 01:56
-
-
Save lukas-hetzenecker/5a12c7c91d3bac054022 to your computer and use it in GitHub Desktop.
django: change primary key - export data using django admin dumpdata, edit json file and load data again
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
data = json.load(open('data.json')) | |
# get changed fields | |
# import model | |
model = User | |
changes = [(unicode(x.related_model._meta), x.field.name) for x in User._meta.get_all_related_objects()] # replace User with your model | |
m = {} | |
for u in model.objects.all(): | |
m[u.id] = str(u.uuid) # lookup key is your old field, value the new one | |
changes = dict(changes) | |
for idx, entry in enumerate(data): | |
f = changes.get(entry['model']) | |
if f is not None: | |
old = entry['fields'][f] | |
new = m.get(old) | |
print "Changed in model '%s' the field '%s' from %s to %s" % (entry['model'], f, repr(old), repr(new)) | |
data[idx]['fields'][f] = new | |
if entry['model'] == unicode(model._meta): | |
old = entry['pk'] | |
new = m.get(old) | |
print "Changed pk in model '%s' from %s to %s" % (entry['model'], repr(old), repr(new)) | |
data[idx]['pk'] = new | |
del data[idx]['fields']['uuid'] # change uuid to your soon-to-be pk field | |
json.dump(data, open('data_new.json', 'w')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment