TMOTTM
TMOTTM

Reputation: 3391

How to filter related objects of related objects in Django?

Imagine a data model where:

class Album(models):
    name = models.CharField

class Song(models):
    albums = models.ManyToManyField(related_name="albums")

class Word(models):
    songs= models.ManyToManyField(related_name="songs")
    category = model.Charfield() # can be "friendly", "expletive", etc.

I.e. an album has many songs and a song can be on several albums. Then a song consists of many words and the same word can be in multiple songs.

I'd like to construct a queryset consisting of all words where the category is "friendly", and which belong to all songs of an album.

Upvotes: 2

Views: 171

Answers (1)

Florin C.
Florin C.

Reputation: 613

Try this:

Word.objects.filter(category='friendly', songs__albums__name__contains='freedom')

You may need to write your own model manager (check out the documentation: https://docs.djangoproject.com/en/3.2/topics/db/managers/).

Upvotes: 2

Related Questions