Django 2 在我的模板页面中结合了 ListView 和 DetailView
Django 2 combine ListView and DetailView in my template page
我有两个型号 "product" 和 "brand"
产品具有品牌字段 ManyToMany 到 link 具有相关品牌的产品
## models.py
class Product(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(blank=True, unique=True)
description = models.TextField()
brand = models.ManyToManyField(Brand)
class Brand(models.Model):
title = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
## url.py
re_path(r'^brands/(?P<slug>[\w-]+)/$', BrandDetail.as_view(), name = 'branddetail'),
## views.py
class BrandDetail(DetailView):
queryset = Brand.objects.all()
template_name = "brands/brand.html"
## brands/brand.html
{{ object.title }} <br/>
{{ object.description }} <br/>
现在在渲染时 brand.html 可以很好地显示品牌名称和描述
我的问题是
如果我想在同一页面中呈现 产品列表 link 特定品牌 "considering the brand slug already passed in the URL",我该怎么做?
class 是 DetailsView,它在查询集中只有品牌详细信息,如图所示!!
我需要任何解决方案 ne
您不需要 ListView
,您可以遍历品牌的 product_set
,例如:
{{ object.title }} <br/>
{{ object.description }} <br/>
products:
{% for product in <b>object.product_set.all</b> %}
{{ product.title }} <br/>
{% endfor %}
我有两个型号 "product" 和 "brand" 产品具有品牌字段 ManyToMany 到 link 具有相关品牌的产品
## models.py
class Product(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(blank=True, unique=True)
description = models.TextField()
brand = models.ManyToManyField(Brand)
class Brand(models.Model):
title = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
## url.py
re_path(r'^brands/(?P<slug>[\w-]+)/$', BrandDetail.as_view(), name = 'branddetail'),
## views.py
class BrandDetail(DetailView):
queryset = Brand.objects.all()
template_name = "brands/brand.html"
## brands/brand.html
{{ object.title }} <br/>
{{ object.description }} <br/>
现在在渲染时 brand.html 可以很好地显示品牌名称和描述
我的问题是 如果我想在同一页面中呈现 产品列表 link 特定品牌 "considering the brand slug already passed in the URL",我该怎么做?
class 是 DetailsView,它在查询集中只有品牌详细信息,如图所示!! 我需要任何解决方案 ne
您不需要 ListView
,您可以遍历品牌的 product_set
,例如:
{{ object.title }} <br/>
{{ object.description }} <br/>
products:
{% for product in <b>object.product_set.all</b> %}
{{ product.title }} <br/>
{% endfor %}