Flask-SQLAlchemy检查行是否存在

时间:2018-11-08 15:10:25

标签: python python-3.x flask flask-sqlalchemy

我已经看过this这样的问题,但到目前为止没有帮助。

因此,我正在尝试使用Flask-SQLAlchemy检查表中是否存在一行,到目前为止,没有任何帮助。

我当前的代码:

@app.route('/guilds/<guildid>')
def guildsettings(guildid):
    discord = make_session(token=session.get('oauth2_token'))
    user = discord.get(API_BASE_URL + '/users/@me').json()
    guilds = discord.get(API_BASE_URL + '/users/@me/guilds').json()
    row = Settings.query.all()
    exists = Settings.query.filter_by(db.exists().where(Settings.guildid==guildid)).scalar()
    print(exists)
    if exists == True:
        info = Settings.query.filter_by(guildid=guildid).first()
        return render_template("guild.html", id=guildid, guilds=guilds, User=user, prefix=info.prefix, logschannel=info.logschannel, modrole=info.modrole, adminrole=info.adminrole, welcomechannel=info.welcomechannel, welcomemessage=info.welcomemessage, dadbot=info.dadbot, music=info.music, funcmds=info.funcmds, weather=info.weather, wapikey=info.wapikey)
    else:
        return render_template("notinserver.html", guildid=guildid, link="https://discordapp.com/api/oauth2/authorize?client_id=xxxxxx&permissions=8&redirect_uri=xxxxxxx%2Fme&scope=bot&guild_id={}".format(guildid))

我不确定现在该怎么办。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

如果确实需要一个结果:

try:
    Settings.query.filter_by(db.exists().where(Settings.guildid==guildid)).one()
except sqlalchemy.orm.exc.NoResultFound:
    return False
except sqlalchemy.orm.exc.MultipleResultsFound:
    #do what ever you want to do if there is more than one result
return True