M
M
maxell2019-09-09 23:02:39
Django
maxell, 2019-09-09 23:02:39

How to do filtering in django?

I tried today to figure out how django_filters works, but it didn't work out.
I am making an online store and so far I have filtered only by product category, the code is below.
I ran into a problem that I don’t understand how to implement additional filters (sort by price, by date, etc.)
Can someone throw options?

#Models.py
class Item(models.Model):

    colors =(
        ('black', 'Черный'),
        ('white', 'Белый'),
        ('bordo', 'Бордовый'),
        ('bej', 'Бежевый'),
        ('green', 'Зеленый')
    )

    item_title = models.CharField('Название', max_length=200)
    item_description = models.TextField('Описание')
    item_size = models.CharField('Размер', max_length=10)
    item_price = models.IntegerField('Цена')
    item_pub_date = models.DateTimeField('Дата публицкации', auto_now=True)
    item_image_1 = models.ImageField('Первая картинка', upload_to="images", null=True)
    item_image_2 = models.ImageField('Вторая картинка', upload_to="images", null=True)
    item_color = MultiSelectField('Цвета', max_length= 100, choices=colors, null=True)
    item_type = models.ForeignKey('ItemType', on_delete = models.CASCADE, null=True)

    
    class Meta:
        verbose_name= 'Товар'
        verbose_name_plural = 'Товар'

    def __str__(self):
        return '{}'.format(self.item_title)
    
class ItemType(models.Model):
    title = models.CharField('Название товара', max_length=200)

    class Meta:
        verbose_name= 'Тип товара'
        verbose_name_plural = 'Тип товара'

    def __str__(self):
        return '{}'.format(self.title)

# views.py
def index(request):
    item = Item.objects.all()
    context ={
        'items':item
    }
    return render(request,'add_item/item.html', context)

def item_type_detail(request, category_name):
    filtred_items= Item.objects.filter(item_type__title= category_name)
    return render (request, 'add_item/item1.html',context={'filtred_items':filtred_items })

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Guest007, 2019-09-10
@Guest007

-- removed paragraph --
If we are talking about django_filters, then you first need to define this filter (as it is written in the documentation for the package ).
Well, further on in the text.
One of the short options is right on the github page
. Better write what you have already tried and what did not work.
And take advice: remove this refrain from the field names. item_This duplication will always bother you. And so you know that you are requesting information from the Item model. Why else mark each field like that? Leave title, descriptionetc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question