1

Django beginner here. I have a many-to-many model and want to update multiple values at once.

This is the model (simplified):

class Inventory(models.Model):
    item = models.ForeignKey(Items, models.CASCADE)
    player = models.ForeignKey(Players, models.CASCADE)
    count = models.PositiveIntegerField()

What I do right now is this:

for key in dict:
    change_value = Inventory.objects.get(player=player, item=key)
    change_value.count += dict[key]
    change_value.save()

At least on my HDD test environment this is very slow. Is there a more efficient way of doing this? In other posts it was suggested to use update instead, so this would be:

for key in dict:
    Inventory.objects.get(player=player, item=key).update(count=dict[key])

Would this be faster? Could this be improved even further by updating multiple entries at once? Also, is there an efficient way of adding multiple new entries?

1 Answer 1

1

It is better to use .filter(..) over .get(..) since then the number of queries is half, so:

for k, v in data.items():
    Inventory.objects.filter(player=player, item=k).update(count=v)

Alternatively you can even perform the mapping in a single query with:

from django.db.models import Case, PositiveIntegerField, Value, When

Inventory.objects.filter(player=player, item__in=data).update(
    count=Case(
        *[When(item=k, then=Value(v)) for k, v in data.items()]
        output_field=PositiveIntegerField()
    )
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.