I want to make a simple query:
with transaction.atomic():
Account.objects.select_for_update().filter(payments__status='PENDING', payments__created_date__lt=timezone.now()-timedelta(days=14)).update(balance=F('balance')+Sum(F('payments__amount') - F('payments__payment_fee__fee_amount')), payments__status='COMPLETED')
It turned out it wasn't simple at all. I've tried Subquery but alternatively get "Joined field references are not permitted in this query" or "FOR UPDATE is not allowed with GROUP BY clause"
Subquery doesn't work because aggregation doesn't work with select_for_update() locks. F() doesn't work because it is referencing foreign key fields...
What's the best way to make this query work? Any idea?
- I am using postgresql behind the ORM.