Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

How to save a foreign key field in the Django Rest Framework

I have a issuetracker project where a manager can assign a user to a project. The manager selects a project and a user from dropdowns, clicks submit, and an api call is called in the frontend to send that post data to my django APIView assignuser. Assignuser then takes both those values and filters for the correct project and the user, and saves that user to the project user. After checking the projects, I am unable to save a new User to a project as User comes up as null. Is there a specified way in saving foreign keys in the DRF?

assignuser

class assignuser(APIView):
    serializer_class = ProjectSerializer

    def post(self, request, format=None):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            user_name = serializer.get('user')
            project_name = serializer.get('project_name')
            user = Users.objects.get(user=user_name)
            project = Project.objects.get(name=project_name)
            project.user = user
            project.save()
            return Response(ProjectSerializer(project).data, status=status.HTTP_201_CREATED)
        else:
            return HttpResponse("Incorrect Credentials")

Project Serializer

class ProjectSerializer(serializers.ModelSerializer):
user = SignUpSerializer()
class Meta: 
    model = Project
    fields = ('name', 'description', 'user')

SignUp Serializer

class SignUpSerializer(serializers.ModelSerializer):
class Meta: 
    model = Users
    fields = ('username', 'password', 'email', 'role')

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

1 Answer

0 votes
by (71.8m points)

you can do this

class assignuser(APIView):
    serializer_class = ProjectSerializer

    def post(self, request, format=None):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            user_name = serializer.get('user')
            project_name = serializer.get('project_name')
            user = Users.objects.get(user=user_name)
            project = Project.objects.get(name=project_name)
            project.user = user
            project.user.save()
            return Response(ProjectSerializer(project).data, status=status.HTTP_201_CREATED)
        else:
            return HttpResponse("Incorrect Credentials")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...