Django object.raw('query') doesnot return updated queryset

Viewed 610
class view_name(viewsets.ModelViewSet):
    queryset = model_name.objects.raw('call stored_procedure();')
    serializer_class = model_name_Serializers
    permission_classes = [IsAuthenticated]

So, when I execute the above the rest framework view set. It works fine. But when I update any value which will effect the queryset of the stored procedure.

It still return the previous queryset not the updated one. I have then checked by running the call procedure sql statement in my database(mysql) where it returns the updated queryset.

But this raw function continues to show the queryset with the previous values. It only returns the updated queryset after restarting the localhost server.

1 Answers

I think the reason of this behavior is that raw execute query during class construction. Here's what documentation saying:

takes a raw SQL query, executes it, and returns a django.db.models.query.RawQuerySet instance

In other words - your query run one's when you start the project, not each time you call the view. Instead of queryset class attribute you can define a get_queryset method and put your raw query there, so that it will be called (and query will be executed) each time you call the view with request:

def get_queryset(self):
    return model_name.objects.raw('call stored_procedure();')
Related