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

基于Preload字段动态设置part_template_ids默认值的技术咨询

Dynamically Set Default for 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_id is often empty initially. The check self.preload if self.project_id else False prevents 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=True block 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:19:50