我们从Python开源项目中,提取了以下2个代码示例,用于说明如何使用sqlalchemy.orm.validates()。
def truncate_to_field_length(self, field, value): """Truncate the value of a string field to the field's max length. Use this in a validator to check/truncate values before inserting them into the database. Copy the below example code after ``@validates`` to your model class and replace ``field1`` and ``field2`` with your field name(s). :Example: from sqlalchemy.orm import validates # ... omitting other imports ... class MyModel(base.Base): field1 = Column(String(128)) field2 = Column(String(64)) @validates('field1', 'field2') def truncate(self, field, value): return self.truncate_to_field_length(field, value) Args: field (str): field name to validate value (str/unicode): value to validate Returns: str/unicode: value truncated to field max length """ max_len = getattr(self.__class__, field).prop.columns[0].type.length if value and len(value) > max_len: return value[:max_len] else: return value
def receive_class_instrument(cls): for field in cls.iter_columns(relationships=False, synonyms=False, use_inspection=False): if not isinstance(field, Field) or not field.can_validate: continue method_name = 'validate_%s' % field.name if not hasattr(cls, method_name): def validator(self, key, value): return self.get_column(key).validate(value) setattr(cls, method_name, validates(field.name)(validator))