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

Why am I getting 2 different results with a query depending on whether I run it as a script or in the consel?

Trying to do the first database project without peeking. Im hung up on the edit portion. I cant get the app to return anything to edit. Whats really stopping me from moving forward is the inability to run a query inside the script. When running the following code:


i return a query object in the consel and dont seem to get anything from the script. The script returns some SQL stuff that appears to have nothing passed in for title.

Side question:

Is there a way to pass a variable to an attribute? For example:

variable = title variable2 = Mindset

session.query(models.Book).filter(models.Book.variable = variable2)

Andy McDonald
Andy McDonald
5,016 Points

.filter() would use python operators such as '=='. Adding that to .filter_by() throws an error in both the consel and script.

1 Answer

Chris Freeman
Chris Freeman
Treehouse Moderator 67,763 Points

Hey Andy McDonald, when running in the script, you may be getting the query object. It just looks like "query language" perhaps due to printing it. The print calls the __str__ method of the query object which may not return same value as the __repr__ version that is returned in the REPL.

If query_object is the result of the query, for the script try:

print(f"There are {query_object.count()} objects in the query result")
for q in query_object:

As for using variables in queries, look at this other Treehouse post answer

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