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

Odoo中肉牛金额自动计算未随磅价更新问题求助

问题分析

当前price_total字段仅在weight_cow更新时自动计算,核心原因是:

  • _compute_cost_import的@api.depends仅监听了当前模型的weight_cow和未实际使用的other_model.price_import,未关联到price.pound模型的记录变化
  • 计算逻辑通过search获取对应肉牛类型的最新磅价,但Odoo无法自动感知其他模型的记录变更来触发当前模型的计算字段更新
解决方案

需要从两方面调整代码:修正计算字段的依赖逻辑,同时在磅价记录变更时主动触发肉牛总金额的重新计算。

1. 修正主模块(livestock.model)的计算逻辑

清理无效依赖并优化查询性能:

from odoo import api, fields, models
from odoo.exceptions import ValidationError


class LivestockModel(models.Model):
    _name = 'livestock.model'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _description = 'New cattle from the agricultural and livestock farm created'
    _order = 'cow_id asc'
    _rec_name = 'cow_id'

    cow_id = fields.Char(
        required=True,
        string="Beef identifier",
        tracking=True
    )
    weight_cow = fields.Float(
        string="Current weight",
        tracking=True,
        store=True
    )
    other_model = fields.Many2one(
        'price.pound',
        string="Price per pound"
    )
    price_actually = fields.Monetary(
        compute="_compute_price_actually",
        string="Current price per kilo",
        store=True
    )
    price_import = fields.Monetary(
        related="other_model.price_import",
        string="Price per kilo",
        store=True
    )
    price_total = fields.Monetary(
        compute="_compute_cost_import",
        string="Amount",
        store=True
    )
    type_cow = fields.Selection(
        [
            ('Steer', 'Steer of meat'),
            ('Heifer', 'Beef Heifer')
        ], 
        string="Type of livestock:",
        required=True
    )

    @api.depends('weight_cow', 'type_cow')
    def _compute_cost_import(self):
        """Calculate total amount for each beef based on latest price of its type"""
        # 预先按type_cow分组获取最新磅价,减少重复查询
        latest_prices = {}
        for type_val in self.mapped('type_cow'):
            price_rec = self.env['price.pound'].search(
                [('type_cow', '=', type_val)], 
                order='date_pound desc', limit=1
            )
            latest_prices[type_val] = price_rec.price_import if price_rec else 0.0

        for record in self:
            if record.weight_cow:
                record.price_total = record.weight_cow * latest_prices.get(record.type_cow, 0.0)
            else:
                record.price_total = 0.0

2. 在辅助模块(price.pound)中添加触发更新逻辑

当新增、修改或删除磅价记录时,自动触发对应肉牛类型的所有肉牛记录重新计算price_total:

from odoo import api, fields, models

class LivestockPrice(models.Model):
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _name = 'price.pound'
    _description = "New pound price"
    _order = 'date_pound desc'

    name = fields.Char(string="New")
    active = fields.Boolean(string="Active", default=True)
    cow_id = fields.Many2one(
        'livestock.model',
        string="Beef identifier",
        required=True
    )
    date_pound = fields.Date(
        string="New price date",
        required=True,
        default=fields.Date.today()
    )
    price_import = fields.Monetary(
        string="Price per kilo",
        required=True,
        tracking=True
    )
    type_cow = fields.Selection(
        related='cow_id.type_cow',
        string="Type of livestock",
        readonly=False,
        store=True,
        required=True
    )

    @api.model
    def create(self, vals):
        res = super().create(vals)
        # 触发对应type_cow的肉牛记录更新总金额
        if res.type_cow:
            self.env['livestock.model'].search([('type_cow', '=', res.type_cow)]).sudo()._compute_cost_import()
        return res

    def write(self, vals):
        old_types = self.mapped('type_cow')
        res = super().write(vals)
        # 新旧type_cow对应的肉牛都需要更新
        new_types = self.mapped('type_cow')
        all_types = set(old_types + new_types)
        for type_val in all_types:
            self.env['livestock.model'].search([('type_cow', '=', type_val)]).sudo()._compute_cost_import()
        return res

    def unlink(self):
        types = self.mapped('type_cow')
        res = super().unlink()
        for type_val in types:
            self.env['livestock.model'].search([('type_cow', '=', type_val)]).sudo()._compute_cost_import()
        return res

说明

  • 主模块中修正了@api.depends,添加type_cow作为依赖(肉牛类型变更时也会重新计算),同时优化查询逻辑避免循环内重复搜索
  • 辅助模块通过重写create/write/unlink方法,在磅价记录变更时主动触发对应类型肉牛的总金额更新
  • 使用sudo()确保操作有足够权限(可根据实际权限配置调整)

内容的提问来源于stack exchange,提问作者Delvis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 11:09:50