You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue调用DRF API提交多选分类时ID传递及格式错误问题

解决Vue多选Select向DRF传递分类ID的问题

问题根源

DRF返回的错误说明序列化器期望接收字典或主键数组,但你传递的是单个字符串/整数:

  • 初始传递分类名称字符串:不符合DRF外键/多对多字段的接收格式
  • 修改为传递单个ID:因为是multiple多选组件,选中的是多个值,应该传递ID数组,而非单个整数

解决方案步骤

1. 修正Vue Select组件的value绑定

让<option>的value绑定分类的id,这样v-model会自动收集选中的ID数组:

<select id="interest_category" name="interest_category" v-model="interest_category" multiple class="block w-full max-w-lg rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:max-w-xs sm:text-sm">
   <!-- 绑定category.id到value,添加key确保渲染稳定 -->
   <option v-for="category in ProjectsAPI" :key="category.id" :value="category.id">
     {{ category.interest_name }}
   </option>
</select>

2. 初始化Vue数据为数组

因为multiple多选组件的v-model需要绑定数组类型,在Vue的data里初始化:

data() {
  return {
    // ...其他表单字段
    interest_category: [], // 初始化为空数组
    ProjectsAPI: []
  }
}

3. 配置DRF序列化器接收主键数组

确保项目序列化器中interest_category字段使用PrimaryKeyRelatedField并开启many=True,表示接收多个主键:

from rest_framework import serializers
from .models import Project, InterestCategory

class ProjectSerializer(serializers.ModelSerializer):
    # 配置为接收多个分类ID
    interest_category = serializers.PrimaryKeyRelatedField(
        queryset=InterestCategory.objects.all(),
        many=True
    )

    class Meta:
        model = Project
        fields = ['project_title', 'project_description', 'interest_category', 'created_by']

4. 验证提交数据格式

此时提交的formData中,interest_category会是一个ID数组(比如[1,3,5]),符合DRF的接收要求,不会再返回格式错误。


内容的提问来源于stack exchange,提问作者ckcAdmin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 13:40:54