Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python SQLAlchemy Basics Working with SQLAlchemy Creating Our Book Database

Andy McDonald
Andy McDonald
5,016 Points

How to identify empty query object when empty query is truthy?

Working on the project and if the app searches for a book thats not in the database I would like the app to say so. The best way I know how to do so is like so:

def delete():
    todel = input("What's the title of the book you want to delete?")
    dellie = models.session.query(models.Book).filter_by(title=todel)
    if dellie:
        for book in dellie:
            print('Alright that book is gone. Now what?')
        print('Cant find a book by that name. Try again.')

However, when I input a book title that does not exist it returns a query object that is truthy. Any suggestions?

[MOD: added ```python formatting -cf]

1 Answer

Chris Freeman
Chris Freeman
Treehouse Moderator 67,763 Points

Hey Andy McDonald, then query method count() gives the size of the query result.

    if dellie.count() > 0:

    # OR in truthy fashion

    if dellie.count():

Post back if you need more help. Good luck!!!