Created
August 19, 2015 21:05
-
-
Save arthuralvim/54a9544a75dd444e6827 to your computer and use it in GitHub Desktop.
Convert .csv to Django fixtures.
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
# -*- coding: utf-8 -*- | |
# requirements | |
# pip install unipath | |
# pip install python-decouple | |
from os.path import join | |
from unipath import Path | |
from decouple import config | |
import csv | |
import json | |
fixture_name = config('FIXTURE_CSV', default='input.csv') | |
fixture_json = config('FIXTURE_JSON', default='output.json') | |
fixture_delimiter = config('FIXTURE_DELIMITER', default=';') | |
fixture_quotechar = config('FIXTURE_QUOTECHAR', default='"') | |
fixture_model = config('FIXTURE_MODEL', default='app.Model') | |
fixture_path = config('FIXTURE_CSV', | |
default=Path(__file__).absolute().ancestor(1)) | |
with open(join(fixture_path, fixture_name), 'rb') as csvfile: | |
table = csv.reader(csvfile, delimiter=fixture_delimiter, | |
quotechar=fixture_quotechar) | |
header = next(table) | |
elements = list(table) | |
pk = 1 | |
fixtures = [] | |
for el in elements: | |
print el | |
new_el = {} | |
new_el.update({"fields": {}}) | |
new_el.update({"model": fixture_model}) | |
new_el.update({"pk": None}) | |
for num, field in enumerate(header): | |
new_el['fields'][field] = el[num] | |
fixtures.append(new_el) | |
pk += 1 | |
with open(join(fixture_path, fixture_json), 'wb') as json_file: | |
json_file.write("%s" % json.dumps(fixtures, indent=4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment