Flask-SQLAlchemy check if row exists in table

前端 未结 5 2057
耶瑟儿~
耶瑟儿~ 2020-12-05 02:17

I have a Flask application which uses Flask-SQLAlchemy to connect to a MySQL database.

I would like to be able to check whether a row is present in a table. How woul

5条回答
  •  盖世英雄少女心
    2020-12-05 02:56

    Forgive the hijacking but ... with the instructions given here I made the following WTForm validator to check uniqueness of the field

    class Unique(object):
        def __init__(self, column, session, message="Already exists."):
            self.column = column
            self.session = session
            self.message = message
    
        def __call__(self, form, field):
            if field.data == field.object_data:
                return  # Field value equals to existing value. That's ok.
            model = self.column.class_
            query = model.query.filter(self.column == field.data).exists()
            if self.session.query(query).scalar():
                raise ValidationError(self.message)
    

    It would be used like this

    class Register(Form):
        email = EmailField('Email', [Unique(User.email, db.session)])
    

    However, I would like to have API which does not need db session as a second param

    class Register(Form):
        email = EmailField('Email', [Unique(User.email)])
    

    Is there any way to get db session from model? Without session it seems to be impossible to avoid loading the entire object to check its existence.

提交回复
热议问题