Updating the selection of objects, each of which has a different meaning (Django)

Imagine I have a python dictionary where the keys are existing user identifiers and the values ​​are the ratings that should be added to the existing ratings of these users.

For example: {1: 1580, 4: 540, 2: 678}(this can stretch to nk, v pairs)

I need to update the ratings of all these user objects (updated_score = original_score + new_score). One way to do this iteratively, for example:

from django.db.models import F
scores = {1: 1580, 4: 540, 2: 678}
for user_id,score_to_add in scores.iteritems():
    UserProfile.objects.filter(user_id=user_id).update(score=F('score')+score_to_add)

But these are a few database calls. Can I do this at a time? An illustrative example would be great. As you may have guessed, this is for the Django project.

+4
source share
2

- :

from django.db.models import F
from django.db import transaction

with transaction.atomic():
    scores = {1: 1580, 4: 540, 2: 678}
    for user_id,score_to_add in scores:
        UserProfile.objects.filter(user_id=user_id).update(score=F('score')+score_to_add)

.

[UPDATE]:

TL; DR: db, , .

docs @ahmed :

Djangos . , .

with transaction.atomic(), . , , , .

+1

transaction.atomic(), @nik_m, , .

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])
0

Source: https://habr.com/ru/post/1672040/


All Articles