将用户输入值与数据库中表中的所有其他值进行比较

时间:2017-04-30 10:45:40

标签: web2py

在我的web2py控制器中,我有一个函数将用户输入值与数据库中的表中的值进行比较,但问题是只比较数据库中的第一个值,第二个值与之后的其他值不进行比较用户输入的值!!!
CODE:

def bMarket():
key=db(db.regKeys).select(db.regKeys.ALL)
for k in key:
    if request.vars.regCode == k.regKey:
        message="Correct Key"
        return DIV(message, _style="color: white; border: solid 1px green; width: 160px; background-color: green; font-weight: bold; padding: 3px; border-radius:5px;")
    else:
        return DIV("Incorrect Key", _id="regCodeTarget", _style="color: white; border: solid 1px red; width: 160px; background-color: red; font-weight: bold; padding: 3px; border-radius:5px;")<br />

我做错了什么???如何将用户输入的值与数据库中的所有其他值进行比较而不仅仅是第一个?**请帮助!!!

1 个答案:

答案 0 :(得分:0)

for循环中的代码检查密钥,如果不匹配,则会立即返回&#34;不正确的密钥&#34;响应。相反,你应该循环遍历所有记录,只返回&#34;不正确的密钥&#34;循环完成后:

def bMarket():
    key=db(db.regKeys).select(db.regKeys.ALL)
    for k in key:
        if request.vars.regCode == k.regKey:
            message="Correct Key"
            return DIV(message, _style="color: white; border: solid 1px green; width: 160px; background-color: green; font-weight: bold; padding: 3px; border-radius:5px;")
    return DIV("Incorrect Key", _id="regCodeTarget", _style="color: white; border: solid 1px red; width: 160px; background-color: red; font-weight: bold; padding: 3px; border-radius:5px;")

但是该方法效率很低,因为它需要将数据库中的所有记录加载到Python对象中,然后在Python中循环遍历每个记录。相反,您应该直接通过数据库查询(不需要从数据库加载任何数据)来处理查找:

def bMarket():
    key_exists = not db(db.regKeys.regKey == request.vars.regCode).isempty()
    if key_exists:
        return DIV(...)
    else:
        return DIV(...)

为了使查找更快,您可以在数据库的regKey列上创建索引。

相关问题