update state with flask sqlalchemy with postgres will not commit to database

前端 未结 1 584
别那么骄傲
别那么骄傲 2021-01-29 04:05

I have read quite a bit of documentation and I can\'t see what is wrong with these lines

update_this = User.query.filter_by(email=email).first()
update_this.emai         


        
相关标签:
1条回答
  • 2021-01-29 04:59

    Ideally you want to maintain a single session throughout your application lifecycle. This way it makes it easy to reason about and you avoid binding sessions to individual models.

    Thanks @Ilja Everila

    In main.py instead of initializing SQLAlchemy you should write,

    db.init_app(app)
    

    Define a save instance method for your User model.

    def save(self):
        """Saves model object instance
        """
        db.session.add(self)
        db.session.commit()
    

    You can call this method to save the instance as

    update_this.save()
    

    Another way to update the entity is to get the specific object session before committing

    from sqlachemy.orm import session
    ...
    session = session.object_session(update_this)
    session.commit()
    

    0 讨论(0)
提交回复
热议问题