无法为Python(Django)函数调用添加额外的参数

时间:2017-01-20 11:07:54

标签: python django django-rest-framework

我需要使用序列化程序序列化数据,并且我还有一个用于保存的文件,但我无法将带有文件的额外变量路径到我的序列化程序

issue_dict = request.data.get('issue')
file = request.data.get('file')

这很好用:

 serializer = WriteIssueSerializer(data=issue_dict, context=self.get_serializer_context())

这就是我想要的,但它说"得到了一个意想不到的关键字参数' file'" :

 serializer = WriteIssueSerializer(data=issue_dict, file=file, context=self.get_serializer_context())

我明白在序列化程序中我应该定义变量" file", 所以看看这个序列化器:

class WriteIssueSerializer(serializers.ModelSerializer):
    notes = IssueNoteSerializer(many=True)

    def create(self, val):
        issue_dict = val.get('issue')
        # issue_dict['assigned_to'] = issue_dict['assigned_to']['id']
        # issue_dict['reported_by'] = issue_dict['reported_by']['id']

        assigned_to_id = issue_dict.pop('assigned_to').id
        reported_by_id = issue_dict.pop('reported_by').id
        notes_info = issue_dict.pop('notes')
        # print(validated_data.pop('file'))
        issue = Issue.objects.create(assigned_to_id=assigned_to_id, reported_by_id=reported_by_id, **issue_dict)
        for note_info in notes_info:
            note = IssueNote.objects.create(**note_info)
            note.issue = issue
很明显,改变了 def create(self, val):def create(self, val, file):会修复我的错误,但,错误仍然相同

1 个答案:

答案 0 :(得分:1)

serializer = WriteIssueSerializer(data=issue_dict, file=file, context=self.get_serializer_context())

这会调用WriteIssueSerializer(__init__())的构造函数,而不是.create()。所以你必须在那里创建额外的参数,或者调用.create()