如何在Odoo的payment.term模型中通过Python获取关联的account.invoice记录ID
获取关联的Account Invoice ID(Python方案)
Hey there! I get you want to grab the related account.invoice record ID when opening a payment.term form, using Python instead of just XML context. Let's break down how to do this properly in Odoo.
Core Principle
When you open the payment.term form from an account.invoice record (via the payment_term_id Many2one field), Odoo automatically passes the current invoice's ID in the context as active_id, along with the model name as active_model (which will be account.invoice here). We can leverage this context in Python code.
Step-by-Step Implementation
First, inherit the account.payment.term model and add your custom methods:
from odoo import models, api class AccountPaymentTerm(models.Model): _inherit = 'account.payment.term' @api.model def fetch_related_invoice_id(self): """Fetch the ID of the related account.invoice record from context""" # Extract context values active_id = self.env.context.get('active_id') active_model = self.env.context.get('active_model') # Validate we're coming from an account.invoice record if active_model == 'account.invoice' and active_id: return active_id # Return False if no valid invoice found in context return False @api.model def default_get(self, fields): """Auto-fetch invoice ID when loading the payment.term form""" res = super().default_get(fields) # Get the related invoice ID invoice_id = self.fetch_related_invoice_id() if invoice_id: # Here you can do whatever you need with the invoice ID: # - Store it in a custom field (if you added one to payment.term) # - Fetch invoice details to pre-fill payment term values # - Log it for debugging # Example: If you have a field 'related_invoice_id' on payment.term: # res['related_invoice_id'] = invoice_id pass return res
Key Explanations
fetch_related_invoice_idMethod:- This method pulls
active_idandactive_modelfrom the current context. - We validate
active_modelto make sure we're actually coming from anaccount.invoicerecord (avoids errors if opening payment terms from other menus).
- This method pulls
default_getMethod:- Odoo calls this method when loading a form to set default values.
- We use it here to automatically fetch the invoice ID as soon as the payment term form opens, so you can use it for any pre-processing or data retrieval.
Usage Notes
- This will only work when opening the
payment.termform directly from anaccount.invoicerecord. If you open payment terms from the main menu or another model,active_idwon't correspond to an invoice. - If you need to use the invoice ID in a button action on the payment term form, you can call
self.fetch_related_invoice_id()directly in that button's method—since the context stays intact when interacting with the form.
内容的提问来源于stack exchange,提问作者Tessnim
相关产品推荐
相关产品推荐

