Search code examples
djangodjango-modelsdjango-querysetdjango-filter

How to start Count from 0 in django annotation?


I have the following code to count tickets related to each event.

class EventManager(models.Manager.from_queryset(EventQuerySet)):
    def get_queryset(self):
        attendees_count = Sum(Case(
            When(~Q(ticket__ticket_number=""), then=1),
            output_field=models.IntegerField()
        ))
        return super(EventManager, self).get_queryset().annotate(attendees_count=attendees_count)

the

When(~Q(ticket__ticket_number=""), then=1)

part exculdes all tickets which do not have a ticket number. It works well for events where is more than one valid ticket (if 4, shows 4). However, when there is no ticket associated, it returns 1. Behaviour is like so; 0 related tickets - returns 1, 1 related ticket - 1, 2 related tickets - 2 etc.

How to start counting from 0? so 0 related tickets - returns 0?


Solution

  • Solution found - for a future reference;

    the Case had to be extended for a not null primary keys filter as when the FK relation does not exist, ~Q(ticket__ticket_number="") will return True

    Therefore the solution is

    When(Q(ticket__id__isnull=False) & ~Q(ticket__ticket_number=""), then=1)