MASIGNASUKAv102
6510051498749449419

Automatically update foreign key in django rest framework using serializer

Automatically update foreign key in django rest framework using serializer
Add Comments
Monday, May 3, 2021

#Django100days

This code helps you to update the foreign key automatically after saving the serializer in views.

 



class CreateGroup(APIView):
    """
    Provides a post method handler.

    """

    def post(self, request , *args, **kwargs):
        serializer = GroupSerializer(data=request.data)

        if serializer.is_valid():
            newGroup = serializer.save() #Saving the serializer
            update_s = CustomUser.objects.get(email = request.user) # getting th current logged in user
            update_s.group = newGroup // assigning newly created group to user
            print(newGroup)
            update_s.save()
            
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors,status=400)   
Adarshreddy Adelli

As an Engineering Lead with deep expertise in Artificial Intelligence, Cybersecurity, and Systems Architecture, I guide teams in building innovative, secure, and scalable solutions.I am passionate about tackling challenging technical problems, fostering engineering excellence, and delivering solutions that balance innovation, security, and performance. I actively share knowledge through blogging and community engagement, contributing to the advancement of AI and cybersecurity practices.