如何将sale.order.line的product_uom_qty与account.invoice.line的quantity显示为整数
实现销售订单和发票行字段转为整数格式显示
下面分两种场景给出具体实现方案,基于Odoo自定义模块开发(避免修改核心代码):
场景一:仅界面显示为整数(数据存储仍为浮点型)
适合无需改变底层数据结构,仅优化前端显示的需求。
1. 销售订单行(sale.order.line)
方案A:修改字段小数位数控制显示
在自定义模块的模型文件中继承sale.order.line,重定义product_uom_qty字段的digits属性,设置小数位为0:
from odoo import models, fields class SaleOrderLine(models.Model): _inherit = 'sale.order.line' product_uom_qty = fields.Float( digits=(16, 0), string='Quantity' )
部署模块后,界面上该字段将自动显示为整数格式,底层存储仍保留浮点型精度。
方案B:用计算字段替代原字段
若需要更灵活的取整逻辑(如强制取整而非四舍五入),可新增计算字段并替换视图中的原字段:
from odoo import models, fields, api class SaleOrderLine(models.Model): _inherit = 'sale.order.line' product_uom_qty_int = fields.Integer( compute='_compute_product_uom_qty_int', inverse='_inverse_product_uom_qty_int', string='Quantity', store=False ) @api.depends('product_uom_qty') def _compute_product_uom_qty_int(self): for line in self: # 这里可替换为int(line.product_uom_qty)实现向下取整 line.product_uom_qty_int = int(round(line.product_uom_qty, 0)) def _inverse_product_uom_qty_int(self): for line in self: line.product_uom_qty = float(line.product_uom_qty_int)
之后修改销售订单的表单/列表视图,将原product_uom_qty字段替换为product_uom_qty_int即可。
2. 发票行(account.invoice.line / account.move.line)
Odoo 12及以下版本用account.invoice.line,13+版本用account.move.line,实现逻辑与销售订单行一致:
from odoo import models, fields class AccountInvoiceLine(models.Model): _inherit = 'account.invoice.line' # Odoo13+替换为'account.move.line' quantity = fields.Float( digits=(16, 0), string='Quantity' )
或采用计算字段方案,代码逻辑参考销售订单行部分。
场景二:存储与显示均改为整数型
需修改字段存储类型,同时处理原有浮点数据的迁移,操作前务必备份数据并在测试环境验证。
1. 销售订单行
步骤1:重定义字段类型
在模型文件中继承sale.order.line,将product_uom_qty改为整数型:
from odoo import models, fields class SaleOrderLine(models.Model): _inherit = 'sale.order.line' product_uom_qty = fields.Integer(string='Quantity')
步骤2:数据迁移脚本
在模块的migrations/[版本号]/目录下创建post-migrate.py,编写数据转换逻辑:
def migrate(cr, version): # 用ROUND实现四舍五入,也可改为CAST(product_uom_qty AS INTEGER)向下取整 cr.execute(""" UPDATE sale_order_line SET product_uom_qty = ROUND(product_uom_qty) WHERE product_uom_qty IS NOT NULL """)
2. 发票行
步骤1:重定义字段类型
from odoo import models, fields class AccountInvoiceLine(models.Model): _inherit = 'account.invoice.line' # Odoo13+替换为'account.move.line' quantity = fields.Integer(string='Quantity')
步骤2:数据迁移脚本
def migrate(cr, version): # Odoo13+需将表名改为account_move_line cr.execute(""" UPDATE account_invoice_line SET quantity = ROUND(quantity) WHERE quantity IS NOT NULL """)
注意事项
- 修改字段存储类型前,需确认所有关联逻辑(如金额计算、库存扣减)兼容整数运算;
- 自定义模块需正确声明对
sale、account模块的依赖; - 操作前务必备份数据库,避免数据丢失。
内容的提问来源于stack exchange,提问作者art
相关产品推荐
相关产品推荐

