Django exclude from annotation count

2024/10/12 16:25:30

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

Answer

update: ok I played a bit with this to generate the solution and I think I got it using Conditional Expressions:

Conditional expressions let you use if ... elif ... else logic withinfilters, annotations, aggregations, and updates. A conditionalexpression evaluates a series of conditions for each row of a tableand returns the matching result expression.

Note: Conditional Expressions (such as Case and When) are new in Django 1.8, as pointed out by @Pynchia

from django.db.models import IntegerField, Sum, Case, Whenworkers = Worker.objects.annotate(num_jobs=Sum(Case(When(job__is_completed=True, then=1),default=0,  output_field=IntegerField())))

now, each worker will have a num_jobs which will be an Integer that shows how many completed jobs that worker has :)

https://en.xdnf.cn/q/69632.html

Related Q&A

How to use yield function in python

SyntaxError: yield outside function>>> for x in range(10): ... yield x*x ... File "<stdin>", line 2 SyntaxError: yield outside functionwhat should I do? when I try to use …

Tkinter looks different on different computers

My tkinter window looks very different on different computers (running on the same resolution!):windows 8windows 7I want it to look like it does in the first one. Any ideas?My code looks like this:cla…

Sort when values are None or empty strings python

I have a list with dictionaries in which I sort them on different values. Im doing it with these lines of code:def orderBy(self, col, dir, objlist):if dir == asc:sorted_objects = sorted(objlist, key=la…

How to tell if you have multiple Djangos installed

In the process of trying to install django, I had a series of failures. I followed many different tutorials online and ended up trying to install it several times. I think I may have installed it twice…

Python Numerical Integration for Volume of Region

For a program, I need an algorithm to very quickly compute the volume of a solid. This shape is specified by a function that, given a point P(x,y,z), returns 1 if P is a point of the solid and 0 if P i…

invalid literal for int() with base 10: on Python-Django

i am learning django from official django tutorial. and i am getting this error when vote something from form. this caused from - probably - vote function under views.py here is my views.py / vote func…

How to use HTTP method DELETE on Google App Engine?

I can use this verb in the Python Windows SDK. But not in production. Why? What am I doing wrong?The error message includes (only seen via firebug or fiddler)Malformed requestor something like thatMy…

Python heapq : How do I sort the heap using nth element of the list of lists?

So I have lists of lists getting added to the heap; eg:n = [[1, 5, 93],[2, 6, 44],[4, 7, 45],[6, 3, 12]]heapq.heapify(n)print(n)This compares and sorts according to the lists first element.My question …

How strings are stored in python memory model

I am from c background and a beginner in python. I want to know how strings are actually stored in memory in case of python.I did something likes="foo"id(s)=140542718184424id(s[0])= 140542719…

The _imaging C module is not installed (on windows)

Im trying to generate some pdf with django/PIL/Imaging and everything is good until I attempt to put some images into the pdf:Exception Type: ImportError Exception Value: The _imaging C module is n…