Alouani Younes
Alouani Younes

Reputation: 1036

Get all possible values ​of a M2M field in a model

I have three models :

class Country(models.Model):
    name = models.CharField(max_length=200)

class City(models.Model):
    name = models.CharField(max_length=200)
    country = models.ForeignKey(Country,on_delete=models.CASCADE)

class Restaurant(models.Model):
    city = models.ManyToManyField(City)

In my database, there is 120 cities and 25 countries. But the restaurants created are located in 20 cities only.

Problem : I need a query to retrieve all the cities where my restaurants are located. And another query to retrieve all the countries where my restaurants are located.

Solution :

For the first query, i used the idea proposed by @Daniel Roseman :

City.objects.exclude(restaurant=None)

For the second query, I kept getting empty queryset. I had to user filter :

Country.objects.exclude(city__restaurant__isnull=False).distinct()

Upvotes: 2

Views: 253

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

You can just follow the relationships.

City.objects.exclude(restaurant=None)

and

Country.objects.exclude(city__restaurant=None)

Upvotes: 3

Related Questions