I'm defining an PostgreSQL table using an SQLAlchemy declarative base, like this:
from sqlalchemy import Column, String, BigInteger
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class MyTable(Base):
__tablename__ = 'my_table'
id = Column('id', BigInteger, primary_key=True)
some_string = Column('some_string', String(256), nullable=False)
The nullable
constraint guarantees that some_string
cannot be null
. However, I'd additionally like to give some_string
a minimum length, or just forbid it from being the empty string. How can I do this?
Ideally we want the validation to be applied both at the database layer via a constraint and also in our model by rejecting attempts to set the property to a string that's too short even before trying to save it to the database. We can do the former with a CheckConstraint
using the char_length
function, and the latter by adding a validator. Below is an example that enforces a minimum length of 3 characters on some_string
:
from sqlalchemy import Column, String, BigInteger
from sqlalchemy.schema import CheckConstraint
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import validates
Base = declarative_base()
class MyTable(Base):
__tablename__ = 'my_table'
id = Column('id', BigInteger, primary_key=True)
some_string = Column('some_string', String(256), nullable=False)
__table_args__ = (
CheckConstraint('char_length(some_string) > 2',
name='some_string_min_length'),
)
@validates('some_string')
def validate_some_string(self, key, some_string) -> str:
if len(some_string) <= 2:
raise ValueError('some_string too short')
return some_string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With