型号:
class Section(models.Model):
name = models.CharField(max_length=50)
building = models.ForeignKey(Building, related_name='sections', on_delete=models.CASCADE)
class Standpipe(models.Model):
name = models.CharField(max_length=50)
section = models.ForeignKey(Section, related_name='pipes', on_delete=models.CASCADE)
序列化程序:
class StandpipeSerializer(serializers.ModelSerializer):
class Meta:
model = Standpipe
fields = '__all__'
class SectionSerializer(serializers.ModelSerializer):
pipes = StandpipeSerializer(many=True, required=False)
class Meta:
model = Section
fields = ('name', 'building', 'pipes')
def create(self, validated_data):
pipes_data = validated_data.pop('pipes')
section = Section.objects.create(**validated_data)
for pipe_data in pipes_data:
Standpipe.objects.create(section=section, **pipe_data)
return section
视图只是一个常规的ModelViewSet。我没有重写任何方法。
我在请求中发送此数据:
{
'name': 'One',
'building': 1,
'pipes': [
{'name': 'PipeOne'},
{'name': 'PipeTwo'},
]
}
但在经过验证的数据中,我只得到
{'name': 'One', 'building': <Building: Building object (1)>}
在序列化程序的初始数据中,我们可以看到:
<QueryDict: {'name': ['One'], 'building': ['1'], 'pipes': ["{'name': 'PipeOne'}", "{'name': 'PipeTwo'}"]}>
如果我试图从最初的dict中获得关键的"管道",我只能获得第二个dict
"{'name': 'PipeTwo'}"
仅以字符串格式与。如果我从中删除"required=False",我会得到一个错误:
{'pipes': [ErrorDetail(string='This field is required.', code='required')]}
无法理解为什么会出错。我尝试使用文件中的解决方案
问题出在我的测试用例上。我使用drf"APITestCase"发送数据。代码看起来像:
response_section = self.client.post(url_section, data={'name': 'One',
'building': response_building.data['id'],
'pipes': [
{'name': 'PipeOne'},
{'name': 'PipeTwo'}]
})
因此,解决方案是添加
format='json'
所以现在看起来像
response_section = self.client.post(url_section, data={'name': 'One',
'building': response_building.data['id'],
'pipes': [
{'name': 'PipeOne'},
{'name': 'PipeTwo'}
]
}, format='json')
并且运行良好