Last active
August 29, 2015 13:57
-
-
Save MattMS/9505339 to your computer and use it in GitHub Desktop.
Django fixtures from JSON
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
""" | |
Simple operations for editing JSON Django fixtures. | |
These functions may be useful as example code for manipulating a JSON | |
file so it plays nice as a Django fixture. | |
""" | |
import json | |
def add_pk_to_list(): | |
""" | |
Add pk integer to each object. | |
""" | |
with open('items.json') as f: | |
data = json.load(f) | |
i = 0 | |
for ob in data: | |
ob['pk'] = i | |
i += 1 | |
with open('fixture.json', 'w') as f: | |
json.dump(data, f) | |
def move_attr_to_field(field_name): | |
""" | |
Move object attribute to fields object. | |
""" | |
with open('fixture.json') as f: | |
data = json.load(f) | |
for model in data: | |
fields = model.get('fields', {}) | |
try: | |
fields[field_name] = model.pop(field_name) | |
except KeyError: | |
pass | |
model['fields'] = fields | |
with open('fixture2.json', 'w') as f: | |
json.dump(data, f) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment