rahulchem - 8 months ago 72

Python Question

I want to add pandas dataframe (or a numpy array) as a field in django model. Each model instance in django has a large size 2D array associated with it so I want to store it as numpy array or pandas dataframe.

please guide me how can I achieve it. I tried below but it doesn't work.

`from django.db import models`

import numpy

class datafile(models.Model)

filename = models.CharField(max_length=50)

data = numpy.array((1000,1000))

I am reading data from excel file and setting it to data variable in views.py but after I save the model, the value for data doesn't get updated.

regards,

Rahul

Answer

You're likely gonna want to use a PickleField to store your numpy or Pandas dataframe. The PickleField will serialize the data into a text field for the database storage and convert it back upon retrieval.

```
from django.db import models
from picklefield.fields import PickledObjectField
import numpy
class DatafileModel(models.Model)
data = PickledObjectField()
```

And then just create or manipulate your model instances with numpy or pandas objects:

```
datafile = DatafileModel()
datafile.data = numpy.array((1000,1000))
datafile.save()
```

Source (Stackoverflow)