Home > Mobile >  Error with default value in enum field when define model class
Error with default value in enum field when define model class

Time:05-07

Hello I have the following model:

class Status(Enum):
    scheduled: 'scheduled'
    recording: 'recording'
    complete: 'complete'
    failed: 'failed'


@dataclass
class Record(db.Model):
    __tablename__ = 'records'
    id: int
    status: Status
    start: datetime
    end: datetime
    time_duration:int
    camera_id: int
    bucket_destination:str

    id = db.Column(db.Integer, primary_key=True)
    status = db.Column(db.Enum(Status), nullable=False, default=Status.scheduled)
    start = db.Column(db.DateTime(), nullable=False)
    end = db.Column(db.DateTime())
    time_duration = db.Column(db.Integer)
    camera_id = db.Column(db.Integer, unique=True, nullable=False)
    bucket_destination = db.Column(db.String(1000), unique=True, nullable=False) 

    
db.create_all()

And when executing this code I get the following error:

Traceback (most recent call last):   File "src/app.py", line 36, in <module>
    app = create_app()   File "src/app.py", line 25, in create_app
    from routes.record import record_blueprint   File "/home/User/VideoCapturer/services/api/src/routes/record/__init__.py",
line 1, in <module>
    from .routes import *   File "/home/User/VideoCapturer/services/api/src/routes/record/routes.py",
line 4, in <module>
    from .models import Record   File "/home/User/VideoCapturer/services/api/src/routes/record/models.py",
line 14, in <module>
    class Record(db.Model):   File "/home/User/VideoCapturer/services/api/src/routes/record/models.py",
line 25, in Record
    status = db.Column(db.Enum(Status), nullable=False, default=Status.scheduled)   File
"/home/User/.pyenv/versions/3.6.15/lib/python3.6/enum.py", line 326,
in __getattr__
    raise AttributeError(name) from None AttributeError: scheduled

Any idea about why SQL is not taking the enum correctly?

Thanks

CodePudding user response:

The correct syntax to define enums in Python is:

class Status(Enum):
    scheduled = 'scheduled'

What you did was type hinting.

  • Related