2
# views.py
import schedule_update.send_the_result

class UpdatedTypeViewSet(viewsets.ModelViewSet):
    queryset = Updated_Type.objects.all()
    serializer_class = UpdatedTypeSerializer
    # Is it correct to code here, if I would like to call function when post request succeed, and how?
# send_to_redmine.py
def Send_The_Result():
    # get the data from request and send it to redmine.

if __name__ == '__main__':
    Send_The_Result()

Here's my source code and there're 2 questions that I stuck in Modelviewset.

  1. Is it possible to call Send_The_Result when post request succeed in Modelviewset?
  2. When the post request sent, how do I bring the data into Send_The_Result?

Please let me know, if any further information is needed, thank you.

1 Answers1

3

Django Rest Framework being an abstraction over Django, implements Web methods through actions which is little different from the basic HTTP protocols. For example: POST is implemented through create method.

Equivalent ModelViewSet method:

def create(self, *args, **kwargs):
  return super().create(*args, **kwargs)

The create method in ModelViewSet calls the serializer, evaluates request, and if valid, stores in database through Model and returns the response.

So, this gives you three levels of space, where you want to execute your some_function_on_successful_task_completion.

  • You could override in view's create method,
  • You can override in Serializer's create method.
  • You can override in Model's save method.

For example, in your Model:

def save(self, *args, **kwargs):
  # normal stuff, save to db.
  # easier here, as you have every information you need to perform operations
  return obj
  • Thanks for sharing, I have overridden the create function in Modelviewset and inserted the function into it successfully. – victor chang Jun 08 '21 at 06:51