我有一个模特:
class Scenario(models.Model):
tasks = models.ManyToManyField(Task, blank=True)
它的序列化器:
class ScenarioSerializer(serializers.ModelSerializer):
class Meta:
model = Scenario
fields = '__all__'
以及创建方案的视图:
@api_view(['GET', 'POST'])
def scenarios_list(request):
"""
List all scenarios, or create a new.
"""
if request.method == 'GET':
scenarios = Scenario.objects.all()
serializer = ScenarioSerializer(scenarios, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = ScenarioSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(
serializer.errors, status=status.HTTP_400_BAD_REQUEST)
我从我的前端发送以下数据:
[
{id: 3, title: "Three", how_often: "DS", how_important_task: "EI", role: "Lorem", …},
{id: 1, title: "One", how_often: "MO", how_important_task: "RI", role: "Lorem", …},
{id: 6, title: "Six", how_often: "WO", how_important_task: "EI", role: "", …},
{id: 4, title: "Four", how_often: "", how_important_task: "", role: "", …}
]
这引发了我BAD REQUEST错误。我做错了什么?
答案 0 :(得分:0)
将您的请求有效负载更改为dict
类似对象,如下所示(问题为list
),然后发送
{title: "Three", how_often: "DS", how_important_task: "EI", role: "Lorem", …}
我从请求有效负载中删除了id
密钥,因为根据您的序列化程序和模型,您不必在创建新对象时指定id
,