Search with 2 field in generic api view
Do you know how can I search with 2 fields with 'and' conditions?
I mean in the below code I need to search'search_fields' with symbol name and time_frame,(both conditions together not only one of them)
class RegisterSymbolViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = SymbolValidationSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['^symbol','^time_frame']
queryset = RegisterSymbol.objects.all()
First of all DRF docs say that only text-based fields can be used as search field so if timeframe is DateField it will most likely not work.
The SearchFilter class will only be applied if the view has a
search_fields attribute set. The search_fields attribute should
be a list of names of text type fields on the model,
such as CharField or TextField.
You can try creating custom SearchFilter class and override filter_querysetmethod to use and instead of or operator.
See DRF source code https://github.com/encode/django-rest-framework/blob/86673a337a4fe8861c090b4532379b97e3921fef/rest_framework/filters.py#L123