如何使用字符串从表单访问嵌套属性?

How can I use a string to access a nested attribute from a form?

我在使用 Flask WTF 和此命名约定的表单中有几个元素...

# req_app_qty
# req_app_note
# req_main_qty  
# req_main_note
# req_side_qty
# req_side_note
# req_bread_qty
# req_bread_note
# continued... 

我可以像这样手动访问表单数据...

print "Manually (qty): " , form.req_app_qty.data     # works fine
print "Manually (note): " , form.req_app_note.data   # works fine

但我正在尝试以更自动化的方式访问此表单数据...

categories = [ "app", "main", "side", "bread", "dessert", "bev", "uten", "cups", "misc"]
for x in categories:
    field1 = "req_%s_qty.data" % x    # create a string to represent the attributes
    field2 = "req_%s_note.data" % x   # create a string to represent the attributes
    qty_rqst = form.field1.data           # fails
    rqst_note = form.field2.data          # fails

    # also tried        
    print "QTY=", getattr(form, field1)   # fails  
    print "Note:", getattr(form, field2)  # fails

以上这些方法我都试过了,都失败了...

第一种方法行失败并出现错误,指出表单没有属性 'field1' 或 'field2'.

至于第二种访问表单数据的方法,以下行失败并显示没有属性的错误 'req_app_qty.data'

print "QTY=", getattr(form, field1)   # fails  

如何创建一个字符串来访问这些表单属性?

qty_rqst = form.field1.data           # fails

这不起作用,因为您正在尝试访问不存在的字段 field1

print "QTY=", getattr(form, field1)   # fails

这不起作用,因为您正在尝试访问不存在的字段 req_X_qty.data

您需要访问存在的字段,例如

print 'QTY=', getattr(form, 'req_app_qty').data