Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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. 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:

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

However, I’m not sure how to use the Django ORM to achieve this. 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

edit:

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)

There’s a total of 30 variables like variable 1 following it.

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)

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

>Solution :

You can use the built-in function setattr to set an attribute of your instance by name. Iterate over the keys and values in your dict and use the keys as the attribute names when calling 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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading