Y
Y
Yura Khlyan2019-09-27 13:08:35
Django
Yura Khlyan, 2019-09-27 13:08:35

Filtering by MP_Node tree?

I have models structure like this (Django-Oscar):

from treebeard.mp_tree import MP_Node


class Category(MP_Node):
    name = models.CharField(_('Name'), max_length=255, db_index=True)
    ...

class ProductCategory(models.Model):
    product = models.ForeignKey(
        'catalogue.Product',
        on_delete=models.CASCADE,
        verbose_name=_("Product"))
    category = models.ForeignKey(
        'catalogue.Category',
        on_delete=models.CASCADE,
        verbose_name=_("Category"))

I need to get all categories that have products, or have products in child categories. Can I somehow give such categories by means Djangoand filters QuerySet?
Option: get QS, then run through it and check if there are products in the category or in the child ones - I will use it in the end if nothing helps.
PS. If you decide vlob, then something like this:
qs = models.Category.objects.filter(
    depth=1, site=Site.objects.get_current()
)

categories_pks = []
for category in qs:
    category_descendants_and_self = category.get_descendants_and_self()
    for child_category in category_descendants_and_self:
        if models.Product.objects.browsable().filter(
            productcategory__category=child_category
        ).exists():
            categories_pks.append(category.pk)
            break
return models.Category.objects.filter(pk__in=categories_pks)

But how to speed up the code above?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question