如何访问查询集中django中模型的子项

How to access childern of a model in a query set django

我有一个产品模型和一个类别模型: 每个产品可以有多个类别,每个类别可以有多个子类别 例如:

类别:

-Digital devices:
    -laptop
    -smartphone
    -PC

产品:

Mylaptop1
    -category=laptop
Myphone2
    -category=smartphone

我想使用父类别过滤产品,例如当用户到达此地址时:mysite。com/products/digital-devices我想同时显示 Mylaptop1 和 Myphone2。 我没有过滤子类别的问题,但我如何使用查询集中的父类别进行过滤。

models.py:

class Category(models.Model):

    name=models.CharField(max_length=200, db_index=True),
    slug=models.SlugField(max_length=200, unique=True, allow_unicode=True)
    parent = models.ForeignKey('self', default=None, null=True, blank=True, 
                                  on_delete=models.SET_NULL,related_name="children")

class Product(models.Model):

    name=models.CharField(max_length=200, db_index=True),
    slug=models.SlugField(max_length=200, db_index=True, allow_unicode=True),
    description=models.TextField(blank=True),  
    category = models.ManyToManyField(Category, related_name='products')

views.py

def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
photos = ProductImage.objects.all()

if category_slug:
    category = get_object_or_404(Category,slug=category_slug)

    products = products.filter(category=category) # query for sub categories
    products = products.filter(category__in=[category.children.all]) # i tried to use this query set to get products using parent category but it does not work

那么我如何使用父类别访问具有子类别的产品

您可以通过 parent

字段过滤 sub-category
parent_category = Category.objects.get(slug='DigitalDevices')    
products = products.filter(
    category__in=Category.objects.filter(parent=parent_category)
)