如何使用新的API为many2many字段正确创建,写入或取消链接记录? [英] How do I properly create, write or unlink records for many2many field using the new API?

查看:174
本文介绍了如何使用新的API为many2many字段正确创建,写入或取消链接记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以给我一个使用新API来操纵many2many字段的示例吗?我试图阅读文档无济于事.

Can someone give me an example to manipulate a many2many field using the new API? I've tried to read the Documentation to no avail.

这是我的示例类:

from openerp import models, fields, api, _

class example_class_one(models.Model):

    _name           = "example.class.one"

    name           = fields.Char('Name')
    value          = fields.Float('Value')

example_class_one()

class example_class_two(models.Model):

    _name           = "example.class.two"

    name                = fields.Char('Name')
    example_class_ones  = fields.Many2many('example.class.one',string='Example Class Ones')

    @api.one
    def test(self):
        #CREATES SOME example_class_ones and assign them to self
        #MANIPULATE SOME example_class_ones and save them
        #DELETE SOME example_class_ones from self
        pass

example_class_two()

推荐答案

在Odoo 8中,新的ORM API比前一个更好(带有所有这些无聊的参数(cr,uid,id,..)).使用此新API的最大好处之一是,我们现在正在使用对象,而不是 id .

In Odoo 8 the new ORM API is much nicer that the previous one (with all these boring (cr, uid, ids, ..) parameters). One of the big advantages for me with this new API is the fact that we are now working with objects, not ids.

您需要使用新方法的是self参数.您可以对其进行迭代-除其他外,它还包含odoo对象的集合.

All you need with the new methods is the self parameter. You can iterate over it - it's among other things also a collection of odoo objects.

还有一个魔术变量-self.env,其类型为Environment,包含所有这些cr, uid, etc.内容.它还包含所有已知模型的集合-这就是您所需要的.

And there is also one magic variable - self.env which is of type Environment and contains all this cr, uid, etc. stuff. It contains also a collection of all known models - that's what you need.

那你为什么不这样尝试呢?

So why don't you try this way:

@api.one
def test(self):
    model_one = self.env['example.class.one']
    model_one.create({'name': 'Some ONE object', 'value': 2.0})
    ones = model_one.browse([1, 3, 5])
    ones2 = model_one.search([('name', '=', 'Some name')])
    # You can imagine - search() return also objects! :)
    ones2[0].unlink()
    # Or, to deal with you many2many field...
    self.example_class_ones += model_one.new({
        'name': 'New comer to the many2many relation',
        'value': 666.0})

希望能回答您的问题.

这篇关于如何使用新的API为many2many字段正确创建,写入或取消链接记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆