Reputation: 196
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
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
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