[Fixed]-Saving a Pandas DataFrame to a Django Model

27πŸ‘

βœ…

It would be most efficient to use to_sql() with appropriate connection parameters for the engine, and run this inside your Django app rather than iterating through the DataFrame and saving one model instance at a time:

from sqlalchemy import create_engine
from django.conf import settings

user = settings.DATABASES['default']['USER']
password = settings.DATABASES['default']['PASSWORD']
database_name = settings.DATABASES['default']['NAME']

database_url = 'postgresql://{user}:{password}@localhost:5432/{database_name}'.format(
    user=user,
    password=password,
    database_name=database_name,
)

engine = create_engine(database_url, echo=False)
df.to_sql(HistoricalPrices, con=engine)
πŸ‘€Stefan

0πŸ‘

Easier way , you can try this :

json_list = json.loads(json.dumps(list(df.T.to_dict().values())))

for dic in json_list:
     HistoricalPrices.objects.get_or_create(**dic)
πŸ‘€Amir.S

Leave a comment