SQLAlchemy - Is there a way to see what is currently in the session?

前端 未结 1 2029
礼貌的吻别
礼貌的吻别 2021-02-14 01:41

I\'m curious if there\'s a way to show what is currently in the session?

Or perhaps a way to check if the session is empty or not so that I can do something like the be

相关标签:
1条回答
  • 2021-02-14 02:25

    There are following properties to check session state:

    • Session.new - for objects, which will be added to database.
    • Session.dirty - for objects, which will be updated.
    • Session.deleted - for objects, which will be deleted from database.

    These three properties can be used to check session state:

    if not db.session.new and not db.session.dirty and not db.session.deleted:
        # do smth
    

    However it is safe to call session.commit() even if there is no changes in session. If you don't do something special, you don't need to explicitly check session state before commit.


    Also there is a private method called Session._is_clean(), which is used to check if there are any changes to be flushed to database. It's implemented like this:

    def _is_clean(self):
        return not self.identity_map.check_modified() and \
            not self._deleted and \
            not self._new
    
    0 讨论(0)
提交回复
热议问题