Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

python - Product filter for Django categories and subcategories

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'),

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...