Ryan
Ryan

Reputation: 2660

How do I filter for all descendants of a ForeignKey MPTT Model?

Here is the situation. I'm utilizing an MPTT Model in Django to create a hierarchy of music genres (Rock, Hard Rock, etc). I'm assigning one of the nodes of this hierarchy to an Album. Let's say I create a Album object with Hard Rock genre. How can I query my Albums for all Rock albums and have it include Rock and all descendants of the Rock genre?

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

    class MPTTMeta:
        order_insertion_by = ['name']

    def __unicode__(self):
        return self.name


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

Upvotes: 2

Views: 1129

Answers (1)

catavaran
catavaran

Reputation: 45585

Use the get_descendants() method of the MPTTModel:

genres = album.genre.get_descendants(include_self=True)
albums = Album.objects.filter(genre__in=genres)

Upvotes: 5

Related Questions