Home > Mobile >  Can you iterate through model fields when you overwrite the save() method in django?
Can you iterate through model fields when you overwrite the save() method in django?

Time:04-09

I'm calling a custom save method in my model. The save method is designed to produce some values in the model based on the content of a TextField. This content is stored in a dictionary, and is generated correctly.

I'm trying to write a for loop to store the values of the dictionary. The keys correspond to the model field names:

def save(self, *args, **kwargs):
        if self.text != "":
            results_dict = analyze(self.text)
            for field_name in field_names_list:
                self.field_name = results_dict[field_name]

The value is not stored in the corresponding field. Do I need to use setattr here instead?

CodePudding user response:

Try this:

def save(self, *args, **kwargs):
   if self.text != "":
      results_dict = analyze(self.text)
      for field_name in field_names_list:
         setattr(self, field_name, results_dict[field_name])
   super().save(*args, **kwargs)
  • Related