【问题标题】:Django REST Framework. Keep getting KeyError in all the methodsDjango REST 框架。在所有方法中不断收到 KeyError
【发布时间】:2020-06-05 23:05:12
【问题描述】:

在测试我的 Django REST Api 一段时间后,我在使用 request.data 时开始出现 KeyError。这个问题在此之前没有发生,它只是随机开始发生的。我使用 Python 3.8 和 Django REST 3.11

这是我的序列化程序和视图。如有任何帮助,我将不胜感激。

序列化器.py

class InterestSerializer(serializers.ModelSerializer):
    class Meta:
        model = Interest
        fields = '__all__'

class UserIntrestSerializer(serializers.ModelSerializer):
    interest = InterestSerializer()

    class Meta:
        model = UserInterest
        fields = ('id','interest')

views.py

class UserInterestView(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserIntrestSerializer

    def get_user_interests(self, request):
        try:
            user = get_object_or_404(User, pk=request.data['id'])
            interests = UserInterest.objects.all().filter(user__id = user.id)
            serializer = UserIntrestSerializer(interests, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
        except MultiValueDictKeyError:
            return Response("No data given", status=status.HTTP_204_NO_CONTENT)

    def create_user_interests(self, request):
        try:
            user = User.objects.get(pk=request.data['id'])
            interest_list = [Interest.objects.all().filter(name=interest)[0] for interest in request.data['interests']]
            print(interest_list)
            for interest in interest_list:
                UserInterest(user=user, interest=interest).save()
            return Response("User interests created properly")
        except IndexError:
            return Response("Interest not found", status=status.HTTP_404_NOT_FOUND)
        except User.DoesNotExist:
            return Response("User not found")

    def delete_interest(self, request):
        try:
            userinterest = UserInterest.objects.get(interest__name=request.data["interest_name"], user__id=request.data["user_id"])
            userinterest.delete()
            return Response("User's interest deleted properly", status=status.HTTP_200_OK)
        except UserInterest.DoesNotExist:
            return Response("User or User's interest not found", status=status.HTTP_404_NOT_FOUND)

    def update_interest(self, request):
        try:
            user = User.objects.get(pk=request.data['id'])
            current_interests = [user_interest.interest for user_interest in UserInterest.objects.all().filter(user__id=user.id)]
            new_interests = [Interest.objects.get(name=interest) for interest in request.data['new_interests']]

            for current_interest in current_interests:
                if current_interest not in new_interests:
                    UserInterest.objects.get(user=user, interest=current_interest).delete()
            for new_interest in new_interests:
                if new_interest not in current_interests:
                    UserInterest(interest=new_interest, user=user).save()
            return Response("Interests updated properly", status=status.HTTP_200_OK)
        except ObjectDoesNotExist:
            return Response("User or User's interests haven't been found", status=status.HTTP_404_NOT_FOUND)
        except KeyError:
            return Response("ID or new_interests haven't been provided", status=status.HTTP_400_BAD_REQUEST)

我正在使用 Postman 来处理我的请求。

【问题讨论】:

  • 你能分享完整的回溯吗?

标签: python django django-rest-framework


【解决方案1】:

GET 请求没有正文 (data),这就是 request.data 不起作用的原因。您可以在网址中发送id 并使用request.GET['id']

例如:https://yourdomain.com/?id=2

【讨论】:

  • 如果我想使用请求的正文发送数据怎么办?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-30
  • 2021-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多