首页 > 解决方案 > ManyToMany relationship between Category and Product in Ecommerce

问题描述

I am developing a eCommerce using Django and relationship between Product and Category Models is Many-to-many. That is, one product can belong to several category.

In the product list page there is a sidebar showing the category list as well as the product list under each category. We use get_absolute_url method of Product to link to the url of each product detail page.

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.

Product model

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})

Product list template (prod.model is the model number of product)

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

urls.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'),
]

标签: pythondjango

解决方案


问题是在商品详情页面(模板)中,不知道如何获取该商品的分类名称,因为该商品可能属于多个分类。我想使用这个产品的类别来制作面包屑。

在开始实施细节之前,您需要解决如何确定应该使用哪个类别的问题。我可以想到两个选项:

  1. 跟踪会话中的类别。
  2. 在产品的 URL 中包含类别。

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

您必须确定如何根据您的业务逻辑最好地设计您的网址。通常是:category/<category_id>/<product_slug>查看一个类别应该返回多个产品。但是,您的应用程序将决定如何执行此操作。

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


推荐阅读