How to dynamically change variable name in form.vars.var_name

ぃ、小莉子 提交于 2019-12-12 05:28:48

问题


I have defined counter variable in controller.

I can define tables and fields dynamically.

tables = [db.define_table('example_table_%s' % x,
    Field('example_field_%s' % x, type='string', ...)
    ...
    )
    for x in range(0, counter+1)]

I can add defined tables to SQLFORM.

form = SQLFORM.factory(
    db.table_1,
    db.table_2,
    *tables,
    submit_button='Submit')

I can control process manually if the counter value is '2'.

if form.process.accepted():
    id = db.table_1.insert(**db.table_1._filter_fields(form.vars))
    form.vars.table_1_field = id
    id = db.table_2.insert(**db.table_2._filter_fields(form.vars))

    #'0'
    form.vars.table_2_field = form.vars.example_field_0
    id = db.table_2.insert(**db.table_2._filter_fields(form.vars))

    #'1'
    form.vars.table_2_field = form.vars.example_field_1
    id = db.table_2.insert(**db.table_2._filter_fields(form.vars))

    #'2'
    form.vars.table_2_field = form.vars.example_field_2
    id = db.table_2.insert(**db.table_2._filter_fields(form.vars))

Above code works on my application.

How do I dynamically do the #'0', #'1' and #'2' steps?


回答1:


for i in range(0, counter + 1):
    form.vars.table_2_field = form.vars['example_field_%s' % i]
    db.table_2.insert(**db.table_2._filter_fields(form.vars))

Also, if you are not using the dynamically generated tables to store data in the database, be sure to set migrate=False in the table definitions -- otherwise, the DAL will actually create each of those tables in the database.



来源:https://stackoverflow.com/questions/34314669/how-to-dynamically-change-variable-name-in-form-vars-var-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!