Mptt. Как отфильтровать категории?

Всем привет. всю голову уже сломал.
Есть Модели:
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'Категория', null=True)
    name            = models.CharField(max_length=100)
    model           = models.CharField(max_length=50, default='Модель')
    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)


Как мне получить древовидный список категорий в которых есть "Product" c определенным "Vendor"?
  • Вопрос задан
  • 493 просмотра
Пригласить эксперта
Ответы на вопрос 2
fox_12
@fox_12 Куратор тега Django
Расставляю биты, управляю заряженными частицами
Запросы такого вида как вариант:
my_branch = some_genre_node.get_children().product_set.filter(vendor=some_vendor)
Ответ написан
Комментировать
@gromsterus
Если правильно понял вопрос
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)

Можно добавить индексы по полям "name" и добавить в Genre (будет строить ветки, сортируя по полю 'name')
class MPTTMeta:
    order_insertion_by = ['name']
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы