我正在尝试创建在线商店。按类别分类,产品按类别正确过滤。现在,我尝试按品牌和其他属性来筛选类别中的产品。但这不起作用。
#Models
class Product(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
category = TreeForeignKey('Category', related_name='products', on_delete=models.CASCADE)
vendor = models.ForeignKey('Vendor', related_name='vendors', on_delete=models.CASCADE, blank=True, null=True)
class Vendor(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True)
#urls
urlpatterns = [
path('catalog/<slug:slug>/', views.category_catalog, name='category_catalog')
]
#views
def category_catalog(request, slug=None):
category = get_object_or_404(Category, slug=slug)
breadcrumbs = Category.get_ancestors(category, include_self=True)
# cat = Product.objects.filter(category__in=Category.objects.get(id=category.id).get_descendants())
if category.get_level() <= 1:
cat = category.get_descendants().order_by('tree_id', 'id', 'name')
return render(request, 'shop/category_catalog.html', {'category': category,
'cat': cat,
'menu': menu(request),
'breadcrumbs': breadcrumbs})
if category.get_level() >= 2:
list_pro = Product.objects.filter(category__in=Category.objects.get(id=category.id)\
.get_descendants(include_self=True)) \
.annotate(min_price=Min('prices__price'))
vendors_ids = list_pro.values_list('vendor_id', flat=True).order_by().distinct()
vendors = Vendor.objects.filter(id__in=vendors_ids)
filter = BrandFilter(queryset=Vendor.objects.all())
print(filter)
print(vendors)
products_list = helpers.pg_records(request, list_pro, 12)
category = get_object_or_404(Category, slug=slug)
cat = category.get_descendants(include_self=True).order_by('tree_id', 'id', 'name')
last_node = category.get_siblings(include_self=True)
return render(request, 'shop/category_product_list.html', {'products_list': products_list,
'category': category,
'vendors': vendors,
'cat': cat,
'last_node': last_node,
'menu': menu(request),
'breadcrumbs': breadcrumbs,
'filter': filter,
})
我如何实现这个想法?
答案 0 :(得分:0)
我已经通过Forms找到了解决方案!它有效,但我仍在尝试。我的解决办法!
#Forms
class BrandForms(forms.Form):
brand = forms.ModelMultipleChoiceField(queryset=Vendor.objects.none())
filter_brand = BrandForms(request.GET)
if filter_brand.is_valid():
if filter_brand.cleaned_data['brand']:
print(filter_brand.cleaned_data['brand'])
list_pro = Product.objects.filter(category__in=Category.objects.get(id=category.id)\
.get_descendants(include_self=True)) \
.annotate(min_price=Min('prices__price'))\
.filter(vendor_id__in=filter_brand.cleaned_data['brand'])