I need to update a couple of objects using update(), but not the save() method.
Is it possible to cast a model to a queryset to do that ?
Otherwise I tried something like:
objects = Article.objects.all()
ctype = ContentType.objects.get_for_model(Article)
objects.update( stats=process_data(F('id'), ctype) )
process_data gets other objects relatif to Article and after a calculation returns a float:
def process_data(object_id, content_type):
counts = Counter.objects.get(content_type=content_type, object_pk=object_id)
...
return float(calculation_based_on_counts)
Unfortunately this is not possible. I get a MultipleObjectsReturned exception:
counter.models.MultipleObjectsReturned: get() returned more than one Counter — it returned 15! Lookup parameters were {‘object_pk’: , ‘content_type’: }
Thanks for any help !
The
Fclass does not return a value, as your code expects it to.Fobjects are nodes in an expression.Fexpressions only allow a certain subset of operations, mainly boolean logic and arithmetic: not arbitrary functions. If you’re interested in how this works under the hood, look atdjango/db/models/expressions.py. It’s not as well documented as it could be.Without knowing what your calculation is, it’s not possible to say whether it’s possible with an
F. If you were, for example, updating the sum of some related objects you could do it by combiningaggregatewith anupdateusing anFexpression.