Skip to main content
 首页 » 编程设计

python之将 matplotlib 图保存为数据库中的图像字段

2024年11月01日13jillzhang

我刚开始学习 matplotlib,我想在我的一个 Django 应用程序中使用它。所以我想知道如何保存在我的模型的图像字段中生成的图形,以便我可以在需要时进行检索。

请您参考如下方法:

matplotlib.pyplot.savefig接受类文件对象作为第一个参数。您可以传递 StringIO/BytesIO(根据您的 python 版本)。

f = StringIO() 
plt.savefig(f) 

然后,使用django.core.files.ContentFile将字符串转换为 django.core.files.File (因为 FieldFile.save 只接受 django.core.files.File 的实例)。

content_file = ContentFile(f.getvalue()) 
model_object = Model(....) 
model_object.image_field.save('name_of_image', content_file) 
model_object.save()