Answer the question
In order to leave comments, you need to log in
Is it possible to write an abstract filtering function on HStoreField?
Hello! The stack I'm working with: Django 1.9
and Django REST framework
for creating an API. django-hstore
to work with HStoreField
, in which I store product attributes. django-filter
used 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', ]
OR
, but should be like AND
. Tell me how to write a similar function that accepts a dictionary of the formattributes={"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
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()
)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question