1

I'm using pyodbc + pandas to analyze data, and I'm wondering how to store the final dataframe in Django.

cnxn = pyodbc.connect('DSN=DATABASE;UID=USERNAME;PWD=PASSWORD')
cursor = cnxn.cursor()

qry = "SELECT * FROM SECURITIES"
df = pd.read_sql(qry, cnxn)

*do some manipulation*

df_final

ticker    beta
ABC       1.2
XYZ       0.8

Ive got my model and serializer set up, but I'm stuck on how to push the dataframe into this model.

class Stocks(models.Model):
    ticker = models.CharField(max_length=16)
    beta = models.FloatField()

    def __str__(self):
        return self.ticker

class TickerSerializer(serializers.ModelSerializer):

    class Meta:
        model = Ticker
        fields = ('ticker', 'beta')
0

1 Answer 1

1

This did the trick:

from django.db import models
from django.conf import settings
from .available import df_available
import sqlite3

engine = settings.DATABASES['default']['NAME']

# Create your models here.
class Stocks(models.Model):
    ticker = models.CharField(max_length=16, primary_key=True)
    beta = models.FloatField(default=1.0)

    def __str__(self):
        return self.ticker

cnxn = sqlite3.connect(engine)

df_final.to_sql('api_stocks', con=cnxn, if_exists='replace', index=False)
Sign up to request clarification or add additional context in comments.

1 Comment

works: df_final.to_sql('api_stocks', con=cnxn, if_exists='replace', index=False) doesn't work: df_final.to_sql('Available', con=cnxn, if_exists='replace', index=False) error: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': Error binding parameter 0 - probably unsupported type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.