6

I have a class as such:

class VoteEnum(enum.Enum):
    like = "LIKE"
    dislike = "DISLIKE"
    abstain =  "ABSTAIN"

I have a database which stores these votes as such:

class MyVotes(db.Model):
    __tablename__ = "my_votes"
    id = db.Column(db.String, primary_key=True, default=lambda: str(uuid4()))
    item = db.Column(db.String,  nullable=False),
    vote = db.Column(db.Enum(VoteEnum))

    def __str__(self):
        return json.dumps({
            "id":self.id,
            "item":self.item,
            # I want to print the value of vote?
    )}

When retrieving values from sqlalchemy (in flask) and printing, I get the following error:

TypeError: Object of type MyVotes is not JSON serializable

Perhaps there a way to call in my sqlalchemy request? Maybe the class method? I appreciate any help folks can provide.

Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69

1 Answers1

7

I have a similar situation. Here is how you should do it. Enums have name and value.

def __str__(self):
    return json.dumps({
        'id': self.id,
        'item': self.item,
        'vote': self.vote.name
    })
LNF
  • 644
  • 8
  • 8