Mptt. How to filter categories?

Hi all. all head already broke.
There Are Models:
class Genre(MPTTModel):
 name = models.CharField(max_length=100)
 position = models.IntegerField(null=True)
 onoff = models.BooleanField(default=True)
 url = AutoSlugField(populate_from='name', max_length=100, editable=True, blank=True, unique=True)
 imagea = ImageField(upload_to='cataog_image', blank=True)
 description = RichTextUploadingField(blank=True)
 parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)

 def __unicode__(self):
 return self.name

class Product(models.Model):
 category = TreeForeignKey(Genre, verbose_name=u Category', null=True)
 name = models.CharField(max_length=100)
 model = models.CharField(max_length=50, default='Model')
 url = AutoSlugField(populate_from='name', max_length=100, editable=True, blank=True, unique=True)
 img = ImageField(upload_to='product_image', blank=True)
 shortdes = models.TextField(blank=True)
 description = RichTextField(blank=True)
 vendor = models.ForeignKey('Vendor', null=True)

 def __unicode__(self):
 return self.name
class Vendor(models.Model):
 name = models.CharField(max_length=50)
 logo = ImageField(upload_to='cataog_image', blank=True)
 description = RichTextField(blank=True)


How do I get a tree list of categories in which there is a "Product" of a certain "Vendor"?
July 8th 19 at 16:27
2 answers
July 8th 19 at 16:29
Requests of this type as an option:
my_branch = some_genre_node.get_children().product_set.filter(vendor=some_vendor)
July 8th 19 at 16:31
If correctly understood the question
tree_ids_subquery = Genre.objects \
.filter(product__name=u 'Product',
 product__vendor__name=u 'Vendor') \
 .values_list('tree_id', flat=True) \
.distinct()

genres = Genre.objects.filter(tree_id__in=tree_ids_subquery)

You can add indexes on fields "name" and add the Genre (will build a branch, sorting on the field 'name')
class MPTTMeta:
 order_insertion_by = ['name']

Find more questions by tags DjangoPython