如何在Django在线商店中对产品进行排序

huangapple go评论67阅读模式
英文:

How to sort the products in the Django online store

问题

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>
英文:

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(&#39;sort&#39;)
        products = Product.objects.filter(available=True)
        if sort_form.is_valid():
            needed_sort = sort_form.cleaned_data.get(&quot;sort_form&quot;)
            if needed_sort == &quot;ДТ&quot;:
                products = products.order_by(
                    &quot;created&quot;)  # или updated  в зависимости от того, что ты вкладываешь в понятие по дате
            elif needed_sort == &quot;ДЕД&quot;:
                products = products.order_by(&quot;price&quot;)
            elif needed_sort == &quot;ДОД&quot;:
                products = products.order_by(&quot;-price&quot;)
        return render(
            request=request,
            template_name=&#39;main/index.html&#39;,
            context={
                &#39;products&#39;:products,
            }
        )

forms.py

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

index.py

&lt;form action=&quot;{% url &#39;product_list&#39; %}&quot; method=&quot;get&quot; class=&quot;sort-form&quot;&gt;
  {{ sort_form }}
  &lt;p&gt;&lt;input type=&quot;submit&quot; name=&quot;sort&quot; value=&quot;Сортировать&quot;&gt;&lt;/p&gt;
  {% csrf_token %}
&lt;/form&gt;

答案1

得分: 0

以下是翻译好的代码部分:

# 一个示例,你可以如何处理它:

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):

        # 初始化类并设置产品数据
        _product = SortProduct(products=products.objects.filter(somefilter=request.GET('somefilter')))

        # 设置一个过滤器集
        filterset = {'sort_by_price':_product.sort_by_price,
                     'sort_by_popularity':_product.sort_by_popularity,
                     'filter_brand':_product.filter_brand, 
                     }
        # 使用过滤器集进行过滤
        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'))

        # 以JSON格式返回过滤后的产品
        return JsonResponse(list(_product.values()), safe=False)

urlpatterns  = [
        path('/product', SectionView.as_views(), name='sectionviews'),
    ]
英文:

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(&#39;-price&#39;)
            else:
                self.products = self.products.order_by(&#39;price&#39;)
    
        def sort_by_popularity(self, descending=False):
            if descending:
                self.products = self.products.order_by(&#39;-popularity&#39;)
            else:
                self.products = self.products.order_by(&#39;popularity&#39;)
        
        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(&#39;somefilter&#39;)))
    
            #Setting up a filterset
            filterset = {&#39;sort_by_price&#39;:_product.sort_by_price,
                         &#39;sort_by_popularity&#39;:_product.sort_by_popularity,
                         &#39;filter_brand&#39;:_product.filter_brand, 
                         }
            #Filtering using a filterset
            if request.GET(&#39;sort_by_price&#39;):
                filterset[request.GET(&#39;sort_by_price&#39;)](request.GET(&#39;descending&#39;))
            if request.GET(&#39;sort_by_popularity&#39;):
                filterset[request.GET(&#39;sort_by_popularity&#39;)](request.GET(&#39;descending&#39;))
            if request.GET(&#39;filter_brand&#39;):
                filterset[request.GET(&#39;filter_brand&#39;)](request.GET(&#39;brand&#39;))
    
            #Returning filtered products as JSON
            return JsonResponse(list(_product.values()), safe=False)
    
    
    urlpatterns  = [
            path(&#39;/product&#39;, SectionView.as_views(), name=&#39;sectionviews&#39;),
        ]

huangapple
  • 本文由 发表于 2023年2月19日 17:57:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499283.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定