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
4.5k 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 Reply

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")

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

...