如何检查数据库中的现有值并进行更改?

时间:2014-11-05 10:42:33

标签: python flask sqlalchemy

我有一张名为' Codes'和3列:id(主要),codenumber(字符串)和激活(布尔值,默认= False)

我有一个表单,我想检查值,如果它存在,请激活== False。

我试图: myform.py:

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

my 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'

我正在使用flask和sqlalchemy

1 个答案:

答案 0 :(得分: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()