many to many - Django Rest Framework ManyToMany filter multiple values -


i have 2 models, 1 defining users, other defining labels on these users. using django rest framework create api. able query users @ least labels ids 1 , 2.

for instance users' labels are: [(1,2), (1,2,3), (2,3), (1,3)] want query return [(1,2), (1,2,3)].

so far, i've managed query users given label (let's id=1) doing: /api/users/?labels=1, unable query users labels 1 , 2. i've tried /api/users/?labels=1,2 or /api/users/?labels=1&labels=2 return invalid users, i.e. users without labels 1 or 2...

any welcome.

thanks,
dimitry

github test repo:

https://github.com/thedimlebowski/drf-m2m-filter

code:

models.py

class label(models.model):     name = models.charfield(max_length = 60)  class user(models.model):     labels = models.manytomanyfield(label) 

filters.py

class userfilter(django_filters.filterset):     labels = django_filters.filters.baseinfilter(         name='labels',         lookup_type='in',     )      class meta:         model = user         fields = ('labels',) 

serializers.py

class labelserializer(serializers.modelserializer):     class meta:         model = label         fields = ('id','name')  class userserializer(serializers.modelserializer):     labels = labelserializer(many = true)     class meta:         model = user         fields = ('labels',) 

views.py

class userviewset(viewsets.modelviewset):     queryset = user.objects.all()     serializer_class = userserializer     filter_backends = (filters.djangofilterbackend,)     filter_class = userfilter     filter_fields = ('labels',) 

you can use chain filters solving problem.
example, if need users labels contains both of 1 , 2 values, can write query so:

user.objects.filter(labels=1).filter(labels=2) 

django-filters not support queries default need custom filter.

class m2mfilter(django_filters.filter):      def filter(self, qs, value):         if not value:             return qs          values = value.split(',')         v in values:             qs = qs.filter(labels=v)         return qs   class userfilter(django_filters.filterset):     labels = m2mfilter(name='labels')      class meta:         model = user         fields = ('labels',) 

now can write labels id's comma separated , need

/api/users/?labels=1,2 

here answer m2m queries


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -