我的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关系实际上并没有保存到数据库中。响应成功,但未遵循配置文件。
我在这里错过了什么,以正确地保存追随者关系?
1条答案
按热度按时间tzcvj98z1#