AttributeError:' int'对象没有属性' id' - Odoo v9社区

时间:2016-11-10 15:22:01

标签: python csv openerp odoo-9

通过上传csv,我已经迁移了一个可以创建stock.inventory动作的模块。

它运作良好,但有时候,当我上传某些csv时,它会抛出这个错误:

Odoo

Odoo Server Error

Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 648, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 685, in dispatch
result = self._call_function(**self.params)
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 321, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 118, in wrapper
return f(dbname, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 314, in checked_call
result = self.endpoint(*a, **kw)
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 964, in __call__
return self.method(*args, **kw)
File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 514, in response_wrap
response = f(*args, **kw)
File "/usr/lib/python2.7/dist-packages/openerp/addons/web/controllers/main.py", line 892, in call_button
action = self._call_kw(model, method, args, {})
File "/usr/lib/python2.7/dist-packages/openerp/addons/web/controllers/main.py", line 880, in _call_kw
return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 250, in wrapper
return old_api(self, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 421, in old_api
result = new_api(recs, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 425, in new_api
result = [method(rec, *args, **kwargs) for rec in self]
File "/usr/lib/python2.7/dist-packages/openerp/custom_addons/stock_inventory_import/wizard/import_inventory.py", line 85, in action_import
val['location_id'] = prod_location.id
AttributeError: 'int' object has no attribute 'id'

代码是这样的:

@api.one
def action_import(self):
    """Load Inventory data from the CSV file."""
    ctx = self._context
    stloc_obj = self.env['stock.location']
    inventory_obj = self.env['stock.inventory']
    inv_imporline_obj = self.env['stock.inventory.import.line']
    product_obj = self.env['product.product']
    if 'active_id' in ctx:
        inventory = inventory_obj.browse(ctx['active_id'])
    if not self.data:
        raise exceptions.Warning(_("You need to select a file!"))
    # Decode the file data
    data = base64.b64decode(self.data)
    file_input = cStringIO.StringIO(data)
    file_input.seek(0)
    location = self.location
    reader_info = []
    if self.delimeter:
        delimeter = str(self.delimeter)
    else:
        delimeter = ','
    reader = csv.reader(file_input, delimiter=delimeter,
                        lineterminator='\r\n')
    try:
        reader_info.extend(reader)
    except Exception:
        raise exceptions.Warning(_("Not a valid file!"))
    keys = reader_info[0]
    # check if keys exist
    if not isinstance(keys, list) or ('code' not in keys or
                                      'quantity' not in keys):
        raise exceptions.Warning(
            _("Not 'code' or 'quantity' keys found"))
    del reader_info[0]
    values = {}
    actual_date = fields.Date.today()
    inv_name = self.name + ' - ' + actual_date
    inventory.write({'name': inv_name,
                     'date': fields.Datetime.now(),
                     'imported': True, 'state': 'confirm'})
    for i in range(len(reader_info)):
        val = {}
        field = reader_info[i]
        values = dict(zip(keys, field))
        prod_location = location.id
        if 'location' in values and values['location']:
            locat_lst = stloc_obj.search([('name', '=',
                                           values['location'])])
            if locat_lst:
                prod_location = locat_lst[0]
        prod_lst = product_obj.search([('default_code', '=',
                                        values['code'])])
        if prod_lst:
            val['product'] = prod_lst[0].id
        if 'lot' in values and values['lot']:
            val['lot'] = values['lot']
        val['code'] = values['code']
        val['quantity'] = values['quantity']
        val['location_id'] = prod_location.id
        val['inventory_id'] = inventory.id
        val['fail'] = True
        val['fail_reason'] = _('No processed')
        inv_imporline_obj.create(val)

csv看起来像这样:

id       product_id     reference                   code    combinacion avanzadastock   location                            quantity    qty
2780    Piloto trasero  Recambio Ecológico Original M0002780                            gsx 600 f 600 1988-1991/4316/A8I    1   

此错误会不时出现,通常只会正常运行,但其他一些时候会抛出此错误。

它正好位于location列。

我有超过5k项目的csv,所以我很难跟踪错误。

这个csv有关吗?或者这是代码问题?

3 个答案:

答案 0 :(得分:3)

问题是你的逻辑

prod_location = location.id

然后从未输入以下if语句,并转到

val['location_id'] = prod_location.id

错误被抛出

答案 1 :(得分:1)

是的,没错。某些位置不存在于系统上。它会引发错误。为避免此类错误,您可以使用以下技巧。

prod_location = self.location and self.location.id or False

表示系统是否具有位置,然后 prod_location 变量设置值 id ,否则 False

注:

在模型声明中, location_id 字段设置为required = False,否则您无法使用 location_id = False创建记录它将为您提供完整性错误。

答案 2 :(得分:0)

实际上问题是csv内容

由于某些位置不存在于系统中,因此会抛出该错误。

因此,在继续该过程之前,需要检查确实存在的位置。

谢谢。