简体   繁体   中英

How do i get specific values using flask-sqlalchemy?

I'm trying to build signup and signin using flask + sql + sqlalchemy. I tried many methods to extract specific data from columns. but when i give query, it just return named tuple. like [, ] I just want to get userid from columns. Any help? This is my code

app.py

@app.route('/login', methods=['GET','POST'])  
def login():
    form = LoginForm()
    user_id = form.data.get('userid')
    keyword = "%{}%".format(form.data.get('userid'))
    addr = User.query.filter(User.userid.like(keyword)).all()
    print(addr)


    return render_template('login.html', form=form)

and this is my sql table column

在此处输入图像描述

and this is what i returned

 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 161-830-439
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[<User 2>]
127.0.0.1 - - [18/Mar/2021 13:00:32] "POST /login HTTP/1.1" 200 

I just want to get userid using list. like this

['min', 'test1234']

any help?

What you are trying to do does not sound like what you would expect from a login view function. You would expect a login view function to check the credentials of a user and then log them in if they are a registered user, by either using flask_login or storing the user details in a session. You are doing none of that. So I would suggest you revisit what it is you are trying to achieve in this login view.

To answer the specific question you asked, if you want to get the userid of all the users in your database, I would run:

useridList = []
users = User.query.all()

for user in users:
    useridList.append(user.userid)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 161-830-439
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[<User 2>]
127.0.0.1 - - [18/Mar/2021 13:00:32] "POST /login HTTP/1.1" 200 

I can see the variable addr which stores User object getting printed in the line ( [<User 2>] ). However if you want to select only specific columns, then use:

addr = User.query.with_entities(User.userid).filter(User.userid.like(keyword)).all()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM