Django API:更新字典列表

xt0899hw  于 2023-02-14  发布在  Go
关注(0)|答案(1)|浏览(152)

我尝试通过我的djangorest框架API传递一个字典列表,循环通过它们,更新模型中的关联记录,最终将序列化的数据返回到前端。
我在提交词典列表时收到以下错误:

HTTP 400 Bad Request
Allow: PUT, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "non_field_errors": [
            "Expected a list of items but got type \"dict\"."
        ]
    },
    {
        "non_field_errors": [
            "Expected a list of items but got type \"dict\"."
        ]
    }
]

下面是我通过django rest框架API模板传递的JSON:

[
    {
        "id": "1",
        "order": "5"
    },
    {
        "id": "2",
        "order": "3"
    }
]

以下是我的模型的视图:

class Waitlist(models.Model):

    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50, blank=True)
    identification = models.CharField(max_length=50)

    email = models.EmailField(max_length=100, validators=[], blank=True)
    mobile_phone = PhoneNumberField(blank=True)

    store_number = models.PositiveSmallIntegerField()
    order = models.PositiveSmallIntegerField()
    status = models.PositiveSmallIntegerField()

    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.first_name + ' ' + self.last_name

这是我的www.example.com的一个精简视图views.py:

from django.shortcuts import render, get_object_or_404

from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import status

from .models import Waitlist

from .serializers import WaitlistOrderSerializer, WaitlistOrderListSerializer

@api_view(['PUT'])
def waitlistOrder(request):
    waitlist_data = request.data
    waitlist = []
    for data in waitlist_data:
        waitlist_id = data.get('id')
        w = Waitlist.objects.get(id=waitlist_id)
        waitlist.append(w)
    serializer = WaitlistOrderListSerializer(
        waitlist, data=waitlist_data, many=True)
    if serializer.is_valid():
        serializer.save()
        return Response({'success': 'Waitlist order updated successfully'})
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

这是我的www.example.com的简化视图serializers.py

class WaitlistOrderSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    order = serializers.IntegerField()

    def update(self, instance, validated_data):
        instance.order = validated_data.get('order', instance.order)
        instance.save()
        return instance

class WaitlistOrderListSerializer(serializers.ListSerializer):
    child = WaitlistOrderSerializer()

    def update(self, instances, validated_data):
        for instance, data in zip(instances, validated_data):
            self.child.update(instance, data)
        return instances

谢谢你的建议。

r7s23pms

r7s23pms1#

错误位于此行:

serializer = WaitlistOrderListSerializer(
        waitlist, data=waitlist_data, many=True)

它应该是:

serializer = WaitlistOrderListSerializer(waitlist)

但是不需要创建ListSerializer,当你传递many=True时,这个ListSerializer会自动创建,WaitlistOrderSerializer会作为一个子元素传递,和你现在做的类似。
所以你可以:

serializer = WaitlistOrderSerializer(waitlist, many=True)

并完全删除列表序列化程序。

相关问题