Problem with bulk_update

These lines of code should apply changes made by users to the same field ‘score’ in several objects:

  if form.is_valid():
    for key,value in form.cleaned_data.items():
      an_id = int(key)
      a_new_score = float(value)
      obj = qs.filter(struct_id=an_id).get()
      print('new score for',an_id,'will be:',a_new_score)
      #1 obj.score=new_score
      #2 print('score for',an_id,'was _not_ changed to', obj.score,'?!')
      obj.update(score=a_new_score)

    qs.bulk_update(list(qs),['score'])
 

where qs is a queryset of those several objects to be changed.

The code runs and does the expected, but it queries the database at every turn of the loop,
and the final bulk_update is superfluous and may (should!) be omitted.

On the other side, if I uncomment #1 then nothing gets done, as #2 would show if executed.

So I have 2 questions: 1) how should I rewrite commented line #1 so that no queries are done in the loop, and 2) what is actually achieved by my present line #1, that gets executed without errors?

Thank you!

What is qs? Where is it defined in the view?

Yes, the excess queries are caused by the different filter/get modifications.

For us to provide alternatives, we would need to see the model as well. (It’s difficult to design a query without seeing what’s being queried.)

Also, it appears as if the bulk_update isn’t doing anything at all, because you’re not modifying the elements of qs. The .filter().get() combination is resulting in a different query to get a reference to obj, which may not be the same instance of obj as what exists in qs.

After studying yet again django documentation (although excellently written, I find the subject so hard that I don’t grasp it until I experience it in action) I let the individual updates in the loop stand as they are, and remove the final bulk_update. After all, my users are a few hundred and not millions.

As for my perplexity, I got from my study some hint that it may have something to do with queryset laziness; some day or other I will figure it out completely.

Thanks Ken for your answer!