Updating model in Django based on dictionary values
<p>I have a dictionary in Django, contains a model's keys and some values. I want to update one of field (<em>score</em>) of the model (<em>A</em>) like this:
multiply that field for all the records to a constant, and then, if the record was found in the dictionary, add the corresponding dict value to the field. there are many records, and getting and then saving each object takes lots of time. I tried this update query, but it is not working:</p>

<p><code>A.objects.update(score=F('score') * CONST + (dictionary[F('key')] if F('key') in dictionary else 0))</code></p>

<p>the problem is that the condition seems to be false for all of the records, I tried to debug the problem, and it seems <code>F('key')</code> doesn't have the desired value (a string).</p>

<p>for further information, this line have the correct result:</p>

<p><code>a = A.objects.get(key='key1')
a.score * CONST + (dictionary[a.key] if a.key in dictionary else 0)</code></p>

<p>It doesn't make sense to use a dictionary lookup here; this is transformed into a single SQL query, the value of F() is not resolved in Python so there is no way it can be used to look up in a dictionary.</p>

<p>Instead you will probably have to use a <a href="https://docs.djangoproject.com/en/1.10/ref/models/conditional-expressions" rel="nofollow">conditional expression</a>.</p>

python sql django