Reputation: 17243
So, imagine there is a model City
which has a foreign key Country
. In the database, some Countries were selected in one or more cities, and some in none.
How can we find only those countries that are selected in one or more cities, excluding those that aren't selected at all?
Upvotes: 1
Views: 119
Reputation: 12903
Try this:
from django.db.models import Count
Country.objects.annotate(city_count=Count('city_set')).filter(city_count__gt=1)
Docs here: https://docs.djangoproject.com/en/dev/topics/db/aggregation/#joins-and-aggregates
Upvotes: 0
Reputation: 53981
# Get all countries that have at least one city
Country.objects.exclude(city__isnull=False)
Upvotes: 1