0

I am implementing a function that gets a model class as a parameter, and should get a dictionary from the same model, set model fields to namesake keys in such dictionary, and save the model to the database.

This is the code of the function:

def populate_model(self, model_to_populate): model_to_populate_instance = model_to_populate() if hasattr(model_to_populate_instance, 'populate_data'): populate_data = getattr(model_to_populate, 'populate_data') for key, value in populate_data.items(): field = getattr(model_to_populate_instance, key) field = value model_to_populate_instance.save() 

Something is wrong because I don't get values from the dictionary in the database, but objects GeneralApp.models.CustomCharField>. I guess I am not succeeding to set the value of the model instance field to the value in the dictionary.

O would appreciate your help.

4
  • why is the data a field called populate_data? Commented Aug 20, 2018 at 3:03
  • @e4c5 it is not a field, it is a dictionary attribute with some information that must be populated to the database table related to the model Commented Aug 20, 2018 at 3:06
  • @HugoLuisVillalobosCanto What you mean by "and should get a dictionary from the same model" ? Commented Aug 20, 2018 at 3:27
  • @Jerin Peter George, that the model received as a parameter has a dictionary attribute that must be accessed (populate_data = getattr(model_to_populate, 'populate_data') Commented Aug 20, 2018 at 6:06

1 Answer 1

1

Replace the lines

 field = getattr(model_to_populate_instance, key) field = value 

with

 setattr(model_to_populate_instance, key, value) 

Reason: the return value of getattr is the value of the attribute, not a reference to the attribute itself (if it were a reference, it wouldn't make sense to set field = value anyway.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.