django rest framework: : Passing raw query

2019-03-22 06:30发布

问题:

Is it possible to perform raw queries in django rest framework like django. https://docs.djangoproject.com/en/dev/topics/db/sql/#performing-raw-queries

回答1:

Yes you should be able to, since you can customize the queryset that backs your view, e.g.

class MyModelViewSet(viewsets.ModelViewSet):
    # The usual stuff here
    model = MyModel

    def list(self, request):
        queryset = MyModel.objects.raw('... your SQL here...')
        serializer = MyModelSerializer(queryset, many=True)
        return Response(serializer.data)

Manager.raw() returns RawQuerySet which is a QuerySet, so you can see how it all fits