Reputation: 5455
Sorry about the confusing title, but I don't know how to describe it better.
I need to run a model-function on the object I am editing using PUT in Django-Rest-Framework, which uses some of the new data from the PUT to calculate some new values it should save in the same model.
Example:
{'amount': 2, 'price': 0, 'total': 0}
is already stored in the database. update_total()
which I need to call to update the total field in the database (to, in this case 2 (2*1)).total=0
. After getting the object on new, total will be 2 as expected.I need the response to be 2 in the response from the PUT, not after a regrab of the object. But how?
I have tried several things (which all doesn’t work):
post_save()
in ListCreateAPIView
to update the data.pre_save()
in ListCreateAPIView
restore_object()
(even though it isn't for this purpose)Does this look like a bug? Or is there another trick?
Upvotes: 1
Views: 1114
Reputation: 5455
I kinda found a solution, but it feels somewhat dirty..
In my serializers restore_object I put code like this:
new_values = instance.update_counters()
for k, v in new_values.items():
self.data[k] = v
and in my models update_counters() function, I am returning a dict of what I changed..
Upvotes: 1