You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django点击商品跳转详情页功能异常的问题求助

问题分析与解决方案

你的问题核心不在select_related的使用,而是跳转链接未传递商品标识、详情页视图未正确获取单个商品数据,查询操作不会破坏数据表,放心调整即可。

1. 修复商品列表页的跳转链接

当前所有商品的跳转链接都是item,无法区分具体商品,详情页自然不知道要展示哪一个。需要给每个链接添加商品ID参数:

修改列表页模板中所有<a href="item"的部分,替换为带商品ID的URL:

<!-- 图片链接示例 -->
<a href="{% url 'item' product.id %}"><img class='product-image' src='{{product.product_picture.url}}' alt=""></a>

<!-- 标题、价格、描述等其他链接同理修改 -->
<a href="{% url 'item' product.id %}">{{product.name}}</a>
<a href="{% url 'item' product.id %}">${{product.price}}</a>
<a href="{% url 'item' product.id %}">{{product.desc}}</a>
<a href="{% url 'item' product.id %}">Special Offer</a>

另外注意:div标签没有href属性,你模板里的<div href="item"是无效代码,直接删除这些href属性即可。

2. 配置URL路由

在项目的urls.py中,给详情页添加带参数的路由规则:

from django.urls import path
from . import views

urlpatterns = [
    path('store/', views.store, name='store'),
    # 新增带商品ID参数的路由
    path('item/<int:product_id>/', views.item, name='item'),
]

3. 修复views.py的item函数

原代码中select_related()未指定关联模型,且返回的是所有商品的查询集,不是单个商品。修改为根据ID获取对应商品:

from django.shortcuts import render, get_object_or_404
from .models import Product

def item(request, product_id):
    # 使用get_object_or_404,找不到商品时返回404页面,比直接get()更友好
    item = get_object_or_404(Product, id=product_id)
    return render(request, "item.html", {"item": item })

def store(request):
    products = Product.objects.all()
    return render(request, 'store.html', {'products': products})

如果你的Product模型有外键关联(比如关联用户),需要提前加载关联数据优化性能时,才需要用到select_related,比如get_object_or_404(Product, id=product_id).select_related('user'),当前场景不需要额外添加。

4. 验证详情页模板

现在详情页模板中的{{item.name}}可以正确显示对应商品的名称,你可以按需添加其他商品字段(如价格、描述等)。

内容的提问来源于stack exchange,提问作者kyudotkyu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 15:40:21