2014-11-05 76 views
0

我有一个表名叫“代码”和3列:ID(主),码号(串)和激活(布尔值,默认值= FALSE)如何检查数据库中的现有值并更改它?

,我已经在这里我要检查值的形式,如果它存在,使其激活== False。

我想: myform.py:

#all imports here 
class CheckForm(Form): 
    some_code = StringField('Code: ',validators=[Required()]) 
    submit = SubmitField('Check it!') 

我views.py:

#all imports here 
@some.route('/sometest', methods=['GET', 'POST'] 
def check_function(): 
    form = CheckForm() 
    code=form.some_code.data 
    check_code = Codes.query.filter_by(code=code).first() 
    if check_code.activated == False: 
     check_code.activated = True 
     db.session.add(check_code) 
     db.session.commit() 
    elif check_code.activated == True: 
     print 'Code already used' 
    else: 
     print 'Code not found') 
return render_template('test.html') 

但我发现了错误:

AttributeError: 'NoneType' object has no attribute 'activated' 

我m使用烧瓶和sqlalchemy

+1

您的对象'check_code'为空,这意味着数据库中没有包含您的条件的行。 – badc0re 2014-11-05 10:46:42

回答

0

只需为check_code添加一个条件,以防在数据库中找不到结果。

提示:处理上面的失败条件和从函数返回时总是更具可读性。

def check_function(): 
    form = CheckForm() 
    code=form.some_code.data 
    check_code = Codes.query.filter_by(code=code).first() 
    if not check_code: 
     print 'Code not found' 
     return # You don't have to worry about that again 

    if check_code.activated == True: 
     print 'Code already used' 
     return # Second case is already covered 

    # That's the only case left, no need for an `if` condition 
    check_code.activated = True 
    db.session.add(check_code) 
    db.session.commit() 
+0

小问题在这里。现在,如果我第一次检查代码,它会打印'未找到代码',并且如果我再次执行此操作(打印'已使用的代码')。为什么我第一次收到'code not founds'? – bartezr 2014-11-05 11:20:39

+0

确保没有代码在每次访问时创建一个新条目。因为它听起来像你先调用这个函数(打印代码没有找到),那么你需要做一个form.save()或者在数据库中创建一个新条目的东西。 – Emam 2014-11-05 12:09:55

相关问题