Understanding F expression in Django
What I have done is -
prev_ordr = Order.objects.filter(abc).values("order_sl").first()
if prev_ordr:
new_order_sl = prev_ordr.get("order_sl")
else:
new_order_sl = 100000
ins.order_sl = F("order_sl") + (new_order_sl + 1)
ins.save()
ins.refresh_from_db()
return
But I'm not sure about this, this is loading the previous value into the python and not directly managing the database (i think so), as it should be in the case of F expression and it may fail race condition.
Can you let me know the correct way, I have to increase the value by 1 (from the last row) in the new row.
Thanks
The cleanest, most robust approach is to use a DB-side sequence (PostgreSQL’s CREATE SEQUENCE
or the django-sequences package) so that each order_sl
is allocated atomically by the database itself. If you cannot add a sequence, wrap your max-lookup and insert in a single transaction with select_for_update()
.