In this tutorial I will learn you how to install data in a module by default. This will mean that data is automatically inserted in the database whenever you would install this module. In some cases this is very handy because you need some default values inserted when the module is installed.
1. Adding a new XML file to the module
The first thing you need to do is create a new XML file in your custom module, for example demodata.xml, and to add the filename to __openerp__.py. An example of my __openerp__.py file:
# -*- coding: utf-8 -*-
A demo that shows how default data is created in code and how it is inserted in the Odoo db.""",
A demo that shows how default data is created in code and how it is inserted in the Odoo db.
'author': "Yenthe Van Ginneken",
# Categories can be used to filter modules in modules listing
# Check https://github.com/odoo/odoo/blob/master/openerp/addons/base/module/module_data.xml
# for the full list
# any module necessary for this one to work correctly
# always loaded
#This will link to a file in the folder data. This file, defaultdata.xml will contain the data that is automatically installed when the module is installed.
# only loaded in demonstration mode
Create default data
After you’ve added the location to the file (to __openerp__.py) you should create the data for the file. Open up your custom module, go in to the folder data and edit your XML file. The structure is always the same. You give the record a name (this can be anything, make sure its unique) and add the name of the model where you want data installed in. Then add a field for every field you have in the model which you want to fill with data. The following is an example that creates a record in the model ‘demo.default.data’ when you install the module:
<record id="first_course_item" model="demo.default.data">
<field name="name">Record #1</field>
<field name="description">A description for record #1.</field>
As you can see by this record with demo data it will create a new record with a name named ‘Record #1’ and a description with the text ‘A description for record #1’. These are the fields that I’ve created in my custom model (models.py) like this:
# -*- coding: utf-8 -*-
from openerp import models, fields, api
_name = 'demo.default.data'
_description = 'Demo default data'
name = fields.Char('Name', required=True)
description = fields.Html('Description')
When you would now install this module it will automatically install the records that are defined.
Want to see an example module where you can see how everything works? You can download/view it on Github!
Has this tutorial helped you, do you have any feedback or questions? Post away!