4

Let's say I have a model Album:

class Genre(MPTTModel):
name = models.CharField(max_length=50, unique=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)

And a model called Album like this

class Album(models.Model):
    name = models.CharField(..)
    ...
    genre = models.ForeignKey(Genre)

Let's also assume I have the following Genres:

Rock
- Hard Rock
- Classic Rock
Pop
    ....

Is it possible to filter all albums that have genres (or ancestor genres) ids in a list?

Basically, what I want to do:

Album.objects.filter(genre__ancestors__in=[id_of_rock, id_of_classical])

The closest thing I found is this:

genre_list = []
for id in genres:
    genre_list.append(Genre.objects.get(pk=id).get_ancestors(include_self=True)
Album.objects.filter(genre__in=genre_list)

But that's pretty expensive. I'm sure it can be done in a single query using some MPTT strategy, but I couldn't find a thing online. Any help?

XelharK
  • 598
  • 8
  • 21

0 Answers0