Skip to content

Instantly share code, notes, and snippets.

@mschulz
Created March 26, 2025 22:33
Show Gist options
  • Save mschulz/87ab88848d6ecd82d612c86ffd96cb79 to your computer and use it in GitHub Desktop.
Save mschulz/87ab88848d6ecd82d612c86ffd96cb79 to your computer and use it in GitHub Desktop.
sqlalchemy - automatically truncate string
import sqlalchemy.types as types
class LimitedLengthString(types.TypeDecorator):
impl = types.String
def process_bind_param(self, value, dialect):
return value[:self.impl.length]
def copy(self, **kwargs):
return LimitedLengthString(self.impl.length)
class MyModel:
__tablename__ = 'my_model'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(LimitedLengthString(40), nullable=False, unique=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment