Please help me sort the products in the django online store

Question:

How to sort the goods in the online store so that you can click on the button and the sorting has changed, for example: price,-price. And to views.py was in class, not in 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>
Asked By: Lightcart

||

Answers:

A sample of how you could approach it:

   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'),
        ]
Answered By: user21243872
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.