Best way to force values to uppercase in sqlalchemy field
Have a look at events
YOu can easily add a listener for a save/update and just uppercase the string:
def uppercase_code(target, value, oldvalue, initiator):
return value.upper()
# setup listener on Item.code attribute, instructing
# it to use the return value
listen(Item.code, 'set', uppercase_code, retval=True)
Validators can do this fairly easily:
from sqlalchemy.orm import validates
class Item(db.Model):
# I need to ensure the code column converts values to uppercase automatically
code = db.Column(db.String(30), primary_key=True)
name = db.Column(db.String(250), nullable=False)
@validates('code', 'name')
def convert_upper(self, key, value):
return value.upper()
A similar approach can be taken with descriptors or hybrids, though it's not quite as easy to apply the same mutations to multiple columns at once. Hybrids do provide some additional benefits, in that using them in queries can delegate work to the DBMS instead of performing the work on the Python side (though for this particular case, doing the work on the Python side doesn't really cost you anything).
To be clear, the validator is applied at the model level; you must be constructing Item
classes to benefit from it (for example, using Item.__table__
to directly manipulate the table will bypass the model's validator).