它应该运行3次,但仅对第一个元素运行。我试图在python控制台上运行它,并且相同的方法效果很好。我无法弄清楚代码的问题。
@api_view(['POST'])
def SaveVisitView(request):
if request.method == 'POST':
visits = json.loads(request.POST.get('request'))
for i in range(len(visits['visits'])):
serializer = VisVisitsSerializer(data=visits['visits'][i])
if serializer.is_valid():
serializer.save()
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return Response(serializer.data, status=status.HTTP_201_CREATED)
class VisVisits(models.Model):
visit_id = models.IntegerField(primary_key=True,auto_created=True)
app_local_id = models.IntegerField(blank=True, null=True)
school_program = models.ForeignKey(SchProgramForSchools, models.DO_NOTHING, blank=True, null=True)
user = models.ForeignKey(UsrUsers, models.DO_NOTHING, blank=False, null=False)
class Meta:
managed = False
db_table = 'vis_visits'
def __str__(self):
return str(self.visit_id)
{
"user": "1",
"visits": [
{
"action": "i",
"local_id": "170",
"visit_id": "",
"school_program_id": "1",
},
{
"action": "i",
"local_id": "172",
"visit_id": "",
"school_program_id": "1",
},
{
"action": "i",
"local_id": "172",
"visit_id": "",
"school_program_id": "1",
},
]
}
答案 0 :(得分:3)
如何在序列化程序中使用many=True
属性?
它可以处理多个对象。
也看this。
@api_view(['POST'])
def SaveVisitView(request):
if request.method == 'POST':
visits = json.loads(request.POST.get('request'))
serializer = VisVisitsSerializer(data=visits['visits'], many=True)
if serializer.is_valid():
serializer.save()
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return Response(serializer.data, status=status.HTTP_201_CREATED)