I have a query set, categories = unipart.categories.all(), which is all the categories that a unipart object is linked to.
However, I’d like to remove the top-level categories from this list — ie. those with subcategories that the unipart is also listed within.
Or those categories with a parent_id equal to one of the category_ids in the queryset.
For example if a unipart was listed in:
Nutmeg (parent= Spices) and
Spices (parent = Food)
then I’d want to ONLY include Nutmeg — so basically I want to ‘pop’ Spices from the queryset.
What is the best way to do this? I would rather not use a list.
Here’s my models:
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):
Your can exclude those categories who has a child category binded to this unipart item:
Here
categorieschildis de related name for the categories children.