【发布时间】:2020-11-12 17:47:46
【问题描述】:
我正在尝试根据类别进行过滤,但它在每个类别页面上显示所有产品,但我想根据类别页面进行过滤,请检查我的代码并告诉我该怎么做。
这是我的models.py 文件...
class SubCategory(models.Model):
subcat_name=models.CharField(max_length=225)
subcat_slug=models.SlugField(max_length=225, unique=True)
category = models.ForeignKey('Category', related_name='subcategoryies', on_delete=models.CASCADE, blank=True, null=True)
and here is my product models.py file...
class Product(models.Model):
name=models.CharField(max_length=225)
slug=models.SlugField(max_length=225, unique=True)
subcategory=models.ForeignKey('SubCategory', related_name='prosubcat', on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return self.name
class ProductFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains')
class Meta:
model = Product
fields = ['saleprice', 'title','veg_non','brand','supplement']
def SubCategorySlugListAPIView(request, subcat_slug):
category = Category.objects.all()
subcategories = SubCategory.objects.all()
product = Product.objects.all()
brands=Brand.objects.all()
f = ProductFilter(request.GET, queryset=Product.objects.all())
supplement=Supplement.objects.all()
featured=Product.objects.filter(featured=True).order_by('-created_at')[0:6]
high = Product.objects.all().order_by('-saleprice')
if subcat_slug:
subcategory = get_object_or_404(SubCategory, subcat_slug=subcat_slug)
productlist = product.filter(subcategory=subcategory)
paginator = Paginator(productlist, 12)
page_number = request.GET.get('page')
product = paginator.get_page(page_number)
template_name = 'mainpage/cat-products.html'
context = {'product': product,
'subcategories': subcategories, 'subcategory': subcategory, 'category': category, 'featured':featured, 'high':high, 'brands':brands, 'supplement':supplement, 'filter':f}
return render(request, template_name, context)
我知道需要合并这些代码 f = ProductFilter(request.GET, queryset=Product.objects.all()) 和这个productlist = product.filter(subcategory=subcategory),使用productlist 我根据类别获取产品但是当我使用filter 进行过滤时,所有产品都会显示在每个类别页面上.请合并这两个代码并给我一个正确的解决方案。
【问题讨论】:
标签: python django django-views django-templates django-filter