无法修改Django模型中保存的数据帧

2024-09-27 23:22:08 发布

您现在位置:Python中文网/ 问答频道 /正文

在models.py中,我创建了以下模型:

from django.db import models
from Data.DataFrame import df  #df is the DataFrame

# Create your models here.
class Custumer(models.Model):
    ip = models.CharField(max_length=100)
    products = df

在python shell中,我完成了以下操作:

In [1]: from app.models import Custumer as C

In [2]: new = C.objects.create(ip='1')

In [3]: new.products
Out[3]: 
   B000JMLBHU  B002AJ7X2C  B002D48NBO  B0031Y9CPG  B0032YXH2E  B00359FHZ6  ...  B00LDD8NDO  B00LF56Y3Q  B00LKQNFVE  B00LKS5WUY  B00LLWDUDK  B00LMTLV24       
0           0           0           0           0           0           0  ...           0           0           0           0           0           0       

[1 rows x 1000 columns]

In [4]: new.products['B000JMLBHU'] =1

In [5]: new.products
Out[5]: 
   B000JMLBHU  B002AJ7X2C  B002D48NBO  B0031Y9CPG  B0032YXH2E  B00359FHZ6  ...  B00LDD8NDO  B00LF56Y3Q  B00LKQNFVE  B00LKS5WUY  B00LLWDUDK  B00LMTLV24       
0           1           0           0           0           0           0  ...           0           0           0           0           0           0       

[1 rows x 1000 columns]

In [6]: new.save()

但是,当我在shell中退出()并再次打开它时,我在第一列中编写的1就消失了。如何修改保存在模型中的数据帧


Tags: infrom模型importipdataframedfnew
1条回答
网友
1楼 · 发布于 2024-09-27 23:22:08

问题是您没有使用某个列来存储数据,并使其持久化

但是,您可以自己define a field [Django-doc],这是^{} [Django-doc]的修改版本。因此,我们需要实现某种机制,在二进制表示和数据格式之间自动换行

例如,我们可以使用^{}来序列化和反序列化数据帧。您可以通过以下方式安装feather-format

pip3 install feather-format

然后我们可以定义我们自己的DataframeField

# app/fields.py

form django.db.models import BinaryField
from io import BytesIO
from pandas import DataFrame
from pyarrow.feather as write_dataframe, read_dataframe

class DataframeField(BinaryField):

    def to_python(self, value):
        if value is None or isinstance(value, DataFrame):
            return value
        value = super().to_python(value)
        with BytesIO(value) as b:
            return read_dataframe(b)

    def from_db_value(self, value, expression, connection):
        if value is None:
            return value
        value = super().from_db_value(value, expression, connection)
        with BytesIO(value) as b:
            return read_dataframe(b)

    def get_prep_value(self, value):
        result = value
        if isinstance(value, DataFrame):
            with BytesIO() as b:
                write_dataframe(value, b)
                result = b.getvalue()
        return super().get_prep_value(result)

现在,我们可以在模型中使用此字段,通过序列化使数据帧保持不变:

# app/models.py

from app.fields import DataframeField
from django.db import models
from Data.DataFrame import df

# Create your models here.
class Custumer(models.Model):
    ip = models.CharField(max_length=100)
    products = DataframeField(default=df)

相关问题 更多 >

    热门问题