显示所有来自父类别的产品

时间:2020-10-09 19:45:21

标签: django django-models django-views

即时通讯在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)

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

1 个答案:

答案 0 :(得分:1)

您可以使用以下方法对属于类别 Product 的子类别的category进行过滤:

products = products.filter(category__parent=category)

,或者如果您想要Product属于 category 或属于category且{em> parent 1}} ,则可以使用Q objects [Django-doc]进行过滤:

category