[Answered ]-Counting occurrences of a foreign key in a related queryset

2👍

The following query should work (or something similar depending on the related_name for the Visit to Store ForeignKey)

Store.objects.filter(
    visit_set__in=visit_queryset
).annotate(
    num_visits=Count('visit_set')
).filter(
    num_visits__gte=2
).count()

Filtering by visit_set__in=visits will “filter” the annotation to only count those visits

Leave a comment