Bootstrap FreeKB - Flask - Resolve "Blueprint object has no attribute query"
Flask - Resolve "Blueprint object has no attribute query"

Updated:   |  Flask articles

Let's say you are attempting to use Query records in a table using SQLAlchemy.

from flask import Blueprint, render_template
from . import db
from .models import users
from sqlalchemy import exc

@views.route('/Results', methods=['GET', 'POST'])
def results():
    try:
        data = users.query.filter(users.email.ilike('john.doe@example.com')).one()
    except exc.SQLAlchemyError as exception: 
        print(execption)
        return exception
    except Exception as exception:
        print(execption)
        return execption
    else:
        print("data.firstname = " + str(data.firstname))
        print("data.lastname  = " + str(data.lastname))
        return render_template('results.html', result=data)  

 

And something like this is being returned.

'Blueprint' object has no attribute 'query'

 

I once happened up this when I had a model that had a class named "users". In other words, in my database there was a table named "users".

from sqlalchemy import func
from flask_login import UserMixin
from . import db

class users(db.Model, UserMixin):
    id       = db.Column(db.Integer,     nullable=False, unique=True, primary_key=True) 
    email    = db.Column(db.String(100), nullable=False, unique=True)
    password = db.Column(db.String(200), nullable=False, unique=False) 

 

And I had a Blueprint named "users".

from flask import Blueprint, render_template
from . import db
from .models import users
from sqlalchemy import exc

users = Blueprint('users', __name__)

@users.route('/Results', methods=['GET', 'POST'])
def results():
    try:
        data = users.query.filter(users.email.ilike('john.doe@example.com')).one()
    except exc.SQLAlchemyError as exception: 
        print(execption)
        return exception
    except Exception as exception:
        print(execption)
        return execption
    else:
        print("data.firstname = " + str(data.firstname))
        print("data.lastname  = " + str(data.lastname))
        return render_template('results.html', result=data)  

 

I simply just had to renamed the Blueprint to something other than users.

myusers = Blueprint('myusers', __name__)

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter b30acc in the box below so that we can be sure you are a human.