Best way to force values to uppercase in sqlalchemy field

前端 未结 2 1092
自闭症患者
自闭症患者 2021-01-04 17:22

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 rec

2条回答
  •  隐瞒了意图╮
    2021-01-04 17:44

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

提交回复
热议问题