DRF:预期为整数,但收到字符串(使用Axios)

qyswt5oh  于 2022-11-05  发布在  iOS
关注(0)|答案(1)|浏览(115)

当我尝试发送一个id数组到django rest框架时,收到以下错误:
我的有效负载如下所示:
分配的设施(_L):1,2
当我使用drf API测试页时,它工作正常,有效负载如下所示:分配的设施(_L):[第一、二条]
所以我的假设是,如果我没有括号,这就是它不工作的原因,我该怎么解决这个问题?

const cpBoard = useSelector((state) => state.cpBoard);
    const facilityIds = (cpBoard.cpBoardItems?.map(cpBoardItem => (cpBoardItem.id)));

    function submitFacilities() {

        const facilitydata = new FormData()
        facilitydata.append("assigned_facilities", facilityIds);

        axios.patch(API.leads.update(id), facilitydata, {
            headers: {
                "Authorization": `Bearer ${accessToken}`,
                'Content-Type' : 'application/x-www-form-urlencoded',
                'Accept' : 'application/json',
            },
            withCredentials: true,
        })
            .then(res => {
                setLead(res.data)
            })
            .finally(() => {
                setLoading(false)
            })
    }

views.py

class LeadUpdateView(UpdateAPIView):
    permission_classes = [IsAuthenticated, IsLeadOwner]
    serializer_class = LeadUpdateSerializer

    def get_queryset(self):
        return Lead.objects.all()

serializers.py

class LeadUpdateSerializer(serializers.ModelSerializer):
    is_owner = serializers.SerializerMethodField()
    class Meta:
        model = Lead
        fields = (
            "id",
            "first_name",
            "last_name",
            "PrimaryAddress",
            "assigned_facilities",

        )
        read_only_fields = ("id", "created_at", "agent", "is_owner")

    def get_is_owner(self, obj):
        user = self.context["request"].user
        return obj.agent == user
ryevplcw

ryevplcw1#

我想通了:

axios.patch(API.leads.update(id), { "assigned_facilities": facilityIds}, {

            headers: {
                "Authorization": `Bearer ${accessToken}`,
                'Accept' : 'application/json',
            },
            withCredentials: true,
        })
            .then(res => {
                setLead(res.data)
            })
            .finally(() => {
                setSending(false)
            })
    }

将其作为FormData发送,仅作为键为assigned_facilities且值为facilityIds的Object发送

相关问题