且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

int()参数必须是字符串或数字,而不是'Files'

更新时间:2022-11-12 16:08:32

你必须告诉序列化器你期望哪个模型字段获取值。

You have to tell the serializer from which model field do you expect it to get the value from.

class DocumentSerializer(serializers.ModelSerializer):
    file_id = serializers.PrimaryKeyRelatedField(queryset=Files.objects.all(), 
                                                 source='file')

因为如果没有,restframework试图使用来自序列化程序的定义的名称,因此它将使用 file_id ,并且实际上不存在于 Documents 模型中。 p>

Because if you dont, restframework tries to use the defined name from the serializer so it will use file_id and that is actually not present in the Documents model.

# this is how PrimaryKeyRelatedField resolves its pk value
pk = getattr(obj, self.source or field_name).pk