1

I would like to create a custom method to tell me whether a row exists in my database. The SQLAlchemy exists method returns a subquery but doesn't execute anything, so I wanted to create the method does_exist, which will simply return True or False. Here is my code:

from flask_sqlalchemy import SQLAlchemy, BaseQuery, Model

class CustomBaseQuery(BaseQuery):
    def does_exist(self):
        return db.session.query(self.exists()).scalar()

db = SQLAlchemy(app, query_class=CustomBaseQuery)

This actually does work, but it seems wrong to refer to db.session within the body of the method, which thus depends on later naming the SQLAlchemy instance db. I would like to find a way to reference the eventual db.session object in a more general way.

Full working example here: https://gist.github.com/wbruntra/3db7b630e6ffb86fe792e4ed5a7a9578

1 Answer 1

2

Though undocumented, the session used by the Query object is accessible as

self.session

so your more generic CustomBaseQuery could look like

class CustomBaseQuery(BaseQuery):
    def does_exist(self):
        return self.session.query(self.exists()).scalar()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.