问题
I am using Django Rest Framework Filter to access my data. I need to get data that answers one of two conditions. Example:
Mywebsite/api/animal/?name=lion||name=frog
The ||
is not working. Does anyone know how I can do this filter?
回答1:
I realize this maybe a little old but i solved it like this:
from django.db.models import Q
class FooViewSet(viewsets.ModelViewSet):
queryset = Foo.objects.all()
status = self.request.query_params.get('status', None)
def get_queryset(self):
if status is not None:
status = status.split('|')
query = Q()
for x in status:
q = Q(status=x)
query |= q
queryset = queryset.filter(query)
return queryset
My url then looks like this:
example.com/api/foo/?status=test1|test2|test3
and filters like this
Foo.objects.filter(Q(status=test1)|Q(status=test2)|Q(status=test3))
来源:https://stackoverflow.com/questions/37540275/django-rest-framework-filter-with-or-condition