django - 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__'
解决方案
请您分享您的请求内容和您的模型。
在您的 Json 请求中,我认为您正在尝试发送 Month Object 但序列化程序正在等待 dict 。
也许您的 json 请求应该是:
"月":[ {你的月份对象} ]
推荐阅读
- javascript - 导入一个 js 库并在 vue-cli 组件中全局使用它(vue 2)
- google-cloud-platform - 云代码:部署到云运行不起作用
- javascript - 用对象实例方法链依次解析promise
- java - java.lang.ClassNotFoundException: org.apache.jsp.index_jsp 部署 Spring Boot 应用程序时出错
- android - 在 Android Studio 中添加投影(带有参数颜色、x、y 和模糊)
- javascript - 在 jquery 上收到错误消息“未捕获的 TypeError:无法读取属性 'ownerDocument' of null”
- android-jetpack-compose - Jetpack 在 LazyColumn 和 LazyRow 上编写滚动条
- makefile - 如何在 Clion 中启用 Makefile 插件
- flutter - 为什么这个 DateTime 函数会使我的应用程序崩溃?
- sas - Layout Lattice 中创建的列与条形图的排序顺序不匹配