Reputation: 498
I have described the product model as follows: models.py
class Product(models.Model):
category = TreeManyToManyField(ProductCategory, blank=True, symmetrical=False, related_name='products',
verbose_name='Категория->Подкатегория')
name = models.CharField(max_length=200, db_index=True, verbose_name='Наименование товара')
price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Цена')
In views.py:
def product_list(request, category_slug=None):
category = None
categories = ProductCategory.objects.filter(available=True, is_active=True)
object_list = Product.objects.filter(available=True, is_active=True)
if category_slug:
category = get_object_or_404(ProductCategory, slug=category_slug)
object_list = object_list.filter(category=category)
paginator = Paginator(object_list, 16)
page = request.GET.get('page')
try:
products = paginator.page(page)
except PageNotAnInteger:
products = paginator.page(1)
except EmptyPage:
products = paginator.page(paginator.num_pages)
return render(request, 'shop/products/list_by_category/product_list.html', {'category': category,
'categories': categories,
'products': products,
})
The problem is that I want to sort the products by the lowest price or the highest price (that is, displaying goods in min_price order of price and max_price price). In the template I have a sort form:
<div class="secand_fillter">
<h4>sort by price:</h4>
<select class="selectpicker">
<option>descending price</option>
<option>ascending price</option>
</select>
</div>
As far as I understand correctly, it is necessary to send the parameter by which the goods will be sorted using the GET method, and in the view, by overriding the get_queryset method (receiving the sorting parameter), return the list of products back.
Upvotes: 0
Views: 439
Reputation: 1431
Ascending
object_list = Product.objects.filter(available=True, is_active=True).order_by('price')
Descending
object_list = Product.objects.filter(available=True, is_active=True).order_by('-price')
Upvotes: 1