From ce0575ef274ec6419ffb08211461e7bdcbed1019 Mon Sep 17 00:00:00 2001 From: Denis Ledoux Date: Mon, 4 Feb 2019 14:08:48 +0000 Subject: [PATCH] [IMP] models: faster ensure_one implementation Calling `len` on a long list and checking that its value is 1 is slower than just unpacking the list. The point is to check whether there is just one item in the list, and counting all items just for that is a bit overkill. --- odoo/models.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/odoo/models.py b/odoo/models.py index b8c4df1a8f8..090e0686e97 100644 --- a/odoo/models.py +++ b/odoo/models.py @@ -4367,9 +4367,12 @@ class BaseModel(MetaModel('DummyModel', (object,), {'_register': False})): """ Verifies that the current recorset holds a single record. Raises an exception otherwise. """ - if len(self) == 1: + try: + # unpack to ensure there is only one value is faster than len for big lists + _id, = self._ids return self - raise ValueError("Expected singleton: %s" % self) + except ValueError: + raise ValueError("Expected singleton: %s" % self) def with_env(self, env): """ Returns a new version of this recordset attached to the provided