如何过滤ForeignKey MPTT模型的所有后代? [英] How do I filter for all descendants of a ForeignKey MPTT Model?

查看:83
本文介绍了如何过滤ForeignKey MPTT模型的所有后代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是情况.我正在Django中利用MPTT模型创建音乐流派的层次结构(Rock,Hard Rock等).我正在将此层次结构的节点之一分配给相册".假设我使用Hard Rock流派创建了一个Album对象.如何在我的专辑中查询所有Rock专辑,并使其包含Rock以及Rock类型的所有后代?

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)

推荐答案

使用 get_descendants() :

Use the get_descendants() method of the MPTTModel:

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

这篇关于如何过滤ForeignKey MPTT模型的所有后代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆