Ahmed Hached
Ahmed Hached

Reputation: 150

Call a function on Module Install

How to call a function or execute a code on module install only (Not update)? Is there a specific function for that ?

I want to execute this code on module install:

all_countries = self.env['res.country'].search([])
for country in all_countries:
   _logger.error(country.name)

Upvotes: 3

Views: 3809

Answers (2)

Travis Waelbroeck
Travis Waelbroeck

Reputation: 2135

The best way to do this is with a data file.

  1. Add the data file to your __openerp__ file
  2. Create the data file with the noupdate="1" flag
    • This indicates the code should be run once, then never again
    • It will run upon installation, or if the module is already installed, then it will the next time the module is upgraded.
  3. Define the function element in your data file to trigger the appropriate python method

You can see the documentation here for details, but the end result looks something like this:

__openerp__.py

{
    ...
    'data': [
        ...
        'data/data.xml',
        ...
    ],
    ...
}

/data/data.xml

<openerp>
    <data noupdate="1">
        <function model="res.country" name="method_name"/>
    </data>
</openerp>

/models/country.py

from openerp import models
import logging
_logger = logging.getLogger(__name__)

class ResCountry(models.Model):
    _inherit = 'res.country'

    @api.model
    def method_name(self):
        for country in self.search([]):
           _logger.error(country.name)

Upvotes: 8

T.V.
T.V.

Reputation: 467

I've implemented a workaround to run arbitrary code at install/uninstall time, that is described here in details. In your case suitable function to write your code in is a create method from the proposed workaround.

Upvotes: 1

Related Questions