无法在PostgreSQL数据库中存储python类对象

时间:2018-07-21 16:10:29

标签: django python-3.x postgresql

我有一个如下定义的类

class StatementStatus:
    def __init__(self, id, statement, call, intent, score):
        self.id = callback_id
        self.statement = statement
        self.entities = entities
        self.intent = intent
        self.score = score

    def getIntent(self):
        return self.intent

    def getScore(self):
        return self.score

    def addIntent(self, intent_val):
        self.intent.append(intent_val)

现在我想将此类的实例存储到postgres数据库中。此文件托管在django服务器中,由于服务器中的某些问题,我无法使用django迁移,因此我需要手动进行操作。< / p>

下面是我的Django模型

class StoreState(models.Model):
    context_name = models.CharField(null=True,max_length=100)
    state = models.BinaryField(null=True)

在这里,我想将StatementStatus实例存储在一个名为state的字段中。

类似地,我的postgres表结构如下所示

    Column    |          Type          | Modifiers 
--------------+------------------------+-----------
 id           | integer                | 
 context_name | character varying(100) | 
 state        | bytea                  | 

但是当我执行以下操作时,它不会在表中存储任何条目

try:
    conv = StoreState.objects.create(
    context_name = callback_id,
    state=s
    )
except Exception as e:
    print("unable to save update", e)

但是它没有在表中存储任何内容。我得到以下错误。

('unable to save update', TypeError("can't escape instance to binary",))

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

如果要将对象保存在数据库中,请使用pickle。

import pickle
state = pickle.dump(state) #your state object will be converted to binary

try:
    conv = StoreState.objects.create(
    context_name = callback_id,
    state=s
      )
except Exception as e:
    print("unable to save update", e)