基于Preload字段动态设置part_template_ids默认值的技术咨询
part_template_ids Based on preload Field Got it, let's tackle this problem of adjusting the default value for part_template_ids based on the preload field in Odoo. Here's a practical, step-by-step solution that works for both new records and real-time form updates:
1. Update the Default Value Method
Modify your existing _default_part_template_ids method to check the preload value and switch logic accordingly. Keep in mind that when creating a new record, project_id might not be set yet—so we need to handle that edge case to avoid errors:
def _default_part_template_ids(self): # Get preload value only if project exists; default to False otherwise preload = self.preload if self.project_id else False if preload: # Replace this with YOUR custom logic for when preload is True # Example: Fetch templates directly linked to the current project domain = [('project_id', '=', self.project_id.id)] return self.env['project.part.template'].search(domain) else: # Keep your original default logic for preload=False domain = [('case_default', '=', True)] return self.env['project.part.template'].search(domain)
2. Add an Onchange for Real-Time Updates
If users select a project after opening the form, you'll want part_template_ids to update automatically based on the new preload value. Add this onchange method to make that happen:
@api.onchange('project_id') def _onchange_project_id(self): # Refresh part templates whenever the selected project changes if self.project_id: self.part_template_ids = self._default_part_template_ids()
Key Notes to Remember
- Edge Case Handling: When creating a new record,
project_idis often empty initially. The checkself.preload if self.project_id else Falseprevents errors from trying to access a related field on a non-existent record. - Customize the Preload Logic: Swap out the example domain in the
preload=Trueblock with whatever logic you need—maybe templates tagged as "preload-ready" or specific to the project's type. - User Experience: The onchange method ensures users don't have to manually refresh the field after selecting a project; it updates automatically.
This setup will make part_template_ids use your custom default whenever preload is True, and fall back to your original default when it's False.
内容的提问来源于stack exchange,提问作者Chaban33

