Reputation: 5456
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.
Upvotes: 0
Views: 458
Reputation: 2830
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.
Upvotes: 1