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?
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