Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

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

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. question from:https://stackoverflow.com/questions/65898074/django-object-rawquery-doesnot-return-updated-queryset

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...