跳至内容
菜单
此问题已终结
5 回复
51989 查看
最佳答案

Hi MouBou,

self.ensure_one is made to ensure that only one record is being passed on. It checks that the current record is a singleton (so just one record, not multiple records). If self would contain multiple records the system would throw up an error. An example case to check you just have one record:

@api.multi
def some_fuction(self):
    # This will make sure we have on record, not multiple records.
self.ensure_one()

When you would run this code with a selection of records (for example selecting multiple records from a treeview) the self.ensure_one() would check this and throw up an error.

A general rule of thumb is to only use self.ensure_one when you are sure / want to be sure you only have one record, not multiple. In cases of you using multiple records in one action you should use @api.multi without self.ensure_one()
Have a look at the ORM documentation: https://www.odoo.com/documentation/8.0/reference/orm.html

Yenthe

形象
丢弃
最佳答案

This function will be called !!!




Thanks !!
iWesabe

形象
丢弃
最佳答案

In odoo 15, this is what ensure_one do

    def ensure_one(self):
        """Verify that the current recorset holds a single record.

        :raise odoo.exceptions.ValueError: ``len(self) != 1``
        """
        try:
            # unpack to ensure there is only one value is faster than len when true and
            # has a significant impact as this check is largely called
            _id, = self._ids
            return self
        except ValueError:
            raise ValueError("Expected singleton: %s" % self)



形象
丢弃
最佳答案

To reply your second question,

You can use @api.one, but since @api.one put returned value in a list and it is not always supported by the web client, therefore most of the developers uses@api.multi with self.ensureone().

Refer to this link for more details,

http://odoo-new-api-guide-line.readthedocs.io/en/latest/decorator.html

形象
丢弃
最佳答案

@Yenthe: so why not use @api.one only, example:

@api.one
def some_fuction(self):
     # ...
形象
丢弃

We can't call wizards from @api.one.