Annotation help

here is my when conditions:

master_keyword_filter = [When(Q(headline__icontains=key) | Q(current_position__icontains=key), then=Value(1)) for key in master_keyword] if master_keyword else [When(Q(pk=None), then=Value(0))]

I got always 1 even both keywords are matched in the master_keywords:

master = queryset.annotate( master_keyword_count=Sum(Case(*master_keyword_filter, default=Value(0), output_field=IntegerField()))

like I passed ["python","django"] and these both keywords are present in the records but the master_keyword_count only return 1 rather than 2

The problem is with how the Case statement is being evaluated with multiple When conditions. In your current setup, it’s returning 1 as soon as any condition is met, rather than summing up all matches.

I suggest, instead of using Case/When, try to create separate annotations for each keyword
and then sum them up, if that is your goal.

Thank you, I got it.