我有以下django-rest序列化器:
class FileSerializer(serializers.ModelSerializer):
class Meta:
model = FileModel
fields = ('id', '_file')
class SomeSerializer(serializers.ModelSerializer):
files = FileSerializer(many=True, required= False)
class Meta:
model = SomeModel
fields = ('id', 'files')
和模特
class File(models.Model):
some_obj = models.ForeignKey('SomeObj',related_name='files', blank=True, null=True)
_file = models.FileField(upload_to=get_file_path)
当我使用现有的File对象
创建SomeSerializer时,问题出现了s = SomeSerializer(data = {'files': [{'id' : 1}]})
s.is_valid()
s.errors
返回
False
{'_file': [u'No file was submitted.']}
如何解决这个问题?感谢。
答案 0 :(得分:0)
嗯,这个消息非常明显。您没有为序列化程序提供“_file”。这应该解决:
s = SomeSerializer(data = {'files': [{'id' : 1, '_file': <somedata>}]})
答案 1 :(得分:0)
_file
字段,如果不需要,请将required
设置为False
:
class FileSerializer(serializers.ModelSerializer):
_file = serializer.FileField(required=False)
class Meta:
model = FileModel
fields = ('id', '_file')