4

When I try to store a Animals object with a field species containing a Python Enum object SpeciesType.Cat, I get the error

TypeError: object of type 'VisitableType' has no len()

What is the correct way to store a Python 3 Enum in MySQL using SQLAlchemy?

# SQLALCHEMY CODE ########################

from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class SpeciesType(Enum):
    Cat = 1
    Dog = 2


class Animals(Base):
    __tablename__ = 'animals'
    id  = Column(String(16), primary_key=True)
    species = Column(Enum(SpeciesType))


# REGULAR CODE ########################

import enum

class SpeciesType(enum.Enum):
    Cat = 1
    Dog = 2


class MyClass:
    @property
    def session(self):
        ....

    def insertToDB(self):
        kitty = Animals(id='kitty', species=SpeciesType.Cat)
        self.session.add(kitty)
        self.session.commit()

c = MyClass()
c.insertToDB()

Update

The following new error occurs after fixing the name collision between sqlalchemy.enum and Enum.enum.

sqlalchemy.exc.StatementError: (builtins.LookupError) "SpeciesType.Cat" is not among the defined enum values [SQL: 'INSERT INTO animals (id, species) VALUES (%(id)s, %(species)s)'] [parameters: [{'species': , 'id': 'kitty'}]]

2
  • 1
    Are you sure you don't have a name collision between enum.Enum and sqlalchemy.Enum? Commented Jan 4, 2018 at 20:58
  • @univerio Fixed the name collision, now I get a new error that I cant solve sqlalchemy.exc.StatementError: (builtins.LookupError) "SpeciesType.Cat" is not among the defined enum values [SQL: 'INSERT INTO animals (id, species) VALUES (%(id)s, %(species)s)'] [parameters: [{'species': <SpeciesType.Cat: 1>, 'id': 'kitty'}]]. Updated question Commented Jan 4, 2018 at 21:37

2 Answers 2

2

Looks like you are creating the Animals enumeration twice, which means you will have two different enums that happen to have the same names.

Define it only once, and import it anywhere else you need it.

Sign up to request clarification or add additional context in comments.

Comments

1

Your enum model should be a subclass of Python's enum.Enum and your models column definitions should use sqlalchemy.Enum

class SpeciesType(enum.Enum):
...

class Animals(Base):
    ...
    species = Column(sqlalchemy.Enum(SpeciesType))

1 Comment

with this configuration, I get "Boolean value of this clause is not defined"

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.