Ecomm中范畴与产品的多种关系

2024-04-25 16:45:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个电子商务使用Django和产品之间的关系和类别模型是多对多。也就是说,一个产品可以属于多个类别。你知道吗

在产品列表页面中有一个侧边栏,显示类别列表以及每个类别下的产品列表。我们使用产品的get\u absolute\u url方法链接到每个产品详情页面的url。你知道吗

问题是,在产品详细信息页面(模板)中,我不知道如何获取此产品的类别名称,因为此产品可能属于多个类别。我想用这个产品的类别做一个面包屑。你知道吗

产品型号

class AbstractProduct(models.Model):
...
categories = models.ManyToManyField(
        'catalogue.Category',
        through='ProductCategory',
        verbose_name=_("Categories"))
...
    def get_absolute_url(self):
        return reverse('catalogue:detail', kwargs={'product_slug': self.slug, 'pk': self.id})

产品列表模板(产品型号是产品的型号)

<a href="{{ prod.get_absolute_url }}" class="nav-link text-muted mb-2">{{ prod.model }}</a>

你知道吗网址.py你知道吗

from django.urls import path
from . import views

app_name = 'catalogue'

urlpatterns = [
    path('', views.list, name='list'),
    path('<slug:category_slug>/', views.list,  name='list_by_category'),
    path('<slug:product_slug>/<int:pk>', views.detail, name='detail'),
]

Tags: pathnameselfurl列表get产品页面
1条回答
网友
1楼 · 发布于 2024-04-25 16:45:19

The problem is that in the product detail page (template), I do not know how to get the category name to this product, because this product may belong to several categories. I want to use the category of this product to make a breadcrumb.

在开始实现细节之前,您需要解决如何确定应该使用哪个类别的问题。我脑子里能想到两个选择:

  1. 跟踪会话中的类别。你知道吗
  2. 在产品的url中包含类别。你知道吗

2是更好的选择,因为它不依赖于某个状态来确定渲染的内容。如果您在会话中跟踪类别,则会话中的用户可以清除其cookie、刷新页面并获得完全不同的视图。这通常是件坏事。你知道吗

您必须根据业务逻辑确定如何最佳地设计URL。通常是:category/<category_id>/<product_slug>,因为查看一个类别应该返回多个产品。但是,应用程序将指定如何执行此操作。你知道吗

这样做的一个后果是,当查看“某个类别内”的产品时,您将无法在产品上使用get_absolute_url。确定url中应使用哪个类别的信息在请求中,并且在视图中可用,但在产品实例中不可用。你知道吗

相关问题 更多 >

    热门问题