[Django]-Django count of related objects with conditions

2👍

Maybe you’re looking for something like this:

from django.db.models import Count, Sum, Case, When, IntegerField

Item.objects.annotate(
    count_subitems=Sum(
        Case(
            When(subitems__created_at__lte=datetime.now(), then=1)
        ),
        output_field=IntegerField()
    )
)
👤simon

1👍

Filter the Items that have at least one subitem matching, and then count all the subitems for that Item:

(Item.objects
    .filter(subitems__created_at__lte=datetime.now())
    .annotate(count_subitems=Count('subitems')))

Leave a comment