0👍
That’s not really how you’d use the F object. Once you separate the steps of fetching from saving you’re in essence making it explicitly non-atomic.
You should use update
for that, so the item part should be:
Item.objects.filter(id=reservation.item.id).update(available=F('available')-reservation.quantity)
Or something similar.
-2👍
F() expressions are for use within a query, eg, when you want to do this in SQL:
SELECT * FROM foo WHERE foo_col = bar_col
You’d do:
Foo.objects.filter(foo_col=F('bar_col'))
At any rate, your requirement that an item should only be decreased according to the last reservation made means that you have to get a bit creative with how you’re looping through the reservations. One option would be to order the queryset by item id, and each time the id “changes”, adjust the available amount based on that item’s last reservation.
- [Django]-Django-rest-swagger doesn't work when I want to use get_serializer_class() to return different fields for different user based on the url parameters
- [Django]-Redirect http to https safely for Heroku app
- [Django]-How to connect Celery worker to django test database
Source:stackexchange.com