通过for循环将值保存到django模型

Saving values to django model through a for loop

我想使用字典通过模型窗体和视图在模型中存储值。今天我是这样解决的:

form.variable_1 = dictionary['variable_1']
form.variable_2 = dictionary['variable_2']
form.variable_3 = dictionary['variable_3']
form.variable_4 = dictionary['variable_4']
form.variable_5 = dictionary['variable_5']
form.variable_6 = dictionary['variable_6']

字典中的键与我要存储的值的字段名称相同。我想让这个函数更像 pythonic - 像这样:

for field in form: 
    form.field = dictionary['field']

但是,我不确定如何使用 Django ORM 来实现这一点。我要迭代的字段在字段列表中编号为 3-28,所以我想我必须以某种方式对字段进行切片并基于它创建一个列表?

编辑:

models.py

class MyModel(Model):
user = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE)
Instance_name = CharField(max_length=200, default='')
Instance_text = TextField(default='')
variable_1 = IntegerField(null=True)

后面跟变量1一​​共30个变量

forms.py:

class MyModelMF(ModelForm):
class Meta:
    model = MyModel
    fields = [
        'Instance_name',
        'Instance_text'
    ]

    widgets = {
        'Instance_text': Textarea(attrs={"style": "height:4em;" "width:25em;"})
    }

views.py(直到迭代开始,为简单起见排除了 return 渲染等)

def create_instance(request):
form = MyModelMF()
if request.method == 'POST':
    form = MyModelMF(request.POST)
    if form.is_valid()
        form = form.save(commit=False)
        form.user = request.user
        form.variable_1 = scores_dict['variable_1']

您可以使用内置函数 setattr 通过名称设置实例的属性。遍历字典中的键和值,并在调用 setattr

时使用键作为属性名称
if form.is_valid()
    form = form.save(commit=False)
    form.user = request.user
    for field_name, value in scores_dict.items():
        setattr(form, field_name, value)
    form.save()