Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialWelby Obeng
20,340 PointsWhy do you compare models.User.id == userid?
#function to use if you need to look up a user
@login_manager.user_loader
def load_user(userid):
try:
# get user row with id
return models.User.get(models.User.id == userid)
# if does not exist return none
except models.DoesNotExist:
return None
Regarding the code above why do you compare models.User.id == userid in get function? why not return models.User.get(userid)? if userid doesn't exist it will throw models.DoesNotExist exception
regarding def load_user(userid), where in social network app do you use use this function and pass in user id? is it login_user(user) in login function?
1 Answer
Kenneth Love
Treehouse Guest TeacherI'm gonna answer those backwards.
We don't use load_user
, but flask-login
does any time we need to check/fetch the current user. So, yes, when we login the user. When we do @login_required
. When we do current_user
. We have to provide that so flask-login
knows how to find our user accounts.
Why do the comparison? Mainly to keep it explicit and uniform through the rest of the code base. We do comparisons everywhere else and there's no harm in doing a comparison here.
Nicolas Hampton
44,638 PointsNicolas Hampton
44,638 PointsYes, but I was actually wondering why when we do that comparison, it doesn't return a boolean, but the userid we put in. I feel like I'm missing something obvious, but it looks like the get method on the User model would receive the value True from the comparison. That doesn't happen though. Why?
Kenneth Love
Treehouse Guest TeacherKenneth Love
Treehouse Guest TeacherNicolas Hampton It doesn't do a comparison there, though. It does it in Peewee's ORM. Peewee is using that comparison to craft its SQL query for the database. Here's a bit more information.
Nicolas Hampton
44,638 PointsNicolas Hampton
44,638 PointsThank you for that. So it's working similarly to the where method on the same ORM model. Got ya. Databases man, one of my weakest points. Getting there!