django queryset count

# Import necessary modules
from django.db.models import Count

# Define your queryset
queryset = YourModel.objects.all()

# Use annotate() to count the occurrences of a related model's field
# In this example, counting the occurrences of a ForeignKey field named 'related_field'
queryset = queryset.annotate(related_field_count=Count('related_field'))

# Filter the queryset as needed
# Example: Filter only records where the count is greater than a certain value
filtered_queryset = queryset.filter(related_field_count__gt=some_value)