Reputation: 19
There is a problem, confused in several things. Made some filter for categories, but it filters only for subcategories. When you click on the parent category, it's just a blank page, when you click on the child, everything is filtered well. And I got confused in the url, how do I output both the parent url and the child? I will be very grateful. Sorry for the Russian When i click on parent category pic, When I click on child category pic
models.py
class Category(models.Model):
parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=True, null=True)
name = models.CharField('Название', max_length=255)
slug = models.SlugField('Ссылка', unique=True)
def get_absolute_url(self):
return reverse('jewel:category_detail', args=[ self.slug])
views.py
def cat(request, cat_slug):
products = Product.objects.all()
main_categories = Category.objects.filter(parent=None)
sliders = Slider.objects.all()
cats = 0
if cat_slug:
category_s = get_object_or_404(Category, slug=cat_slug)
products = products.filter(category=category_s)
context = {
'products': products,
'main_categories': main_categories,
'category_s': category_s,
'sliders': sliders,
}
return render(request, 'jewel/category_detail.html', context)
urls.py
path('category/<slug:cat_slug>/', views.cat, name='category_detail'),
Upvotes: 1
Views: 951
Reputation: 169032
If you want to show all products within category_s
and all of its child categories (that is, products whose category's parent is category_s
), you can use a Q
object and a query like
products = products.filter(Q(category=category_s) | Q(category__parent=category_s))
However, with a deeper hierarchy this will become unwieldy to manage and I would suggest using either https://github.com/django-treebeard/django-treebeard or https://github.com/django-mptt/django-mptt for your Category model.
Upvotes: 4