使用F引用2​​个表来更新python

时间:2013-08-08 04:43:54

标签: python mysql django performance updatemodel

我有一个脚本,使用2或3个表进行引用以更新数据库中的数据

下面是代码

getteam  = myteam.objects.only("id")  # [:2] limits the query to 2 just for testing
for i in getteam:
     gettraining = training.objects.get(teamID=i.id)    # because for now the traning table is empty

     getPrimary =  gettraining.primary
     if getPrimary  == 1 or getPrimary == 0 :
         getteamPlayers =  teamPlayers.objects.filter(teamId=i.id)
         for t in getteamPlayers :
             getmyplayer= myplayer.objects.get(id=t.playerId)
             getPlayerAge = getmyplayer.age     
             increase = max(0, (1+((MIDAGE - getPlayerAge) * MULTIPLIER) / 100) * 0.05 / 9)
             getvitals = vitals.objects.get(playerID=t.playerId)
             getvitals.velocity = min(max(getvitals.velocity + increase,0),1)  
             getvitals.power = min(max(getvitals.power + increase,0),1)  
             getvitals.arm = min(max(getvitals.arm + increase,0),1)  
             getvitals.ranges = min(max(getvitals.ranges + increase,0),1)  
             getvitals.save()
             print t.playerId

我在终端上运行这个脚本,我想使用像f类或更新这样的东西,因为它需要花费很多时间来更新,你能否建议我如何使用或增加插入时间的速度

1 个答案:

答案 0 :(得分:0)

可以在单个事务中运行更新功能,从而显着提升性能。

请查看Django database transaction management了解详情。 您可以考虑使用可以用作上下文管理器的django.db.transaction.commit_on_success

from django.db import transaction


with transaction.commit_on_success():
    # your code here

或作为功能装饰者:

from django.db import transaction


@transaction.commit_on_success
def update_function():
    # your code here