Django annotation and reference field with F
Given the models:
class Supporter(models.Model):
...
class Campaign(models.Model):
....
supporters = models.ManyToManyField(Supporter)
supporters_needed = models.PositiveIntegerField()
If we want to get a queryset of the campaigns that have reached the number of supporters needed:
def campaigns_completed():
from django.db.models import Count
from django.db.models import F
return Campaign.objects.annotate(num_supporters=Count('supporters')).filter(num_supporters__gte=F('supporters_needed'))
Written by Hector Garcia
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#