问题
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)
回答1:
Use the get_descendants() method of the MPTTModel
:
genres = album.genre.get_descendants(include_self=True)
albums = Album.objects.filter(genre__in=genres)
来源:https://stackoverflow.com/questions/28973969/how-do-i-filter-for-all-descendants-of-a-foreignkey-mptt-model