如何从odoo中的one2many字段中获取值

AKH*_*HEW 1 python odoo-8

在帐户模块中的客户发票中,有一个one2many字段,

invoice_line = fields.One2many('account.invoice.line', 'invoice_id', string='Invoice Lines')
Run Code Online (Sandbox Code Playgroud)

使用此字段,我们可以在发票中添加多个产品.添加多个产品后,如何将这些产品从这个领域中分离出来,这样我就可以获得产品ID.

假设我们保存两个产品,我们将有两个条目.从这两个条目我需要分离每个产品的产品ID

qvp*_*ham 5

对于你的问题,我只能给你一个通用的答案.我希望,你可以从它开始.

在odoo模型(osv.osv,...)中,您可以使用它self.pool.get("model name")来获取任何模型的对象池.使用此池,您可以使用该方法read()读取数据.
Odoo模型主要存储在数据库的一个表中.

首先,您需要了解Odoo中对象的关系.在你的情况下它是这样的:

account.invoice --(invoice_line_ids:one2many)--> account.invoice.line --(product:many2one)-> product
Run Code Online (Sandbox Code Playgroud)
  • 读取one2many字段将返回list目标对象的ID.
  • 读取Many2one字段将返回int目标对象的ID值.

以下是从发票行中获取产品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]
Run Code Online (Sandbox Code Playgroud)

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))
Run Code Online (Sandbox Code Playgroud)

P/S:您需要自定义我的代码以适合您的代码,因为我不太了解您的想法.我正在使用Odoo 9.但它与Odoo 8的核心大致相同