Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django rest framework: : Passing raw query

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

like image 277
somechow Avatar asked Sep 24 '14 11:09

somechow


People also ask

Should you use raw SQL in Django?

I would balance that by cautioning against overuse of the raw() and extra() methods.” Django project co-leader Jacob Kaplan-Moss says (paraphrased): “If it's easier to write a query using SQL than Django, then do it. extra() is nasty and should be avoided; raw() is great and should be used where appropriate.”

What is raw queries in Django?

What is raw queries in Django? The raw() manager method can be used to perform raw SQL queries that return model instances: Manager. raw (raw_query, params=(), translations=None) This method takes a raw SQL query, executes it, and returns a django.

How do I filter Queryset in Django REST framework?

The simplest way to filter the queryset of any view that subclasses GenericAPIView is to override the . get_queryset() method. Overriding this method allows you to customize the queryset returned by the view in a number of different ways.


1 Answers

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

like image 104
bakkal Avatar answered Nov 09 '22 14:11

bakkal