在账户模块的客户发票中有一个one2many字段,
invoice_line = fields.One2many('account.invoice.line', 'invoice_id', string='Invoice Lines')
使用此字段,我们可以在发票中添加多个产品。添加多个产品后如何从该字段中分离这些产品,以便我将获得产品 ID。
假设如果我们保存两个产品,我们将有两个条目。从这两个条目中,我需要将每个产品的产品 ID 分开
请您参考如下方法:
对于你的问题,我只能给你一个笼统的回答。我希望,您可以从它开始。
在 odoo 模型(osv.osv, ...)中,您可以使用 self.pool.get("model name") 获取对象池任何模型。使用此池,您可以使用方法 read() 读取数据。
Odoo 模型主要存储在数据库的一个表中。
首先您需要了解 Odoo 中对象的关系。在你的情况下是这样的:
account.invoice --(invoice_line_ids:one2many)--> account.invoice.line --(product:many2one)-> product
- 读取 one2many 字段会返回目标对象 ID 的
列表。 - 读取 Many2one 字段返回目标对象 ID 的
int值。
这是一个从发票行中获取产品 ID 的示例:
# call object pool for account.invoice
invoice_pool = self.pool.get("account.invoice")
# here you need the invoice_id to get the data.
# you can get it by parsing the parameter context
found_invoices = invoice_pool.read(cr, uid, [invoice_id,], ["invoice_line_ids"], context)
# It returns a list, but i gave only one invoice_id.
# the list has maximun one element. we need the frist element
found_invoice = found_invoices[0] if found_invoices else None
invoice_line_ids = found_invoice["invoice_line_ids"]
# the same with "account.invoice.line"
invoice_line_pool = self.pool.get("account.invoice.line")
invoice_lines = invoice_line_pool.read(cr, uid, invoice_line_ids, ["product_id"], context)
# Here you have the product ids
# I don't need to get the first element, because it returns a int
product_ids = [line["product_id"] for line in invoice_lines]
cr、uid、context 是参数,您可以从请求中获取这些参数。你可以通过覆盖方法read, write, .... 重要提示:您需要 invoice_id 才能开始。您可以通过解析变量 context 来获取此值。
您可以使用logging 来显示日志文件中context 的内容:
import logging
_logger = logging.getLogger(__name__)
_logger.info("context type: " + type(context))
_logger.info("context content: " + str(context))
P/S:您需要自定义我的代码以适合您的代码,因为我对您的想法知之甚少。我正在使用 Odoo 9。但它与 Odoo 8 的核心基本相同
