Vin
Vin

Reputation: 319

How to filter and access ManyToMany fields in a Django QuerySet?

Suppose I have the following models with a ManyToMany relationship:

class City(models.Model):
    name = models.CharField(max_length=100)

class Course(models.Model):
    name = models.CharField(max_length=100)
    cities = models.ManyToManyField(City)

Now I want to filter for the courses with a given name in a given city:

courses = Course.objects.filter(name='Course1', cities__name='City1')

Is it possible to access the City fields through the courses QuerySet? In this example, would it be possible to get 'City1' from courses only?

Thanks in advance.

Upvotes: 1

Views: 2607

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

You can use prefetch_related with a Prefetch object to do this.

city1 = City.objects.filter(name='City1')
courses = Course.objects.filter(name='Course1', cities__name='City1').prefetch_related(
    Prefetch('cities', queryset=city1)
)

Upvotes: 1

Related Questions