python - 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'),
]
解决方案
问题是在商品详情页面(模板)中,不知道如何获取该商品的分类名称,因为该商品可能属于多个分类。我想使用这个产品的类别来制作面包屑。
在开始实施细节之前,您需要解决如何确定应该使用哪个类别的问题。我可以想到两个选项:
- 跟踪会话中的类别。
- 在产品的 URL 中包含类别。
2 是更好的选择,因为它不依赖于某些状态来确定正在呈现的内容。如果您在会话中跟踪类别,则会话中的用户可以清除他们的 cookie、刷新页面并获得完全不同的视图。这通常是一件坏事。
您必须确定如何根据您的业务逻辑最好地设计您的网址。通常是:category/<category_id>/<product_slug>
查看一个类别应该返回多个产品。但是,您的应用程序将决定如何执行此操作。
get_absolute_url
这样做的一个后果是,在“类别内”查看产品时,您将无法在产品上使用。确定应该在 url 中使用哪个类别的信息在请求中,并且将在视图中可用,但在产品实例上不可用。
推荐阅读
- ruby - Test::Unit::TestCase 中 `#cleanup` 和 `#teardown` 的区别
- r - 转换数据框的列和行
- javascript - Vue动态排序onclick通过复选框选择
- json - 如何将 groupby 数据绑定到 amcharts 地图
- azure - Azure DevOps 如何跳过 PR 构建运行的 PublishBuildArtifacts 步骤
- angular - 使用 SwPush 服务在 Angular 中获取当前推送管理器订阅
- swift - Xcode 12 和 iOS 14 中的手势问题
- asp.net - 为 SSIS SourceConnectionOLEDB 指定 windows 帐户
- android - 深度链接在测试时工作但不在生产中,Android Cordova Webview
- c# - 构造函数的依赖注入