如何在Django中按类别明智地过滤产品?

时间:2020-07-23 04:17:42

标签: python django django-views django-templates django-filter

我正在尝试根据类别进行过滤,但它会在每个类别页面上显示所有产品,但是我想根据类别页面进行过滤,请检查我的代码并告诉我该怎么做。

这是我的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进行过滤时然后所有产品显示在每个类别页面上。请合并两个代码,并为此提供正确的解决方案。

2 个答案:

答案 0 :(得分:0)

您可以尝试一下。

def SubCategorySlugListAPIView(request, subcat_slug):
    
    # First get the category object.
    subcategory = get_object_or_404(SubCategory, subcat_slug=subcat_slug)
    
    # then filter the products on this category

    productlist =Product.objects.filter(subcategory=subcategory)

编辑:没有必要在此处编写额外的filter方法。 您需要做的基本事情是,首先需要获取单个类别的对象,然后从“产品”模型中过滤该类别的产品。

def SubCategorySlugListAPIView(request, subcat_slug):
    subcategory = get_object_or_404(SubCategory, subcat_slug=subcat_slug)
    productlist = Product.objects.filter(subcategory=subcategory)
    paginator = Paginator(productlist, 12)
    page_number = request.GET.get('page')
    product = paginator.get_page(page_number)

    brands=Brand.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')            
       
    template_name = 'mainpage/cat-products.html'
    context = {'product': product,
           'subcategories': subcategories, 'subcategory': subcategory, 'category': category, 'featured':featured, 'high':high, 'brands':brands, 'supplement':supplement}
    return render(request, template_name, context)

您还可以通过其他方式过滤相关产品

subcategory = get_object_or_404(SubCategory, subcat_slug=subcat_slug)
productlist = subcategory.prosubcat.all()

答案 1 :(得分:0)

例如:

models.py

from django.db import models

class Category(model.Model):
    slug = models.SlugField(unique=True, max_length=50)

class Item(model.Model):
    category = models.ManyToManyField(Category,related_name='ITEM')

views.py

from django.shortcuts import render, get_object_or_404
from .models import Category

def category_filter(request, slug):
    category = get_object_or_404(Category, slug=slug)
    data = category.ITEM.all()
    render(request, TEMPLATE_NAME, context={'data':data})

在 urls.py 中

from django.urls import path
from .views import category_filter

urlpatterns = [
    path('category/<slug:slug>/', category_filter, name='Category'),
]

现在如果 url 是类似的东西

<块引用>

本地主机/类别/froots/

将显示所有属于 froot 类别的项目。