首页 > 解决方案 > DRF,在视图中更新对象后返回序列化数据

问题描述

我有以下视图以及可以发布或修补数据的自定义创建方法:

class MonthsViewSet(ModelViewSet):
    authentication_classes = (TokenAuthentication,)

    def get_queryset(self):
        # TODO: Workaround until Auth is setup on the front.
        query_set = Month.objects.all() if isinstance(self.request.user, AnonymousUser) \
            else Month.objects.filter(farm__user=self.request.user)
        return query_set

    serializer_class = MonthSerializer

    def create(self, request, *args, **kwargs):
        request_month = request.data['month']
        year = request.data['year']
        farm = request.data['farm']
        days = request.data['days']
        # TODO: understand why built-in update_or_create didn't work here.
        farm_obj = Farm.objects.get(id=farm)
        try:
            month = Month.objects.get(year=year, month=request_month, farm=farm_obj)
            month.days = days
            month.save()
            serializer = MonthSerializer(data=month, many=False, partial=True)
            serializer.is_valid(raise_exception=True)
            return Response(data=serializer.data, status=status.HTTP_200_OK)
        except Month.DoesNotExist:
            Month.objects.create(year=year, month=request_month, farm=farm_obj, days=days)
            return Response(status=status.HTTP_201_CREATED)`

现在我的问题是更新后发回对象的数据,更新成功但我无法在保存该对象后序列化该对象,并在收到更新一个月的请求时将其发送回响应中,它得到更新但响应是这个错误:

400
Error: Bad Request
[
  {
    "non_field_errors": [
      "Invalid data. Expected a dictionary, but got Month."
    ]
  }
]

我的序列化器:

class MonthSerializer(serializers.ModelSerializer):
    class Meta:
        model = Month
        fields = '__all__'

标签: djangoserializationdjango-rest-framework

解决方案


请您分享您的请求内容和您的模型。

在您的 Json 请求中,我认为您正在尝试发送 Month Object 但序列化程序正在等待 dict 。

也许您的 json 请求应该是:

"月":[ {你的月份对象} ]


推荐阅读