django - 显示来自父类别的所有产品
问题描述
我是 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)
所以请我需要一些帮助:(
解决方案
您可以过滤Product
属于某个类别的子类别的 s category
:
products = products.filter(category__parent=category)
或者,如果您希望Product
s 属于category
或 a category
with as parent
the ,您可以使用对象 [Django-doc]category
进行过滤:Q
from django.db.models import Q
products = products.filter(
Q(category__parent=category) |
Q(category=category)
)
推荐阅读
- tensorflow - 如何从预训练的 TensorFlow 模型中删除层?
- javascript - 将丰富的消息集成到 Dialogflow fullfilment
- php - 更改 php DOMElement 的 outerHTML?
- eclipse - Qemu 如何定位其图像文件或 Eclipse 如何与 Qemu 交互?
- python - 从 Python 的 Azure 函数获取应用程序设置值(环境)
- django - IP 错误:Django 应用程序未使用 docker 部署
- python - 如何在 Python 中找到精确的字符串匹配?
- r - text2vec 文档相似度代码返回两个值
- python - 在 UPDATE sql 命令中使用变量值 - SQLite (Python)
- php - 如何 PHP appendChild 在 ID 中?