MattBroach / DjangoRestMultipleModels

View (and mixin) for serializing multiple models or querysets in Django Rest Framework
MIT License
549 stars 67 forks source link

Any quick Django Rest SearchFilter implementation? #4

Closed chogarcia closed 8 years ago

chogarcia commented 8 years ago

I was wondering if you know a quick way to implement Django Rest SearchFilter?

MattBroach commented 8 years ago

So it depends on what you mean by that. All querysets in the MultipleModelAPIView (and the corresponding mixing) are put through the filter_backends, so if you add a filter_backends tuple to your view (or add a default filter backend to the whole site) it should work, although I haven't tested this myself.

If you need different filtering per queryset, it's a little bit trickier. You might want to overwrite the get_querylist() function in that case. Also, I just merged a PR that allows for writing functions for dynamic filtering -- of course, this wouldn't be using Django Rest's built-in SearchFilter, but it might be another way to go. I haven't put that version on pip yet (I need to write tests for it), but you can git clone master from this repo if you want to give that a whirl.

baneizalfe commented 8 years ago

I tried just adding

filter_backends = (filters.SearchFilter,) search_fields = ('name',)

but then I get error Cannot filter a query once a slice has been taken.

Can i access request's data in get_querylist(), so I can access search query param and filter queryset with it?

baneizalfe commented 8 years ago

Just managed to pull it off by overriding get_queryList def get_queryList(self): search = self.request.query_params.get('query', None)

MattBroach commented 8 years ago

Hmm, interesting that the DRF built in SearchFilter doesn't seem to be working right now. I'll dig into it, but thanks for letting me know -- and glad you got a workaround.

anujism commented 8 years ago

Can you please provide an example of filter_fn?

MattBroach commented 8 years ago

@anujism, there's now an example of using filter_fn in the documentation: https://django-rest-multiple-models.readthedocs.io/en/latest/filtering.html#custom-filter-functions. I had change the implementation to make it work perfectly, so make sure you update django-rest-multiple-models to version 1.7 or higher.