Django Rest Framework - 保存表单集?
Django Rest Framework - save a formset?
有没有办法优雅地保存表单集?我尝试将所有数据推送到序列化程序中,但它的 validated_data 是空的,因此没有创建任何内容:
这是原样的表单集数据:
每个对象都是这个序列化器:
class RAGReportAtomSerializer(serializers.ModelSerializer):
marker = RAGMarkerSerializer()
item = RAGItemsSerializer()
class Meta:
model = RAGReportAtom
fields = (
'id',
'item',
'marker',
'comments'
)
class RAGMarkerSerializer(serializers.ModelSerializer):
class Meta:
model = DicRAGMarker
fields = (
'name',
'color_code',
'icon'
)
class RAGItemsSerializer(serializers.ModelSerializer):
class Meta:
model = DicRAGItem
fields = (
'name',
'description',
)
我正在尝试这样保存它:
def create(self, request, project_id):
serialized_data = RAGReportAtomSerializer(data=request.DATA, many=True)
if serialized_data.is_valid():
serialized_data.save()
msg = MessageSerializer(Message(title='OK', body="Milestone successfully created!"))
return Response(msg.data, status=HTTP_201_CREATED)
else:
return Response(serialized_data.errors, status=HTTP_400_BAD_REQUEST)
我做了一个小东西来完成这项工作,但它并没有解决这个问题。以防万一这可以帮助某人。
data = {}
for item in request.DATA:
match = re.match("^form-(\d)-(.+)", item)
if match:
match_form = match.group(1)
match_key = match.group(2)
if not data.get(match_form, None):
data[match_form] = {}
data[match_form][match_key] = request.DATA[item]
for item in data:
serialized_data = RAGReportAtomBaseSerializer(data=data[item])
有没有办法优雅地保存表单集?我尝试将所有数据推送到序列化程序中,但它的 validated_data 是空的,因此没有创建任何内容:
这是原样的表单集数据:
每个对象都是这个序列化器:
class RAGReportAtomSerializer(serializers.ModelSerializer):
marker = RAGMarkerSerializer()
item = RAGItemsSerializer()
class Meta:
model = RAGReportAtom
fields = (
'id',
'item',
'marker',
'comments'
)
class RAGMarkerSerializer(serializers.ModelSerializer):
class Meta:
model = DicRAGMarker
fields = (
'name',
'color_code',
'icon'
)
class RAGItemsSerializer(serializers.ModelSerializer):
class Meta:
model = DicRAGItem
fields = (
'name',
'description',
)
我正在尝试这样保存它:
def create(self, request, project_id):
serialized_data = RAGReportAtomSerializer(data=request.DATA, many=True)
if serialized_data.is_valid():
serialized_data.save()
msg = MessageSerializer(Message(title='OK', body="Milestone successfully created!"))
return Response(msg.data, status=HTTP_201_CREATED)
else:
return Response(serialized_data.errors, status=HTTP_400_BAD_REQUEST)
我做了一个小东西来完成这项工作,但它并没有解决这个问题。以防万一这可以帮助某人。
data = {}
for item in request.DATA:
match = re.match("^form-(\d)-(.+)", item)
if match:
match_form = match.group(1)
match_key = match.group(2)
if not data.get(match_form, None):
data[match_form] = {}
data[match_form][match_key] = request.DATA[item]
for item in data:
serialized_data = RAGReportAtomBaseSerializer(data=data[item])