0

嗨,我有一个脚本,它使用 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 类或更新之类的东西,因为更新需要很长时间,你能建议我如何使用或提高插入时间的速度吗

4

1 回答 1

0

在单个事务中运行更新功能可以显着提高性能。

查看Django 数据库事务管理以了解详细信息。您可以考虑使用可用作上下文管理器的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
于 2013-08-08T08:19:09.820 回答