Optimize "create" overrides by using the decorator "model_create_multi"

In some cases, there is a need to override the create​ method in Odoo and add additional logic to it. 

When overriding this method, the custom logic is triggered on each iteration of creating a new object.

 This means whenever a new object is created the extra code will be evaluated and applied.

In case when the additional logic is closely related to the object's data, this approach can be all right, since the codebase looks simpler and more clear.

However, in situations where some of the custom logic is repeating, especially when using database data, the logic will be executed n-times for n-objects, without any need for that.

In such cases should be used the decorator model_create_multi​. Adding this decorator to the create​ method allows the repeating code to be executed only once and applied to each object using a for​ loop.

It is important to mention that when using the model_create_multi​ decorator, the method receives a list of values while returns a list of newly created objects.

A very simple case to understand the need for this decorator is shown below:


@api.model_create_multi
def create(self, vals_list):
    round_precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
    for vals in vals_list:
		    vals["quantity"] = float_round(vals["quantity"], precision_digits=round_precision)
    return super().create(vals_list)
        

Without using the decorator the logic related to getting the value for round_precision​ will be executed every time a new object is created, which means for a batch of n-objects will be executed n-times.

But in our example, it will be executed only once and applied to all object values using the for​ loop.

in Tips