J
J
jonikwm2016-06-06 09:57:48
Django
jonikwm, 2016-06-06 09:57:48

Mptt. How to filter categories?

Hello. I've already broken my head.
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'Категория', 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)

How do I get a tree list of categories that have a "Product" with a specific "Vendor"?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2016-06-06
@fox_12

Requests of this kind as an option:

my_branch = some_genre_node.get_children().product_set.filter(vendor=some_vendor)

G
gromsterus, 2016-06-18
@gromsterus

If I understand the question correctly

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 the "name" fields and add to Genre (will build branches, sorting on the 'name' field)
class MPTTMeta:
    order_insertion_by = ['name']

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question