Updating selection of objects, each with a different value in bulk (Django)

后端 未结 2 475
清酒与你
清酒与你 2021-01-02 00:02

Imagine I have a python dictionary where keys are existing user ids, and values are scores to be added to those users\' existing scores.

For example: {1: 1580

2条回答
  •  一向
    一向 (楼主)
    2021-01-02 00:26

    transaction.atomic() proposed by @nik_m is good idea, but also you should get records from database in single request.

    from django.db.models import F
    from django.db import transaction
    
    with transaction.atomic():
        scores = {1: 1580, 4: 540, 2: 678}
        users_to_update = UserProfile.objects.filter(
            user_id__in=scores.keys()
        ) 
        for user in users_to_update:
            user.update(score=F('score') + scores[user.user_id])
    

提交回复
热议问题