Reputation: 169
I'm very new to Django so this question might be very basic.
I have a model called UserScores
, which contains 16 different score properties, each representing a user score based on the game he/she has played.
when a user plays a game and finish it, the score he gets in that game should be added to the related property in his/her UserScores object. so the code looks like this:
if game_name == "game_1":
self.game1_score += score
elif game_name == "game_2":
self.game2_score += score
...
in php I used to run a code like this:
obj.{game_name} += score
so no matter what the game name was, the correct property was edited,
Now my question is that,
Is there a dynamic way to access properties on a Django model objects?
Upvotes: 1
Views: 995
Reputation: 641
You can use getattr/setattr to achieve what you want. For example, to set the field value:
old_value = getattr(obj, field_name)
setattr(obj, field_name, old_value + score)
Upvotes: 6