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

Odoo V11中如何不使用关联字段设置字段默认值?(将计算字段overtime_w设为overtime_w_edit的默认值)

Solution to Set Computed Field as Default for Editable Field

Got it, let's work through how to set the computed overtime_w value as the default for overtime_w_edit without using related fields. Here's a practical, Odoo-native approach:

Key Context First

Since overtime_w is a computed field, its value isn't stored in the database—so we can't just reference it directly in the default parameter of overtime_w_edit. Instead, we need to explicitly trigger the field's computation when setting up default values for new records.

Implementation Code

We'll override the model's default_get method. This method handles fetching default values when creating a new record, making it the ideal spot to compute overtime_w and pass its value to overtime_w_edit.

from odoo import models, fields

class YourTargetModel(models.Model):
    _name = 'your.model.name'  # Replace with your actual model name
    _description = 'Your Model Description'

    overtime_w = fields.Float(compute='_compute_t_overtime_w')
    overtime_w_edit = fields.Float()

    def _compute_t_overtime_w(self):
        # Keep your existing computation logic here
        for record in self:
            # Example calculation—swap this with your actual logic
            record.overtime_w = record.hours_worked * 1.5  # Adjust based on your fields

    def default_get(self, fields_list):
        # Grab default values from the parent method first
        res = super().default_get(fields_list)
        
        # Create a temporary record to compute overtime_w (inherits other default values)
        temp_record = self.new()
        # Trigger the compute method to calculate the overtime_w value
        temp_record._compute_t_overtime_w()
        
        # Assign the computed value as default for overtime_w_edit if it's requested
        if 'overtime_w_edit' in fields_list:
            res['overtime_w_edit'] = temp_record.overtime_w
        
        return res

How This Works

  1. When a user starts creating a new record, Odoo calls default_get to populate initial field values.
  2. We create a temporary record (self.new()) that inherits any default values for other fields overtime_w depends on (like hours_worked in the example).
  3. We explicitly run the compute method _compute_t_overtime_w on the temporary record to generate the correct overtime_w value.
  4. Finally, we set that computed value as the default for overtime_w_edit.

This ensures overtime_w_edit starts with the same value as the computed overtime_w when a new record is created—no related fields required.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 22:59:11