首页 > 解决方案 > 显示来自父类别的所有产品

问题描述

我是 django 的新手,我正在做一个电子商务网站。我有一个问题,当我点击一个子类别时,它会显示该子类别的所有产品。但我想点击一个父类别并显示他孩子拥有的所有产品,但我不知道该怎么做。这是我的模型:

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

这是我的看法:

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)

所以请我需要一些帮助:(

标签: djangodjango-modelsdjango-views

解决方案


您可以过滤Product属于某个类别的子类别的 s category

products = products.filter(category__parent=category)

或者,如果您希望Products 属于category或 a categorywith as parentthe ,您可以使用对象 [Django-doc]category进行过滤:Q

from django.db.models import Q

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

推荐阅读