Search code examples
djangodjango-rest-frameworkdjango-viewsdjango-rest-viewsets

Calling a DRF View from another View


I have a User Model Viewset that adds users to my Django Rest Framework application (VueJS -> DRF -> PostGres).

I have another ModelViewSet for an activity log that has entries when users get credit for doing training, etc.

I ran into an issue where I realized that a user that has done nothing, skews the metrics. To combat this, I just want to insert an Activity into the ActivityLog upon user creation.

How can I call a ModelViewSet to post a new activity from the the new user post?

I read several questions that seemed similar but I am not understanding well enough to translate to my issue. I just want to take the ID created from the new user creation and pass that with some data to the ActivityLogViewset.

If I override perform_create() in the UserViewset, how would I call and pass the data to the other endpoint?

EDIT: OK, so I think I got tunnel vision (again). Made it harder than it had to be. I just overrode the perform_create, imported the ActivityLog model, and created an instance of it the way I needed. Seems much easier than created a new request & calling the endpoint.

Thanks.

BCBB


Solution

  • OK, so I think I got tunnel vision (again). Made it harder than it had to be. I just overrode the perform_create, imported the ActivityLog model, and created an instance of it the way I needed. Seems much easier than created a new request & calling the endpoint.

    class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all().order_by('last_name')
        serializer_class = UserSerializer
    
        def perform_create(self, serializer):
            super().perform_create(serializer)
            user = serializer.instance
            act_cat = ActivityCategory(pk=1)
            act_desc = "You joined!"
            act = ActivityLog(user=user, activity_category=act_cat, activity_description=act_desc)
            act.save()