Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to force values to uppercase in sqlalchemy field

I am pretty new to python and sqlalchemy and would like to ask for an advice.

What would be the best way to force uppercase values in a SqlAlchemy field when the record is inserted/updated? Should I use events for that? Here I am using flask-sqlalchemy version, but I believe it is something similar to SQLAlchemy.

from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()

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)
    ...

Thanks for the advice

like image 936
Darius Avatar asked Dec 16 '15 20:12

Darius


1 Answers

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)
like image 150
fiacre Avatar answered Sep 29 '22 00:09

fiacre