2

I have a model Color:

class Color(models.Model):
    color = models.CharField(max_length=32)

    def __str__(self):
        return self.color

And my Product model:

class Product(models.Model):
    ...
    color = models.ForeignKey('Color', on_delete=CASCADE)
    ...

So i need to create a filter that i'll able to get for example all red, blue or yellow products

How can i do that?

Ihor
  • 97
  • 10

2 Answers2

2

To create a filter with multiple choices for a model you can use the ModelMultipleChoiceFilter [django-filter docs]. You can also pass the form widget you want to get used for the field, hence for checkboxes you would pass CheckboxSelectMultiple [Django docs]:

from django import forms
import django_filters


class ProductFilter(django_filters.FilterSet):
    color = django_filters.ModelMultipleChoiceFilter(queryset=Color.objects.all(), widget=forms.CheckboxSelectMultiple())
    
    class Meta:
        model = Product
        fields = ['color']  # Add any other fields you want to filter to the list
Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33
1

You can .filter(…) [Django-doc] with:

Product.objects.filter(color__name=some_color_name)

with some_color_name for example 'Yellow'. If you have a color object, you can work with:

Product.objects.filter(color=some_color)

One can use double underscores (__) to look "through" relations.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • But what if i have a django-filter form?And i need not only one color. I need several For example i have 20 colors in my database and user wants to get the product with his favorite colors – Ihor Jul 16 '21 at 17:36
  • @ihor: you can then filter with `Product.objects.filter(color__name__in=['Red', 'Blue'])` – Willem Van Onsem Jul 16 '21 at 17:37
  • @ihor: as for django-filter, you can speciy an `__in` lookup as well: https://stackoverflow.com/a/59988897/67579 – Willem Van Onsem Jul 16 '21 at 17:38
  • i mean how to add a field with this filter if django-filter needs built-in django-filter filters? – Ihor Jul 16 '21 at 17:39
  • @ihor: you add `in` to the `filter_fields = {'color__name': ['in']}`, and thus pass it in the query with `?color__name__in=red,blue`. – Willem Van Onsem Jul 16 '21 at 17:41
  • moreover idk what color user will choose thus i need to create many checkboxes for each of color – Ihor Jul 16 '21 at 17:42
  • 2
    @ihor: you can do that by specifying the widget to a `CheckboxSelectMultiple`, – Willem Van Onsem Jul 16 '21 at 17:44
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/234983/discussion-between-ihor-and-willem-van-onsem). – Ihor Jul 16 '21 at 17:59