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?
You can .filter(…)
[Django-doc] with:
Product.objects.filter()
with some_color_name
for example 'Yellow'. If you have a color object, you can work with:
Product.objects.filter()
One can use double underscores ( __
) to look "through" relations.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.