A
A
Abdulla Mursalov2015-12-25 10:21:58
Django
Abdulla Mursalov, 2015-12-25 10:21:58

Is it possible to write an abstract filtering function on HStoreField?

Hello! The stack I'm working with:
Django 1.9and Django REST frameworkfor creating an API.
django-hstoreto work with HStoreField, in which I store product attributes.
django-filterused to filter products. I did not want to work with HStoreField out of the box. I found in the documentation django_filters.MethodFilter, which allows you to create a custom queryset. However, there were several problems with this. First, attributes are dynamic, so write view filters:

class ProductFilter(django_filters.FilterSet):
    scu = django_filters.MethodFilter(action='filter_scu')

    def filter_scu(self, queryset, value):
        queryset = Product.objects.filter(attributes__contains={'scu':value})
        return queryset

    class Meta:
        model = Product
        fields = ['scu', ]

possible indefinitely. Secondly, several of these functions work like OR, but should be like AND. Tell me how to write a similar function that accepts a dictionary of the form
attributes={"scu": "214412", "manufacturer": "hp", ...}
and collecting queryset:
Product.objects.filter(attributes__contains={key:value).filter(...)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2015-12-25
@amaprograma

from functools import reduce

class Product(Model):
    attributes = HStoreField()

    @classmethod
    def filter(cls, data):
        return reduce(
            lambda qs, x: qs.filter(attributes__contains={x[0]: x[1]}), 
            data.items(), cls.objects.all()
        )

So what?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question