Saving a Pandas DataFrame to a Django Model
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)