Odoo V11中如何不使用关联字段设置字段默认值?(将计算字段overtime_w设为overtime_w_edit的默认值)
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
- When a user starts creating a new record, Odoo calls
default_getto populate initial field values. - We create a temporary record (
self.new()) that inherits any default values for other fieldsovertime_wdepends on (likehours_workedin the example). - We explicitly run the compute method
_compute_t_overtime_won the temporary record to generate the correctovertime_wvalue. - 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

