请帮我排序的产品在django在线商店

hfyxw5xn  于 2023-02-20  发布在  Go
关注(0)|答案(1)|浏览(127)

如何对网店中的商品进行排序,这样点击按钮,排序就发生了变化,例如:price,-price.而且到views.py是在课堂上,而不是在def上。
views.py

class SectionView(View):
    def get(self, request, *args, **kwargs):
        sort_form = request.GET.getlist('sort')
        products = Product.objects.filter(available=True)
        if sort_form.is_valid():
            needed_sort = sort_form.cleaned_data.get("sort_form")
            if needed_sort == "ДТ":
                products = products.order_by(
                    "created")  # или updated  в зависимости от того, что ты вкладываешь в понятие по дате
            elif needed_sort == "ДЕД":
                products = products.order_by("price")
            elif needed_sort == "ДОД":
                products = products.order_by("-price")
        return render(
            request=request,
            template_name='main/index.html',
            context={
                'products':products,
            }
        )

forms.py

class SortForm(forms.Form):
    sort_form = forms.TypedChoiceField(label='Сортировать:', choices=[('ПУ', 'По умолчанию'), ('ДТ', 'По дате'), ('ДЕД', 'От дешевых к дорогим'), ('ДОД', 'От дорогих к дешевым')])

index.py

<form action="{% url 'product_list' %}" method="get" class="sort-form">
  {{ sort_form }}
  <p><input type="submit" name="sort" value="Сортировать"></p>
  {% csrf_token %}
</form>
juzqafwq

juzqafwq1#

以下是您可以如何处理它的示例:

class SortProduct:
    
        def __init__(self, products):
            products = products
    
        def sort_by_price(self, descending=False):
    
            if descending:
                self.products = self.products.order_by('-price')
            else:
                self.products = self.products.order_by('price')
    
        def sort_by_popularity(self, descending=False):
            if descending:
                self.products = self.products.order_by('-popularity')
            else:
                self.products = self.products.order_by('popularity')
        
        def filter_brand(self, brandname):
            self.products = self.products.filter(brand=brandname)
    
    class SectionView(View):
    
        def get(self, request):
    
            # Intializing class and setting products data
            _product = SortProduct(products=products.objects.filter(somefilter=request.GET('somefilter')))
    
            #Setting up a filterset
            filterset = {'sort_by_price':_product.sort_by_price,
                         'sort_by_popularity':_product.sort_by_popularity,
                         'filter_brand':_product.filter_brand, 
                         }
            #Filtering using a filterset
            if request.GET('sort_by_price'):
                filterset[request.GET('sort_by_price')](request.GET('descending'))
            if request.GET('sort_by_popularity'):
                filterset[request.GET('sort_by_popularity')](request.GET('descending'))
            if request.GET('filter_brand'):
                filterset[request.GET('filter_brand')](request.GET('brand'))
    
            #Returning filtered products as JSON
            return JsonResponse(list(_product.values()), safe=False)
    
    
    urlpatterns  = [
            path('/product', SectionView.as_views(), name='sectionviews'),
        ]

相关问题