Last active
March 26, 2025 22:45
-
-
Save mschulz/081254ffc0f15819801c6c0c91e9330b to your computer and use it in GitHub Desktop.
sqlalchemy - automatically truncate strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Create a TypeDecorator in your base model for an even more generic answer. Then, use this TypeDecorator instead of string. | |
#In base.py | |
from sqlalchemy.types import TypeDecorator | |
class TruncateString(TypeDecorator): | |
"""trim spaces from the string""" | |
impl = db.String | |
cache_ok = True | |
def process_bind_param(self, value, dialect): | |
# In case you have nullable string fields and pass None | |
if value and len(value) > self.impl.length: | |
value = value[:self.impl.length] | |
return value if value else value | |
def copy(self, **kw): | |
return TruncateString(self.impl.length) | |
#Now, in your yourModel.py, use this type. | |
from flask_app.models.base import * | |
class CampaignScript(BaseModel): | |
__tablename__ = 'campaign_script' | |
name = Column(TruncateString(200)) | |
subject = Column(TruncateString(200)) | |
comments = Column(TruncateString(200)) | |
language = Column(TruncateString(200)) | |
script = Column(NVARCHAR(None)) | |
user_id = Column(TruncateString) | |
account_id = Column(Integer) | |
comm_type = Column(TruncateString(45)) | |
short_name = Column(TruncateString(75)) | |
released_locked = Column(Boolean()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment