1

I have a class defined like below

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)

Now I want to store an instance of this class into postgres database.This file is hosted in a django server and I am unable to use django migrations due to some issues in the server.So I need to do it manually.

Below is my django model

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

Here I want to store the StatementStatus instance in a field called state.

Similarly my postgres table structure looks like below

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

But it doesn't store any entry into the table when I do an operation like below

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

But it doesn't store anything into the table.I get the below error.

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

What am I doing wrong?

4
  • 1
    your state is not a binary object. it is just an instance object Commented Jul 21, 2018 at 16:19
  • @HarunERGUL oh ok so how do I store an instance object? Commented Jul 21, 2018 at 16:21
  • can you show us where s coming from? Commented Jul 21, 2018 at 16:21
  • I think you should create a StatementStatus table and use ForeingKey in your Storestate Commented Jul 21, 2018 at 16:27

1 Answer 1

1

If you want to save your object in your database then use 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)
Sign up to request clarification or add additional context in comments.

Comments

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.