Berislav Lopac
Berislav Lopac

Reputation: 17243

Django query to retrieve items that are selected as foreign keys?

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

Answers (2)

frnhr
frnhr

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

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53981

# Get all countries that have at least one city
Country.objects.exclude(city__isnull=False) 

Upvotes: 1

Related Questions