Alex Cuadra
Alex Cuadra

Reputation: 97

Show all products from category parent

im new in django, and im doing an ecommerce website. I have a problem, When I click on a subcategory its okay, it shows all the products of that subcategory. But I want to click on a category parent and show all the products that his children has, and i dont know how to do that. Here is my models:

class Category(models.Model):
parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null = True)
title = models.CharField(max_length= 200, null = True)
slug = models.SlugField(max_length=200, null = True) 
ordering = models.IntegerField(default = 0)

class Meta:
    verbose_name_plural = 'Categories'
    ordering = ('ordering',)

def __str__(self):
    return self.title


class Product(models.Model):
name = models.CharField(max_length = 255, null = True)
slug = models.SlugField(max_length=200)
category = models.ForeignKey(Category, related_name='products', on_delete = models.CASCADE)
parent = models.ForeignKey('self', related_name = 'variants', on_delete = models.CASCADE, blank = True, null = True)
brand = models.ForeignKey(Brand, related_name='products', null = True, on_delete = models.CASCADE)
description = models.TextField(blank = True, null = True)
price = models.FloatField(null = True)
disccount = models.BooleanField(default = False)
disccount_price = models.FloatField(blank = True, null = True)

image = models.ImageField(upload_to = 'images/',blank = True, null = True)
thumbnail = models.ImageField(upload_to = 'images/', blank = True, null = True) 
date_added = models.DateTimeField(auto_now_add = True)

class Meta:
    ordering = ('-date_added',)
def __str__(self):
    return self.name

Here is my view:

def category_detail(request, slug):
products = Product.objects.all()
subcategories = []

if slug:
    category = get_object_or_404(Category, slug=slug)
    products = products.filter(category = category)
    subcategories = Category.objects.filter(parent = category)



context = {
    'category': category,
    'subcategories': subcategories,
    'products' : products,
}

return render(request, 'category_detail.html', context)

So please I need some help:(

Upvotes: 1

Views: 332

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476669

You can filter on Products that belong to a subcategory of a category category with:

products = products.filter(category__parent=category)

or if you want Products that belong to the category or to a category with as parent the category, you can filter with Q objects [Django-doc]:

from django.db.models import Q

products = products.filter(
    Q(category__parent=category) |
    Q(category=category)
)

Upvotes: 1

Related Questions