Saving a Pandas DataFrame to a Django Model

前端 未结 1 1602
梦毁少年i
梦毁少年i 2020-12-24 09:21

I have stock price data that is stored in a pandas DataFrame as shown below (actually it was in a panel, but I converted it to a DataFrame)

        date  tic         


        
相关标签:
1条回答
  • 2020-12-24 09:50

    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 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)
    
    0 讨论(0)
提交回复
热议问题