Я пытаюсь сохранить 3 таблицы одновременно, и данные сохраняются в таблице. Но у меня возникают проблемы, связанные с вставкой visit_id, vdata_id, vchild_id из каждой из этих таблиц.(это первичный ключ с настройками auto_created = True) для возврата значения в API.Я перепробовал много способов добиться этого.одна попытка была такой VisVisits.objects.latest('visit_id')
, но она выдает ошибку, похожую на <visit_id 46> is not serializer
, разделяющую мой код:
serializer
class VisVisitsSerializer(serializers.ModelSerializer):
data = VisVisitDataSerializer(many=True)
data_child = VisVisitChildSerializer(many=True)
class Meta:
model = VisVisits
read_only_fields = ['visit_id']
def create(self, validated_data):
visits_data = validated_data.pop('data')
visits_child_data = validated_data.pop('data_child')
visit = VisVisits.objects.create(**validated_data)
#print()
for visit_data in visits_data:
VisVisitData.objects.create(visit=VisVisits.objects.last(), **visit_data)
for visit__child_data in visits_child_data:
VisVisitChild.objects.create(visit=VisVisits.objects.latest('visit_id'), **visit__child_data)
return visit
views
@api_view(['POST'])
def SaveVisitView(request):
if request.method == 'POST':
visits = json.loads(request.POST.get('request'))
visits['visits'][0].update({'user': visits['user']})
visit = [] #need to return last inserted visit_id
visit_data = [] #need to return last inserted vdata_id
visit_child = [] #need to return last inserted vchild_id
for i in range(len(visits['visits'])):
for z in range(len(visits['visits'][i]['data'])-1):
visits['visits'][i]['data'][z]['parameter_id'] = visits['visits'][i]['data'][z]['VisitParamID']
if visits['visits'][i]['data'][z]['parameter_id'] == '5' or visits['visits'][i]['data'][z]['parameter_id'] == '28':
visits['visits'][i].update({'data_child': [visits['visits'][i]['data'][z]]})
del visits['visits'][i]['data'][z]
serializer = VisVisitsSerializer(data=visits['visits'][i])
if serializer.is_valid():
if visits['visits'][i]['action'] == "i":
serializer.save()
#print(serializer[i]['visit_id'])
# visit_save.save()
visit_data.append({'visit_ids':serializer[i]['visit_id']})
del visits['visits'][i]['data_child']
elif visits['visits'][i]['action'] == "u" :
VisVisits.objects.filter(visit_id=visits['visits'][i]['visit_id']).update(is_valid=visits['visits'][i]['active'])
visit_data_update.append({'visit_id':serializer.data.visit_id })
del visits['visits'][i]['data_child']
else:
visit_issues.append({'local_id':visits['visits'][i]['local_id'],
'validation_issues': serializer.errors,
'status':status.HTTP_400_BAD_REQUEST})
return Response({'visit_issues':visit_issues,
'visit_data': visit_data,
'status': status.HTTP_201_CREATED} )