Python 2.7 奥多9如何正确地连接两个字符?

Python 2.7 奥多9如何正确地连接两个字符?,python-2.7,odoo,odoo-9,Python 2.7,Odoo,Odoo 9,我有3个字段,并试图对字段进行压缩,以便char3=char1+char2 编写了以下代码: # -*- coding: utf-8 -*- from openerp import models, fields, api from openerp.tools import ustr class pucrhase_order_pref_supplier(models.Model): _inherit = 'purchase.order.line' #this field will be

我有3个字段,并试图对字段进行压缩,以便char3=char1+char2

编写了以下代码:

# -*- coding: utf-8 -*-

from openerp import models, fields, api
from openerp.tools import ustr

class pucrhase_order_pref_supplier(models.Model):
    _inherit = 'purchase.order.line'
#this field will be displayed on the product list in the purchase order
    preferred_supplier_product = fields.Char(related="product_id.preferred_supplier_middle", string="Preferred Supplier", readonly="true")
    preferred_supplier_template = fields.Char(related="product_id.preferred_supplier_middle", string="Preferred Supplier", readonly="true")
    preferred_supplier = fields.Char(compute='_onchange_proc', store="True")

@api.one
@api.depends('preferred_supplier','preferred_supplier_product','preferred_supplier_template')
def _onchange_proc(self):
        string1 = self.preferred_supplier_product
        string2 = self.preferred_supplier_template
        output = ustr(string1)+"-"+ustr(string2)
        self.preferred_supplier = output

不确定原因,但未计算首选供应商(其他字段工作正常)。是否应改用onchange?

依赖项中的字段列表不应包含计算的相同字段。并且不依赖于相关字段,在其他模型中使用点进行深入

#如果未在表单视图中显示相关字段,则无需创建这些字段
@api.取决于(“产品id”、“产品id.首选供应商”,
“产品标识首选供应商中间”)
定义更改过程(自):
#我更喜欢使用字符串格式来完成这类工作
self.preferred\u supplier='%s-%s'(产品\u id.preferred\u supplier\u middle或“”,产品\u id.preferred\u supplier\u middle或“”)

首先,对代码本身进行一些评论: 首选供应商产品和首选供应商模板与完全相同的字段相关,我不认为应该是这样

正如Cherif所说,如果您甚至不需要视图中的字段,则无需创建它们

对于字段的readonly/store属性,我将使用Python True/False,而不是字符串

为什么计算依赖于自身

现在请回答:

@api.multi
@api.depends('preferred_supplier_product', 'preferred_supplier_template')
def _onchange_proc(self):
    for record in self:
        record.preferred_supplier = '%s-%s' % (record.preferred_supplier_product, record.preferred_supplier_template)
或者取决于是否需要为视图声明字段

@api.multi
@api.depends('product_id.preferred_supplier_middle')
def _onchange_proc(self):
    for record in self:
        record.preferred_supplier = '%s-%s' % (
            record.product_id.preferred_supplier_middle, record.product_id.preferred_supplier_middle)

您可以通过以下方法连接两个字符串:

@api.onchange('char1', 'char2')
def _onchange_weight_range(self):
    list = []
    if self.char1:
        conc = str(self.char1 or '') + '-' + str(self.char2 or '')
        list.append(conc)
        self.char3 = ', '.join(list)

Python并不是为了使事情复杂化。对于一个小操作,您可以编写所有这些代码!!