To Limit Column Values to Strings in a String List Using sqlalchemy

Asked 1 years ago, Updated 1 years ago, 519 views

As the title suggests, how do you write sqlalchemy to allow values in columns in a table only for specific strings?
If the string does not match when it is inserted/updated, I would like to treat it as an error and not accept it.

Python 3.9
Windows 10

 from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, String
from sqlalchemy.dialects.mysql import INTEGER

# I want to limit it to the values in this list.
mode_type_list = [
    'DEFAULT',
    "Right",
    'LEFT',
    "CENTER".
]


Base=declarative_base()
RDB_PATH='sqlite://db.sqlite3'
ECHO_LOG = True

engine=create_engine(
    RDB_PATH, echo=ECHO_LOG
)

Class Test (Base):
    __tablename__='test_tbl'
    key=Column(
        'pkey',
        INTEGER (unsigned=True),
        primary_key = True,
        autoinclement=True,
    )
    key=Column('mode_type', String(256))

    def__init__(self, mode_type:str):
        self.mode_type=mode_type

Session=sessionmaker (bind=engine)
session=Session()

Base.metadata.create_all(engine)

param=Test(mode_type='DEFAULT')
session.add(param)

session.commit()


python sqlalchemy

2023-03-02 16:00

1 Answers

It might be good to use enum

Specify Python's enum and sqlalchemy's Enum in the definition section and create classes with enum.Enum (value may be a string if necessary...enum---Enumeration support)

import enum

Added from sqlalchemy import Table, Column, Integer, String, Enum# En Enum

# I want to limit it to the values in this list.
mode_type_list = [
    'DEFAULT',
    "Right",
    'LEFT',
    "CENTER".
]
ModeType=enum.Enum('ModeType',mode_type_list)

Specify columns and add data
Use ModeType['DEFAULT'] to specify by string.

class Test (Base):

    # column specification
    mode_type = Column ('mode_type', Enum(ModeType))

with Session() as session, session.begin():
    param=Test(mode_type=ModeType.DEFAULT)#For strings, ModeType['DEFAULT']
    session.add(param)


2023-03-02 19:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.