Using F result for get key

I have dict like {product_id: count}.

For example cart_items = {1: 150}. This dict represents customer basket.

I also have product model with count field. It's representing stock balances.

I want to get products that is in dict and update their quantity according to values in dict.

I get products like this : products = Product.objects.filter(id__in=cart_items)

And I want to update the quantity like this: products.update(count=dict.get(F("id"))

But it doesn't work.

Thx!

You can do this, but it is very bad idea. Typically you make JOINs in the database, since databases are optimized for this. You can however work with a Case-When expression [Django-doc] for this:

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

products.update(
    count=Case(*[When(pk=k, then=Value(v)) for k, v in my_dict.items()])
)

This will thus "unwind" the my_dict into a (likely) long sequence of CASE WHEN … THEN …s. This will however result in linear search slowing down the updating process.

Back to Top