我在Django REST框架中有以下视图来跟踪配置文件:

2izufjch  于 2023-07-01  发布在  Go
关注(0)|答案(1)|浏览(93)

我的views.py:

class FollowView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, pk):
        user_profile = get_object_or_404(Profile, pk=pk)
        user = request.user
        if user_profile.user == user:
            return Response({"error": "You cannot follow your own profile."}, status=status.HTTP_400_BAD_REQUEST)
        try:
            follower = get_object_or_404(Profile, user=user) 
            user_profile.follower.add(follower)
            user_profile.save()  
        except Exception as e:
            print(e)
            return Response({"error": "An error occurred while trying to follow this profile."}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        return Response({"success": "You are now following this profile."}, status=status.HTTP_200_OK)

我的models.py:

user= models.OneToOneField(User, on_delete= models.CASCADE)
follower= models.ManyToManyField('self', related_name= 'followed_by', blank= True, symmetrical= False)

但是,当我向这个视图发出POST请求时,follower关系实际上并没有保存到数据库中。响应成功,但未遵循配置文件。
我在这里错过了什么,以正确地保存追随者关系?

tzcvj98z

tzcvj98z1#

  • 经过与chatgpt的长时间交谈,终于意识到我需要序列化post数据,所以这里的解决方案:
  • 观点
class FollowProfileView(generics.GenericAPIView):
     serializer_class = ProfileSerializer
     permission_classes= (IsAuthenticated,)

     def post(self, request, pk):
         user_profile = request.user.profile
         to_follow_profile = get_object_or_404(Profile, pk=pk)

         if user_profile == to_follow_profile:
             return Response({"error": "You cannot follow your own profile."}, status=status.HTTP_400_BAD_REQUEST)

         user_profile.follower.add(to_follow_profile)
         return Response({"success": "You are now following this profile."}, status=status.HTTP_201_CREATED)
  • 串行器:
class ProfileSerializer(serializers.ModelSerializer):
     follower = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
     class Meta:
         model = Profile
         fields = ('id', 'user', 'follower')

相关问题