Krystian Kazimierczak
Krystian Kazimierczak

Reputation: 592

Django Filter query set

I want to add a button which will sort products by name, price etc.

This is my view:

def product_list(request, category_slug=None):
    category = None
    categories = Category.objects.filter(man=True)
    products = Product.objects.filter(section='man', available=True)
    flt = Product.objects.filter(section='man', available=True).order_by('-name')
    products = products.filter(category=category)
    return render(request,
                  'shop/product/list.html',
                  {'category': category,
                   'categories': categories,
                   'products': products,
                   'flt': flt})

How can I sort by name, price etc on click of the button?

Upvotes: 0

Views: 643

Answers (1)

Ahmed Elemam
Ahmed Elemam

Reputation: 416

First thing u need to know Sort is different than Filter

this the solution in case u add button in html from his action will be redirect to your view named product_list

<button type="submit" name="sortByName"></button>

In your view

After this line products = products.filter(category=category)

Add this

if 'sortByName' in request.GET:
    products=products.order_by('-name')

and u can reach your goal Hope this help u Also keep in touch if u have any inquiry Thanks

Upvotes: 1

Related Questions