gpt4 book ai didi

python - 如何反序列化 django rest 框架中的多个对象列表?

转载 作者:行者123 更新时间:2023-11-28 18:14:49 25 4
gpt4 key购买 nike

我正在开发一个 rest API,它获取由多个对象组成的请求并将它们保存到数据库中。然后,返回另一个对象数组作为响应。所有对象都只有一个模型。

class Ratings(models.Model):
id = models.AutoField(primary_key = True)
userId = models.IntegerField()
movieId = models.IntegerField()
rating = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)])
timestamp = models.DateTimeField(auto_now = True)

class RatingsSerializer(serializers.ModelSerializer):
class Meta:
model = Ratings
fields = ('userId','movieId','rating')

class RecommendationGenerator(generics.ListCreateAPIView):
queryset = Ratings.objects.all()
serializer_class= RatingsSerializer
def post(self, request, format='json'):
serializer= RatingsSerializer(data = request.data, many = True)
if serializer.is_valid():
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_403_FORBIDDEN)

当我在 Postman 中使用 JSON 测试它时:

[
{
"userId": 13,
"movieId": 1765,
"rating": 5
},
{
"userId": 13,
"movieId": 1733,
"rating": 3
},
{
"userId": 13,
"movieId": 1713,
"rating": 2
},
{
"userId": 13,
"movieId": 963,
"rating": 2
}
]

结果是[]。但是对于

{
"userId": 13,
"movieId": 1765,
"rating": 5
}

结果是

{
"userId": 13,
"movieId": 1765,
"rating": 5
}

如何反序列化这些数据?我在这里做错了什么?

最佳答案

观点应该是这样的

class RecommendationGenerator(generics.ListCreateAPIView):
queryset = Ratings.objects.all()
serializer_class= RatingsSerializer

def post(self, request, format='json'):
serializer= RatingsSerializer(data = request.data, many = True)
if serializer.is_valid():
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_403_FORBIDDEN)

试试这个

关于python - 如何反序列化 django rest 框架中的多个对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49005247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com