向one2many添加列表

2024-06-26 00:18:27 发布

您现在位置:Python中文网/ 问答频道 /正文

对于我的用例,我试图在创建时将所有产品类别列表添加到联系人中。在

class product_category(models.Model):
            _inherit = "product.category" 
            is_checked = fields.Boolean('Don', help="Check this box if this contact make Donation.")
            resRelId = fields.Many2one('res.partner')

class res_partner(models.Model):
        _inherit = "res.partner"
        categs = fields.One2many('product.category','resRelId',String='Halo')
        @api.model
    def create(self, values):
        categs = self.env['product.category'].search([])
        new_id = super(res_partner, self).create(values)
        for i in categs:
            _logger.error(i)
            new_id.write({'categs': i})
        _logger.error(new_id.categs)
        return new_id

我的代码编译没有错误,但我总是在联系人中得到一个空的产品列表,我收到了这些警告。在

^{pr2}$

Tags: selfidfields列表newpartnermodelmodels
2条回答

有一种最简单的方法。在

@api.model
def create(self, values):
    ## Here categ is a list containing category ids.
    categs = self.env['product.category'].search([]).ids
    values.update({'categs':[(6, 0, categs or [])]})
    return super(res_partner, self).create(values)

你正试图写入一个2many字段。你不是这样给一个20多岁的人写信的。在

以下是从one2many中添加和删除的各种方法的简便提示:

(0, 0,  { values })    link to a new record that needs to be created with the given values dictionary
(1, ID, { values })    update the linked record with id = ID (write *values* on it)
(2, ID)                remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well)
(3, ID)                cut the link to the linked record with id = ID (delete the relationship between the two objects but does not delete the target object itself)
(4, ID)                link to existing record with id = ID (adds a relationship)
(5)                    unlink all (like using (3,ID) for all linked records)
(6, 0, [IDs])          replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs)

正确的方法是:

^{pr2}$

相关问题 更多 >