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

偶尔善良 提交于 2019-12-12 10:06:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!