Reputation: 27
I have 3 Django models like this
Request
is a donation request, RequestItem
denotes how many instances of the name
item are needed, Donation
denotes how many donations have been done for the connected item
class Request:
pass
class RequestItem:
name
request = ForeignKey(Request)
needed = IntegerField()
class Donation:
item = ForeignKey(RequestItem)
donated = IntegerField()
A RequestItem a is said to be complete if
a.needed == Sum(donation.donated for each donation in a.donation_set.all()
A Request r is said to be complete if
For every RequestItem ri in r.request_item_set.all(); ri is complete
I need to filter out the requests which are complete/aren't complete.
Upvotes: 0
Views: 113
Reputation: 1294
If you are sure sum of 'donated' will never exceed value of 'needed' for every request item, you could do this way:
from django.db.models import Sum, F
Request.objects.annotate(needed=Sum('requestitem__needed', distinct=True), donated=Sum('requestitem__donation__donated')).filter(donated__gte=F('needed'))
Here sum of all donations per request is compared against sum of all 'needed' values for the same request. If former is greater or equivalent, request could be considered as completed
Upvotes: 1