E
E
Evgeny Abaev2020-08-04 11:40:36
Django
Evgeny Abaev, 2020-08-04 11:40:36

How to sort by price in django?

There is a product model:

class Product(models.Model):
    """Товар"""
    name = models.CharField("Название", max_length=100)
    description = models.TextField("Описание")
    preview = models.ImageField("Изображение", upload_to="product_preview", null=True)
    room = models.ManyToManyField(Room, verbose_name="Комната")
    category = models.ForeignKey(Category, verbose_name="Категория", on_delete=models.CASCADE, null=True)
    manufacturer = models.ForeignKey(Manufacturer, verbose_name="Производитель", on_delete=models.CASCADE, null=True)
    width = models.IntegerField("Ширина", default=0)
    depth = models.IntegerField("Глубина", default=0)
    height = models.IntegerField("Высота", default=0)
    price = models.PositiveIntegerField("Цена", default=0, help_text="Укажите цену")
    hit = models.BooleanField(default=False)
    available = models.BooleanField(default=True)
    url = models.SlugField(max_length=160, unique=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("product_detail", kwargs={"slug": self.url})

    def preview_url(self):
        if self.preview and hasattr(self.preview, 'url'):
            return self.preview.url

    class Meta:
        verbose_name = "Товар"
        verbose_name_plural = "Товары"


There is such sorting in view.py. It sorts by manufacturers and categories:
class FilterProductBy(ModelForFilter, ListView):
    template_name = "shop/product/product_list.html"
    def get_queryset(self):
        queryset = Product.objects.filter(
            Q(manufacturer__name__in=self.request.GET.getlist("manufacturer")) |
            Q(category__name__in=self.request.GET.getlist("category"))
        )
        return queryset


Tell me how to sort by price (from .. to ..) having this form on the page:

<li><a href="#" onclick="openMenu('sub_menu_3');return(true)"><p>Цена</p></a>
        <ul id="sub_menu_3">
              от <input id='id66i1' class='range_inpt1' type='number' min='20' max='700'>
              -  до <input id='id66i2' class='range_inpt2' type='number' min='20' max='700'>
        </ul>
 </li>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2020-08-04
@tumbler

Read the doc on the django-filter library, things will become easier.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question