我如何在django上排序产品?[已关闭]

qnyhuwrf  于 2023-02-25  发布在  Go
关注(0)|答案(1)|浏览(142)

6天前关闭。
Improve this question
你能演示一下如何对网上商店中的商品进行排序吗?这样你就可以点击按钮,排序就发生了变化,例如:price,-price.而且到www.example.com是在课堂上,而不是在def上。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,
            }
        )

form.py

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

tf7tbtn21#

你可以试试这样的方法:

def get(self, request)
    allowed_orderings = ('price', '-price', ...)  # define orderings you want
    ordering = request.GET.get('ordering', '-price')  # get ordering from url params
    ordering = ordering if ordering in allowed_orderings else '-price'  # check ordering is allowed, if not - set the default
    your_model = Model.objects.filter(...).order_by(ordering)  # filter queryset with your params and then order by defined ordering
    ... #  and then return your models as you want to

对于这段代码,你需要在你的url参数中提供ordering(比如/shop/goods/?ordering=-price

相关问题