Last Updated: July 17, 2019
·
7.785K
· nabucosound

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'))