0

我有一个查询集 , categories = unipart.categories.all()它是一个 unipart 对象链接到的所有类别。

但是,我想从这个列表中删除顶级类别——即。那些具有 unipart 也列在其中的子类别。

或者那些 parent_id 等于查询集中的 category_id 之一的类别。

例如,如果 unipart 列在:Nutmeg (parent = Spices) 和 Spices (parent = Food)

那么我只想包括 Nutmeg——所以基本上我想从查询集中“弹出”Spices。

做这个的最好方式是什么?我宁愿不使用列表。

这是我的模型:

class UniPart (models.Model):
categories=models.ManyToManyField(Category, related_name = 'unipart')

class Category (MPTTModel):
    category = models.CharField(max_length=250)
    oc_id= models.IntegerField()
    parent = TreeForeignKey('self', blank=True, null=True, related_name='children')
    def __unicode__(self):
4

1 回答 1

2

您可以排除那些将子类别绑定到此单部分项的类别:

categories = unipart.categories.exclude(
                 categorieschild__unipart = unipart).distinct()

categorieschild是子类别的相关名称。

于 2012-11-06T17:32:31.560 回答