You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Odoo12 PostgreSQL中产品图片二进制数据存储位置查询求助

Odoo12 从PostgreSQL提取产品图片实用方案

关联逻辑说明

Odoo12的产品图片存储在ir_attachment表中,和产品表的关联规则:

  • res_model字段对应产品模型:主产品用product.template,变体产品用product.product
  • res_id字段对应产品ID
  • datas字段是base64编码的图片二进制数据
  • datas_fname是图片原始文件名
  • res_field字段区分图片类型:主图为image,缩略图为image_small/image_medium

步骤1:连接数据库并查询关联数据

先通过psql连接到Odoo的PostgreSQL数据库(假设数据库名为odoo12_db,用户名为odoo):

psql -U odoo -d odoo12_db

执行查询获取产品与图片的关联数据:

SELECT
    pt.id AS product_id,
    pt.name AS product_name,
    ia.datas_fname AS image_filename,
    ia.datas AS image_base64
FROM
    product_template pt
JOIN
    ir_attachment ia ON ia.res_model = 'product.template' AND ia.res_id = pt.id
WHERE
    ia.res_field = 'image'  -- 按需替换为image_small/image_medium
ORDER BY
    pt.id;

若处理变体产品,将product_template替换为product_product,res_model改为'product.product'即可。


步骤2:导出查询结果到CSV

直接在psql中导出为CSV文件:

\copy (
    SELECT pt.id, pt.name, ia.datas_fname, ia.datas
    FROM product_template pt
    JOIN ir_attachment ia ON ia.res_model = 'product.template' AND ia.res_id = pt.id
    WHERE ia.res_field = 'image'
) TO '/tmp/product_images.csv' WITH (FORMAT CSV, HEADER, DELIMITER ',', ENCODING 'UTF8');

Docker部署注意:/tmp/product_images.csv是容器内路径,可通过docker cp <容器ID>:/tmp/product_images.csv ./复制到宿主机。


步骤3:Python脚本解码并保存图片

如果需要直接将base64数据转换为图片文件,使用以下脚本:

import csv
import base64
import os

# 创建图片保存目录
save_dir = './product_images'
os.makedirs(save_dir, exist_ok=True)

# 读取CSV并处理
with open('product_images.csv', 'r', encoding='utf-8') as csv_file:
    reader = csv.DictReader(csv_file)
    for row in reader:
        product_id = row['id']
        filename = row['image_filename'] or f'product_{product_id}.png'
        base64_data = row['image_base64']
        
        try:
            img_bytes = base64.b64decode(base64_data)
            with open(os.path.join(save_dir, filename), 'wb') as img_file:
                img_file.write(img_bytes)
            print(f"已保存:{filename}")
        except Exception as e:
            print(f"产品{product_id}处理失败:{str(e)}")

常见问题排查

  • 无匹配结果:检查res_field字段值是否正确,部分场景可能自定义了图片字段
  • 解码失败:确认datas字段未被截断,psql默认不截断长字段,若出现截断可调整client_max_messages参数

内容的提问来源于stack exchange,提问作者nando-ando

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 16:46:00