Last active
October 28, 2018 20:15
-
-
Save AdamGold/c0f6e05eb434a9327f80f7d13cd43386 to your computer and use it in GitHub Desktop.
SQLAlchemy Load CSV Files
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
# from MODELS_MODULE import MODEL | |
import pandas as pd | |
CSV_FOLDER = 'csvs' | |
def load_csv(file, model_name): | |
df = pd.read_csv('{}/{}.csv'.format(CSV_FOLDER, file)) | |
csv = df.where((pd.notnull(df)), None) # replace Nan with None | |
for row in csv.itertuples(index=False): | |
model_class = getattr(sys.modules[__name__], model_name) | |
model = model_class(**row._asdict()) | |
model.save() | |
""" | |
Usage: | |
tables = {'Model': 'table_name'} | |
for model_name, table in tables.items(): | |
load_csv(table, model_name) | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment