Django annotation math operations

I have a Django model that defines TimeSlot. Each TimeSlot can contain a certain number of users ( TimeSlot.spots). Each TimeSlot also have a certain number of users who are already in it (many, many fields TimeSlot.participants.

When I move on to a template that displays the available TimeSlots to the user, I comment with the help TimeSlot.objects.annotate(Count('participants'))that gives the number of users that are currently stored in TimeSlot as participants__count.

However, I really want the number of spots remaining, capacity ( TimeSlot.spots) minus the number that is currently being held ( participants__count). How can I annotate another field with this new number, so I can pass it to the template?

+3
source share
2 answers

Impossible only with annotation. I would create a method on a model that annotates and then subtracted this from your value TimeSlot.spots. This will use more database queries, but this is the only option. Or I think you could go down to raw SQL ...

+1
source

This is still not possible with annotation (although it is planned to be implemented in Django). But you can do this with a query .extra(). See my answer to another question for more details .

Upd :.

Essentially, you need something like this query:

items = MyModel.objects.extra(
    select = {'variance': 'Model.someField - SUM(relatedModel__someField)'},
)
+2
source

Source: https://habr.com/ru/post/1752576/


All Articles