To avoid creating the need to instantiate the model separately, you can use the following simple approach
import pandas as pd
from django.contrib.postgres.fields import JSONField
class StoredDataFrame(Model):
data = JSONField()
@classmethod
def putframe(cls, dataframe):
storeddataframe = cls(data=dataframe.to_json(orient='split'))
storeddataframe.save()
return storeddataframe
def loadframe(self):
return pd.read_json(self.data, orient='split')
Using an example:
df = pd.DataFrame(np.random.randn(6,4), index=list('qwerty'), columns=list('ABCD'))
storeddata = StoredDataFrame.putframe(df)
retrieveddataframe = storeddata.loadframe()
source
share