DRF - is it possible to combine several filter parameters in the URL with some logical symbol OR

I created a REST endpoint using the Django REST Framework.

class PersonFilter(django_filters.FilterSet):
    id = django_filters.NumberFilter(name="id", lookup_type="gt")
    first_name = django_filters.CharFilter(name="first_name", lookup_type="icontains")
    last_name = django_filters.CharFilter(name="last_name", lookup_type="icontains")

class Meta:
    model = Person
    fields = ('id', 'first_name', 'last_name', 'last_mod')

class PersonModelViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Person.objects.none()
    filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    pagination_class = StandardResultsSetPagination
    ordering_fields = ('id', 'first_name', 'last_name', 'last_mod')
    ordering = ('last_mod', 'id')
    filter_class = PersonFilter

Now, if I make a request as follows:

/api/rest/v1/Person?first_name=foo&last_name=foo&page_size=10

This returns only those objects where both first name and last name contain "foo". I want to return those objects where the first name contains "foo" OR the last name contains "foo".

I wonder if there is a character that can be used in the URL parameters, which will mean the logic or the relationship between the filters.

One solution can be to issue two separate AJAX requests for the endpoint, but this requires additional work to unify the result.

+4
1

, django_filter. , Q, . FilterSet.qs() self._qs.query.where OR. . .

: Django SQL-, - :

qs.filter(map(operators.or_, [Q(k=v) for k, v in request.GET.items()]))

, , , .

+3

Source: https://habr.com/ru/post/1623022/


All Articles