I have two models like so:
class Company(models.Model):
raising = models.DecimalField()
class Investment(models.Model):
company = models.ForeignKey(Company)
amount = models.DecimalField()
Now I want to find all companies where cumulative investments are less than raising
If I added a dynamic property to Company called raised_so_far that aggregated the investment amounts, I could do something like so:
Company.objects.filter(raised_so_far__lt=F('raising'))
but filtering happens at the SQL level so that's not possible.
So far, this is my best attempt:
Company.objects.filter(raising__gt=Investment.objects.filter(company=F(outer_company_object)).aggregate(Sum('amount'))['amount__sum'] or 0)
How do I filter on an aggregation of a foreign key using a parent object?