简体   繁体   English

通过 for 循环将值保存到 django model

[英]Saving values to django model through a for loop

I want to use a dictionary to store values in a model through a modelform and a view.我想使用字典通过模型和视图将值存储在 model 中。 Today I solve it like this:今天我这样解决它:

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']

The keys in the dictionary are identical to the field names for the values I want to store.字典中的键与我要存储的值的字段名称相同。 I would like to make the function a bit more pythonic - something like this:我想让 function 更像 pythonic - 像这样:

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

However, I'm not sure how to use the Django ORM to achieve this.但是,我不确定如何使用 Django ORM 来实现这一点。 The fields I want to iterate are numbered 3-28 in the list of fields, so I guess I would have to slice the fields somehow and create a list based on that?我要迭代的字段在字段列表中编号为 3-28,所以我想我必须以某种方式对字段进行切片并基于此创建一个列表?

edit:编辑:

models.py模型.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)

There's a total of 30 variables like variable 1 following it.后面一共有 30 个变量,比如变量 1。

forms.py: 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 (up until iteration starts, excluded return render etc for simplicity) views.py (直到迭代开始,为简单起见,排除返回渲染等)

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']

You can use the built-in function setattr to set an attribute of your instance by name.您可以使用内置的 function setattr按名称设置实例的属性。 Iterate over the keys and values in your dict and use the keys as the attribute names when calling 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM