使用Django F()对象更新多列 [英] 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 stats - these represent the actual keys sent by the game
NumberOfJumps = models.IntegerField(default=0)
NumberOfDoubleJumps = models.IntegerField(default=0)
NumberOfSilverPickups = models.IntegerField(default=0)
NumberOfGoldPickups = models.IntegerField(default=0)
NumberOfHealthPickups = models.IntegerField(default=0)
我基本上得到了一个统计数字,需要添加到数据库中存储的当前统计信息中.
I basically get a dicitonary of stats that I need to to add to the current stats stored in the database.
我真的不想从模型中提取所有数据,然后再次对其进行更新,因为如果可能的话,我想在数据库级别执行此操作.
I really don´t want to pull all of the data out of the model and then update it again, as I would like to do this on the database level, if possible.
一位同事建议我使用django的F()对象将其从视图代码中推出,主要是为了使其保持线程安全并避免任何mysql死锁(状态表可能会不断更新通过不同的线程
A colleague suggested that I use django´s F() object in order to push this out of the view code, mostly in order to keep it thread-safe and avoid any mysql deadlocks (the stats table is potentially being updated continually by different threads)
该词典包含与数据库中使用的那些键相同的键,因此目前,我正在这样做:
The dictionary contains keys that mirror those used in the database, so at the moment I´m doing it like this:
def update_stats(new_stats):
player_stats = PlayerStats(user=user, **new_stats)
old_stats = player_stats.values()[0]
updated_stats = {}
for stat in new_stats:
if old_stat[stat]:
updated_stats[stat] = old_stats[stat] + new_stats[stat]
PlayerStats.objects.filter(user=user).update(**updated_stats)
有人知道如何使用F()对象实现此目标吗?
Anybody have any pointers as to how to achieve this by using the F() object?
推荐答案
要使用 models.F
更新,您需要构建类似
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,
...)
对于您的代码,可能是
new_stats = {
'NumberOfHealthPickups': 99
# ...
}
updated_stats = {}
for stat in new_stats:
updated_stats[stat] = models.F(stat) + new_stats[stat]
PlayerStats.objects.filter(user=user).update(**updated_stats)
这篇关于使用Django F()对象更新多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!