Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 641943
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T21:07:03+00:00 2026-05-13T21:07:03+00:00

is it possible in SQLAlchemy to enforce maximum string length of value assigned to

  • 0

is it possible in SQLAlchemy to enforce maximum string length of value assigned to mapped column? All I want is to raise an exception if an assigned string value is longer then the length of the corresponding table column of type STRING.

Thank you

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T21:07:04+00:00Added an answer on May 13, 2026 at 9:07 pm

    It’s easiest to just rename the mapped column and proxy it through a property:

    class Something(Base):
        ...
        _foo = Column('foo', String(123))
    
        @property
        def foo(self):
            return self._foo
    
        @foo.setter
        def foo(self, value):
            if len(value) > _foo.type.length:
                raise Exception("Value too long")
            self._foo = value 
    

    You can easily factor out the property creation, and even use a generic validation framework like formencode.


    If you need a more SQLAlchemy specific solution and don’t mind using specific interfaces, then SQLAlchemy has an extension mechanism for capturing events on attributes. A validator using that would look something like this:

    from sqlalchemy.orm.interfaces import AttributeExtension, InstrumentationManager
    from sqlalchemy.orm import ColumnProperty
    
    class InstallValidatorListeners(InstrumentationManager):
        def post_configure_attribute(self, class_, key, inst):
            """Add validators for any attributes that can be validated."""
            prop = inst.prop
            # Only interested in simple columns, not relations
            if isinstance(prop, ColumnProperty) and len(prop.columns) == 1:
                col = prop.columns[0]
                # if we have string column with a length, install a length validator
                if isinstance(col.type, String) and col.type.length:
                    inst.impl.extensions.insert(0, LengthValidator(col.type.length))
    
    class ValidationError(Exception):
        pass
    
    class LengthValidator(AttributeExtension):
        def __init__(self, max_length):
            self.max_length = max_length
    
        def set(self, state, value, oldvalue, initiator):
            if len(value) > self.max_length:
                raise ValidationError("Length %d exceeds allowed %d" %
                                    (len(value), self.max_length))
            return value
    

    You would then use this extension by setting __sa_instrumentation_manager__ = InstallValidatorListeners on any class you want validated. You can also just set it on the Base class if you want it to apply to all classes derived from it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

With SQLAlchemy, it is possible to add a default value to every function. As
Trying to find out if it's possible to use SQLAlchemy on Heroku. Thanks.
Is it possible to unbind an object from an SQLAlchemy session? I used to
Possible Duplicate: How can I convert a list<> to a multi-dimensional array? I want
Possible Duplicate: How to do the vector of sets in C++? I want to
Possible Duplicate: check whether internet connection is available with C# I just want to
Is it possible to write custom collation functions with indexes in SQLAlchemy? SQLite for
Is it possible to have multi-level polymorphism in SQLAlchemy? Here's an example: class Entity(Base):
Is it possible to have the postgres database dump(pg_dump) using SQLAlchemy? i can get
Possible Duplicate: Extracting dollar amounts from existing sql data? I have a column in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.