我正在构建的虚假电子商务网站上的产品上方有一个导航栏。我通过 ListView 呈现此 View 。在此导航栏中,我有一个工作正常的搜索区域,并且希望添加根据按下的内容过滤结果的功能。例如,我在导航栏中有风格:现实主义、肖像等。当我单击现实主义时,我希望结果更改为数据库中的所有现实主义绘画。
我的问题是实现这一目标的最佳方法是什么?我可以更改原始 ListView 吗?或者我只需要根据我需要的特定查询创建一个全新的 View ?非常感谢任何帮助!
还附有一张图片,以向您展示我的意思,以防我的解释不是最好的。
查看:
class AllProductView(ListView):
template_name = 'my_site/all_products.html'
model = Product
ordering=['id']
paginate_by = 9
context_object_name = 'products'
要求的产品型号:
class Product(models.Model):
name = models.CharField(max_length=120)
shortened_name = models.CharField(max_length=50)
date_of_creation = models.CharField(max_length=20, null=True)
history = models.CharField(max_length=255)
price = models.DecimalField(max_digits=9, decimal_places=2)
discount_price = models.FloatField(blank=True, null=True)
style = models.CharField(max_length=50)
artist = models.ForeignKey(Artist, on_delete=models.SET_NULL, null=True)
image = models.ImageField(upload_to='images', null=True)
slug = models.SlugField()
最佳答案
您可以通过覆盖 .get_queryset(…)
method [Django-doc] 进行过滤:
class AllProductView(ListView):
template_name = 'my_site/all_products.html'
model = Product
ordering=['id']
paginate_by = 9
context_object_name = 'products'
def get_queryset(self, *args, **kwargs):
qs = super().get_queryset(*args, **kwargs)
fltr = self.kwargs['style']
if fltr != 'all':
qs = qs.<strong>filter(style=self.kwargs['style'])</strong>
return qs
在你的 urls.py 中,你可以使用 <str:…>
路径转换器来确定我们要过滤的样式,因此:
path('products/<strong><str:style></strong>/', AllProductView.as_view(), name='products')
在模板中,我们可以编写 URL:
<a href="<strong>{% url 'products' style='realism' %}</strong>">Realism</a>
这将链接到仅显示 Product
的页面与style='realism'
.
关于Django - 根据按下的链接更改 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68577728/