Django页面按分类展示产品列表问题求助
解决Django分类下产品展示问题的步骤
嗨,我来帮你搞定这个Django分类展示产品的问题!首先得确认你的Product模型是不是正确关联了Category——毕竟外键是连接两者的核心。先给你补全一下Product模型的示例(你可以根据自己的实际字段调整):
1. 完善Product模型(models.py)
from django.db import models from .models import Category # 确保导入Category模型 class Product(models.Model): title = models.CharField(max_length=255) # 外键关联Category,设置related_name方便反向查询 category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name='products' # 这个是关键!后面模板里要用到 ) # 其他字段比如价格、描述等可以按需添加 price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.title
2. 编写视图获取分类及对应产品(views.py)
为了避免N+1查询的性能问题,我们用prefetch_related预加载每个分类下的所有产品:
from django.views.generic import ListView from .models import Category class CategoryProductListView(ListView): template_name = 'products/category_products.html' # 替换成你的模板路径 model = Category def get_queryset(self): # 预加载每个分类关联的产品,优化查询效率 return Category.objects.prefetch_related('products').all()
如果习惯用函数视图,也可以这样写:
from django.shortcuts import render from .models import Category def category_products(request): categories = Category.objects.prefetch_related('products').all() return render(request, 'products/category_products.html', {'categories': categories})
3. 模板渲染分类与产品(category_products.html)
现在就可以在模板里循环遍历分类,再嵌套遍历每个分类下的产品了:
{% for category in object_list %} {# 类视图用object_list,函数视图用你传的变量名比如categories #} <h2>{{ category.title }}</h2> <div class="product-list"> {% for product in category.products.all %} <div class="product-item"> <h3>{{ product.title }}</h3> <p>价格: {{ product.price }}</p> <!-- 可以添加产品详情链接,比如用product.get_absolute_url() --> </div> {% empty %} <p>这个分类下还没有产品哦~</p> {% endfor %} </div> {% endfor %}
关键注意点
- 一定要给
ForeignKey设置related_name(比如上面的products),这样才能通过category.products反向查询到该分类下的所有产品 - 使用
prefetch_related可以大幅提升查询性能,避免每次循环分类都去数据库查一次产品 - 如果之前已经有
Product模型但没加related_name,也可以用默认的反向关联名:category.product_set.all,不过自定义related_name更清晰
内容的提问来源于stack exchange,提问作者Taufiq Rahman
相关产品推荐
相关产品推荐

