title: Automatically truncate strings in sqlalchemy's ORM (postgresql database)
body: <p>How can I automatically truncate string values in a data model across many attributes, without explicitly defining a <code>@validates</code> method for each one?</p>
  <p><strong>My current code:</strong></p>
  <pre class="lang-py prettyprint-override"><code>from sqlalchemy import Column, Integer, String
  from sqlalchemy.orm import validates
  
  class MyModel:
      __tablename__ = 'my_model'
  
      id = Column(Integer, primary_key=True, autoincrement=True)
      name = Column(String(40), nullable=False, unique=True)
  
      # I can &quot;force&quot; truncation to my model using &quot;validates&quot;
      # I'd prefer not to use this solution though...
      @validates('name')
      def validate_code(self, key, value):
          max_len = getattr(self.__class__, key).prop.columns[0].type.length
          if value and len(value) &gt; max_len:
              value = value[:max_len]
          return value
  </code></pre>
  <p>My concern is that my ORM will span many tables and fields and there's a high risk of oversight in including attributes in string length validation. In simpler words, I need a solution that'll scale. <em>Ideally, something in my session configuration which'll automatically truncate strings that are too long...</em></p>