PSchwede
PSchwede

Reputation: 196

SQLAlchemy: How to check for existence in the Database

Is there a better way than doing this with sqlalchemy?

def has_keyword(self, kw):
        s = self.sessionmaker()
        return 0 < s.query(Keyword).filter(kw.word == kw.word)

Upvotes: 1

Views: 699

Answers (2)

Santa
Santa

Reputation: 11547

A Pythonic way I like to do it with:

query = session.query(Model).filter( ... )
try:
    model = query.one()
except NoResultFound:
    # it does not exist!
except MultipleResultsFound:
    # there are more than one matching the filter criteria!

This allows for, say, creating a new model when one does not exist, and warning the user if multiple ones exist (pick the first one, etc).

Upvotes: 0

jwegan
jwegan

Reputation: 363

You can make the query marginally more optimal by adding .count() to the end

ex: return 0 < s.query(Keyword).filter(kw.word == kw.word).count()

Upvotes: 2

Related Questions