Reputation: 117
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?
Upvotes: 3
Views: 4492
Reputation: 21787
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
Upvotes: 3
Reputation: 476557
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.
Upvotes: 1