Python SQLAlchemy check for nonetype

Viewed 149

I am writing a python script that deals with user signups and I need to check a SQLAlchemy database for an existing user but when the lookup.username is non type, it returns an attribute error. Is there anyway to check for a non-existant entry and move past it in SQLAlchemy for Flask?

lookup = User.query.filter_by(phonenumber = request.form['number']).first()
            if request.form['username'] == lookup.username:
                return render_template('numberusererror.html', number = request.form['number'], username = request.form['username'])
            elif request.form['number'] != lookup.phonenumber:
                return render_template('numberusererror.html', number = request.form['number'], username = request.form['username'])
1 Answers

You can check if your query actually returns any results before trying to access it's attributes.

lookup = User.query.filter_by(phonenumber = request.form['number']).first()
if not lookup:
    #return something for non-existent user
    pass
# continue with your code here 
...
Related