I have following application:
from django.db import modelsclass Worker(models.Model):name = models.CharField(max_length=60)def __str__(self):return self.nameclass Job(models.Model):worker = models.ForeignKey(Worker)is_completed = models.BooleanField()
I want to annotate Workers query with count of completed jobs.
I'll try to do it with following script:
from myapp.models import Worker, Job
from django.db.models import Countw = Worker.objects.create(name='Worker1')
Job.objects.create(worker=w, is_completed=False)
Job.objects.create(worker=w, is_completed=False)
Job.objects.create(worker=w, is_completed=True)
Job.objects.create(worker=w, is_completed=True)workers = Worker.objects.all().annotate(num_jobs=Count('job'))
workers[0].num_jobs
# >>> 4
workers = Worker.objects.all().exclude(job__is_completed=False).annotate(num_jobs=Count('job'))
# >>> []
Result of the last query is empty. How to exclude elements from reverse relation?
Django 1.8, python 2.7
UPD. I would like to have all workers in queryset, even those, who has a zero jobs