2

I have the following code:

obj = Products.objects.filter(dump__product_name = 'ABC, dump__product_color = 'black').values()
new_price = [100, 200, 300]

for item in range(len(obj)):
   obj[item]['price'] -= new_price[item]

Products.objects.filter(dump__product_name = 'ABC, dump__product_color = 'black').bulk_update(obj, ['price'])

But I am getting the error, Exception inside application: 'dict' has no attribute 'pk'

The value of obj looks like this:

<QuerySet [{'id': 1, 'product_name': 'Acer - Laptop', 'price': 350}, 
           {'id': 1, 'product_name': 'Dell - Laptop', 'price': 450}, 
           {'id': 1, 'product_name': 'Samsung- Laptop', 'price': 650}]>

I am unable to figure out what's wrong with the code. Any help would be much appreciated. Thanks a lot in advance

Shiny
  • 115
  • 1
  • 9

2 Answers2

1

The QuerySet.values method returns a sequence of dicts, but QuerySet.bulk_update takes a sequence of model instances, not dicts. You should iterate over the QuerySet returned by the filter method for a sequence of model instances that you can make changes to instead, and you also don't have to filter again when you perform bulk_update because it's performed on instances of specific primary keys:

items = list(Products.objects.filter(dump__product_name='ABC', dump__product_color='black'))
new_prices = [100, 200, 300]

for item, new_price in zip(items, new_prices):
   item.price -= new_price

Products.objects.bulk_update(items, ['price'])
blhsing
  • 91,368
  • 6
  • 71
  • 106
1

You should not use .values() since that will create dictionaries instead of model objects, and thus does not offer all the functionality the model provides.

You can work with:

obj = list(Products.objects.filter(
    dump__product_name = 'ABC', dump__product_color = 'black'
))
new_price = [100, 200, 300]

for item, prc in zip(obj, new_price):
   item.price -= prc

Products.objects.bulk_update(obj, ['price'])
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555