Python如何使用POST变量作为对象参数

2024-04-20 09:29:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我该怎么做:

reader = csv.reader(open(file_path, 'rb').read().splitlines(), delimiter=";")
p = Product()

for key, row in enumerate(reader):
    f = request.POST.get('select_%s' % key) // ex. productname
    p.f = row[key] // HOW TO?, p.f should be "productname" from the variable

希望你能帮助我!你知道吗


Tags: csvpathkeyinforreadopenproduct
1条回答
网友
1楼 · 发布于 2024-04-20 09:29:26

使用setattr在运行时基于名称设置对象的属性:

reader = csv.reader(open(file_path, 'rb').read().splitlines(), delimiter=";")
p = Product()

for key, row in enumerate(reader):
    f = request.POST.get('select_%s' % key) // ex. productname
    // p.f should be "productname" from the variable
    setattr(p, f, row[key]) 

相关问题 更多 >