Best way to force values to uppercase in sqlalchemy field

≯℡__Kan透↙ 提交于 2021-01-07 02:51:30

问题


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


回答1:


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




回答2:


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)


来源:https://stackoverflow.com/questions/65408938/sqlalchemy-save-value-as-uppercase-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!