I am working with flask trying to update a mongodb collection which works fine when I state the fieldname that needs updated, but I want to fieldname to be a variable depending on which needs updated. This works fine to update the field:
Scoresenglish6.objects(user_id=user_id).update(E6001=str(score))
But, the fieldname being updated can change (so in this case it is "E6001") so I have the fieldname needing updated as a variable called field_name:
score = "10"
field_name = "E6001"
Scoresenglish6.objects(user_id=user_id).update(field_name=str(score))
Then I get the error:
mongoengine.errors.InvalidQueryError: Cannot resolve field "field_name"
obviously because there is no field name called field_name. Is there a way to do this? Thanks in advance, I'm a home coder working on a home project so apologies if this seems vague and not well explained.
You can use locals() to achieve what you want.
Try this:
score = "10"
field_name = "E6001"
Scoresenglish6.objects(user_id=user_id).update(locals()['field_name']=str(score))
Have a look at this tutorial to understand how locals()
work and how to use them.