Update Multiple Columns Using Django F() Object
I have a model that stores stats on a one integer stat per column basis. I have a view that handles the update of said stats, like so: class PlayerStats(models.Model): #In game
Solution 1:
To update using models.F
, you need to construct something like
qs.update(field_1=models.F('field_1')+field_1_delta,
field_2=models.F('field_2')+field_2_delta,
...)
For you code, it might be
new_stats = {
'NumberOfHealthPickups': 99
# ...
}
updated_stats = {}
forstatin new_stats:
updated_stats[stat] = models.F(stat) + new_stats[stat]
PlayerStats.objects.filter(user=user).update(**updated_stats)
Solution 2:
One option is to update the fields one by one.
This code will not update all fields at once (so it might be slow, db-access-wise), but it is safe (no deadlocks, no lost updates).
user_stats = PlayerStats.objects.get(user=user)
forstat, increment in new_stats.iteritems():
user_stats.update(**{ stat: F(stat) + increment })
Post a Comment for "Update Multiple Columns Using Django F() Object"