mmrz
mmrz

Reputation: 3

how to reverse query for django_filters fields

models.py

class Product(models.Model):
    .
    .
    pass


class Color(models.Model):
    color_name = models.CharField(blank=True, max_length=50)
    color = ColorField(default='#FF0000')


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

filters.py

class ProductFilter(django_filters.FilterSet):
    class Meta:
           model = Product
           fields = ['color',]

i want to filter product by color using django_filters how should i do??

Upvotes: 0

Views: 869

Answers (2)

Vitor Freitas
Vitor Freitas

Reputation: 3610

You can add a new filter to your filters.py file, but instead refer to the ProductColor model.

filters.py

class ProductFilter(django_filters.FilterSet):
    productcolor__color__color = django_filters.CharFilter(lookup_expr='iexact')
    productcolor__color__color_name = django_filters.CharFilter(lookup_expr='iexact')

    class Meta:
        model = Product

Note that I'm using productcolor__color__color to refer to the color property in the Color model. The double underscore access a ForeignKey property.

The lookup_expr='iexact' will match both lowercase and uppercase color code (#fff* or #FFF).

Then a simple HTML to filter your queryset could be:

<form method="get">
    {{ filter.form.as_p }}
    <button type="submit">Search</button>
</form>
<ul>
    {% for product in filter.qs %}
        <li>{{ product.name }}</li>
    {% endfor %}
</ul>

The {{ product.name }} is just an example, I don't know if your Product model have a name field. But you can access your product following the {{ product.<field_name> }}.

You can read more about django_filters here: https://simpleisbetterthancomplex.com/tutorial/2016/11/28/how-to-filter-querysets-dynamically.html

Upvotes: 1

Abe
Abe

Reputation: 1415

Inside your view, you can make a query like this

c = Color('my desired color', '#ffffff')
result = ProductColor.objects.filter(color=c.color)
for r in result:
   # do something ...

Upvotes: 0

Related Questions