Django rest framework filter with or condition

坚强是说给别人听的谎言 提交于 2020-05-15 04:42:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!