问题
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.
Here are my example classes:
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()
回答1:
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.
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.
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})
Hope that answers you question.
回答2:
You can refer to my case as below,
either on @api
@api.onchange('opportunity_id')
def _get_description(self):
if self.opportunity_id.id:
self.x_description = self.opportunity_id.x_description
or declare as setup relationship and field (related) as link below
Pass custom field values from oppertunity to quotation in odoo 10
来源:https://stackoverflow.com/questions/32434541/how-do-i-properly-create-write-or-unlink-records-for-many2many-field-using-the