Prevented unnecessary query to a database.

Hi! I made some changes to avoid unnecessary query to database. Please review.