Technical
Custom Odoo Module: Structure, Security, Tests and Upgrades
A practical walkthrough of building a custom Odoo module that is easy to maintain: folder layout, models, views, access rights, record rules, inheritance, tests and version upgrades.
Kalvyai Engineering · · 6 min read

On this page
Most Odoo upgrade pain comes from custom modules that were written to work today, not to survive next year. This post walks through one small module, end to end, and points out the choices that keep it clean: where files go, how to define models and views, how to lock down access, how to extend core apps without copying them, how to test, and how to make the next version upgrade boring.
The example is an Asset Loan module. It tracks equipment lent to people, and adds a tab on the contact form. The code targets Odoo 17. Where Odoo 18 differs, we say so.
Module structure
A predictable layout makes a module easy to review and easy to upgrade. Keep one model per Python file, and group XML by purpose.
asset_loan/
├── __init__.py
├── __manifest__.py
├── models/
│ ├── __init__.py
│ ├── asset_loan.py
│ └── res_partner.py
├── views/
│ ├── asset_loan_views.xml
│ ├── res_partner_views.xml
│ └── menus.xml
├── security/
│ ├── security.xml
│ └── ir.model.access.csv
├── migrations/
├── tests/
│ ├── __init__.py
│ └── test_asset_loan.py
└── static/description/icon.pngFiles you extend from other modules (here res_partner.py and res_partner_views.xml) are named after the model they touch. Anyone opening the module can see at a glance what it changes in core.
The manifest
{
"name": "Asset Loan",
"version": "17.0.1.0.0",
"summary": "Track equipment lent to employees and partners",
"license": "LGPL-3",
"depends": ["base"],
"data": [
"security/security.xml",
"security/ir.model.access.csv",
"views/asset_loan_views.xml",
"views/res_partner_views.xml",
"views/menus.xml",
],
"installable": True,
"application": True,
}Three things matter here:
- Version format. Start with the Odoo series (
17.0), then your own version (1.0.0). Bumping your part is what triggers migration scripts later. - Depend on the smallest set of modules you need. Every dependency is something that can change under you on upgrade.
- Data file order matters. Groups must load before the CSV that references them, and the window action must load before the menu that points to it.
The init files
# asset_loan/__init__.py
from . import models
# asset_loan/models/__init__.py
from . import asset_loan
from . import res_partnerModels and fields
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class AssetLoan(models.Model):
_name = "asset.loan"
_description = "Asset Loan"
_order = "date_out desc, id desc"
name = fields.Char(string="Asset", required=True)
partner_id = fields.Many2one("res.partner", string="Borrower", required=True)
user_id = fields.Many2one(
"res.users", string="Responsible", default=lambda self: self.env.user
)
company_id = fields.Many2one(
"res.company", required=True, default=lambda self: self.env.company
)
date_out = fields.Date(required=True, default=fields.Date.context_today)
date_due = fields.Date()
date_returned = fields.Date(readonly=True)
state = fields.Selection(
[("draft", "Draft"), ("out", "Lent out"), ("returned", "Returned")],
default="draft",
required=True,
)
is_overdue = fields.Boolean(compute="_compute_is_overdue")
@api.depends("date_due", "state")
def _compute_is_overdue(self):
today = fields.Date.context_today(self)
for loan in self:
loan.is_overdue = bool(
loan.state == "out" and loan.date_due and loan.date_due < today
)
@api.constrains("date_out", "date_due")
def _check_dates(self):
for loan in self:
if loan.date_due and loan.date_due < loan.date_out:
raise ValidationError(_("Due date cannot be before the loan date."))
def action_lend(self):
self.write({"state": "out"})
def action_return(self):
self.write({
"state": "returned",
"date_returned": fields.Date.context_today(self),
})Some habits worth keeping:
- Always set
_description. Odoo warns when it is missing, and it is what users see in several places. - Loop over
selfin computes and constraints. Methods receive recordsets, not single records. - Add
company_idearly if there is any chance the database becomes multi-company. Adding it later means a data migration. - Put business logic in methods, not in view attributes or automated actions scattered around the database. Methods are versioned in git and covered by tests.
- Wrap user-facing strings in
_()so they can be translated.
Views
Define a list, a form, a search view and an action. In Odoo 17 the list view uses the <tree> tag and the action uses tree,form. In Odoo 18 these became <list> and list,form.
<odoo>
<record id="asset_loan_view_tree" model="ir.ui.view">
<field name="name">asset.loan.tree</field>
<field name="model">asset.loan</field>
<field name="arch" type="xml">
<tree>
<field name="name"/>
<field name="partner_id"/>
<field name="date_out"/>
<field name="date_due"/>
<field name="state"/>
</tree>
</field>
</record>
<record id="asset_loan_view_form" model="ir.ui.view">
<field name="name">asset.loan.form</field>
<field name="model">asset.loan</field>
<field name="arch" type="xml">
<form>
<header>
<button name="action_lend" string="Lend" type="object"
class="btn-primary" invisible="state != 'draft'"/>
<button name="action_return" string="Mark Returned" type="object"
invisible="state != 'out'"/>
<field name="state" widget="statusbar"/>
</header>
<sheet>
<group>
<group>
<field name="name"/>
<field name="partner_id"/>
<field name="user_id"/>
</group>
<group>
<field name="date_out"/>
<field name="date_due"/>
<field name="date_returned"/>
<field name="is_overdue"/>
<field name="company_id" groups="base.group_multi_company"/>
</group>
</group>
</sheet>
</form>
</field>
</record>
<record id="asset_loan_view_search" model="ir.ui.view">
<field name="name">asset.loan.search</field>
<field name="model">asset.loan</field>
<field name="arch" type="xml">
<search>
<field name="name"/>
<field name="partner_id"/>
<filter name="filter_out" string="Lent out" domain="[('state', '=', 'out')]"/>
</search>
</field>
</record>
<record id="asset_loan_action" model="ir.actions.act_window">
<field name="name">Asset Loans</field>
<field name="res_model">asset.loan</field>
<field name="view_mode">tree,form</field>
</record>
</odoo>Note the invisible="state != 'draft'" syntax. Since Odoo 17, the old attrs and states attributes are gone and conditions are written directly as expressions. If you are maintaining a module from Odoo 16 or earlier, this is one of the first things that breaks.
The menu file, restricted to our user group:
<odoo>
<menuitem id="asset_loan_menu_root" name="Asset Loans"
groups="group_asset_loan_user"/>
<menuitem id="asset_loan_menu_loans" name="Loans"
parent="asset_loan_menu_root" action="asset_loan_action"/>
</odoo>Access rights and record rules
Odoo security has two layers, and you need both:
- Access rights (
ir.model.access) decide whether a group can read, write, create or delete records of a model at all. - Record rules (
ir.rule) decide which records a user can see or change.
A model with no access rights is unusable for normal users, and Odoo logs a warning about it.
Groups and rules
<odoo>
<record id="group_asset_loan_user" model="res.groups">
<field name="name">Asset Loan / User</field>
<field name="implied_ids" eval="[(4, ref('base.group_user'))]"/>
</record>
<record id="group_asset_loan_manager" model="res.groups">
<field name="name">Asset Loan / Manager</field>
<field name="implied_ids" eval="[(4, ref('group_asset_loan_user'))]"/>
</record>
<record id="rule_asset_loan_own" model="ir.rule">
<field name="name">Asset loans: own records</field>
<field name="model_id" ref="model_asset_loan"/>
<field name="domain_force">[('user_id', '=', user.id)]</field>
<field name="groups" eval="[(4, ref('group_asset_loan_user'))]"/>
</record>
<record id="rule_asset_loan_all" model="ir.rule">
<field name="name">Asset loans: all records</field>
<field name="model_id" ref="model_asset_loan"/>
<field name="domain_force">[(1, '=', 1)]</field>
<field name="groups" eval="[(4, ref('group_asset_loan_manager'))]"/>
</record>
<record id="rule_asset_loan_company" model="ir.rule">
<field name="name">Asset loans: multi-company</field>
<field name="model_id" ref="model_asset_loan"/>
<field name="domain_force">[('company_id', 'in', company_ids)]</field>
</record>
</odoo>How these combine:
- Rules attached to groups are OR-ed together. A manager matches both the "own" and "all" rules, so they see everything.
- Rules with no group are global and are AND-ed with everything else. The company rule applies to every user, managers included.
Group definitions were reworked in Odoo 19.
The access CSV
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_asset_loan_user,asset.loan user,model_asset_loan,group_asset_loan_user,1,1,1,0
access_asset_loan_manager,asset.loan manager,model_asset_loan,group_asset_loan_manager,1,1,1,1Users can create and edit their own loans but not delete them. Managers can do everything.
If what you actually need is to hide menus, buttons or fields from certain users on an existing system rather than write new modules, our Access Management Pro app handles that from the UI, including read-only users and record rules.
Inheriting instead of copying
The fastest way to make an Odoo database un-upgradable is to copy a core module or a core view and edit the copy. On the next version, your copy is frozen in the past while the original moves on.
Instead, extend. In Python, use _inherit without a new _name:
from odoo import api, fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
asset_loan_ids = fields.One2many("asset.loan", "partner_id", string="Asset Loans")In XML, inherit the view and use xpath to place only your change:
<odoo>
<record id="res_partner_view_form_asset_loan" model="ir.ui.view">
<field name="name">res.partner.form.asset.loan</field>
<field name="model">res.partner</field>
<field name="inherit_id" ref="base.view_partner_form"/>
<field name="arch" type="xml">
<xpath expr="//notebook" position="inside">
<page name="asset_loans" string="Asset Loans"
groups="asset_loan.group_asset_loan_user">
<field name="asset_loan_ids"/>
</page>
</xpath>
</field>
</record>
</odoo>Rules for inheritance that survive upgrades:
- Anchor xpaths on
nameattributes or field names, not on positions like//group[2]. Layout changes between versions; field names change far less often. - Avoid
position="replace"on core elements. Useattributesto hide or change things, or add next to them. A replace removes the element for every other module that also inherits that view. - Override methods with
super(), and pass through arguments you do not use:
def action_post(self, *args, **kwargs):
res = super().action_post(*args, **kwargs)
# your extra logic here
return res- Never edit core source files, and avoid monkey-patching. Both are invisible to Odoo's module system and to anyone upgrading later.
Tests
Tests are what let you upgrade with confidence. Focus on your own logic: constraints, state changes and security rules.
from datetime import timedelta
from odoo import fields
from odoo.exceptions import ValidationError
from odoo.tests import TransactionCase, tagged
from odoo.tests.common import new_test_user
@tagged("post_install", "-at_install")
class TestAssetLoan(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.partner = cls.env["res.partner"].create({"name": "Test Borrower"})
groups = "asset_loan.group_asset_loan_user"
cls.user_a = new_test_user(cls.env, login="loan_a", groups=groups)
cls.user_b = new_test_user(cls.env, login="loan_b", groups=groups)
def _create_loan(self, env=None, **vals):
env = env or self.env
values = {"name": "Laptop", "partner_id": self.partner.id}
values.update(vals)
return env["asset.loan"].create(values)
def test_due_date_before_out_date_is_rejected(self):
today = fields.Date.today()
with self.assertRaises(ValidationError):
self._create_loan(date_out=today, date_due=today - timedelta(days=1))
def test_return_sets_state_and_date(self):
loan = self._create_loan()
loan.action_lend()
loan.action_return()
self.assertEqual(loan.state, "returned")
self.assertTrue(loan.date_returned)
def test_user_cannot_see_other_users_loans(self):
loan = self._create_loan(env=self.env(user=self.user_a))
visible = self.env["asset.loan"].with_user(self.user_b).search(
[("id", "=", loan.id)]
)
self.assertFalse(visible)Register the test file in tests/__init__.py with from . import test_asset_loan, then run against a throwaway database:
./odoo-bin -c odoo.conf -d test_asset_loan -i asset_loan --test-enable --stop-after-initOn later runs, update instead of install and filter to your module:
./odoo-bin -c odoo.conf -d test_asset_loan -u asset_loan --test-tags /asset_loan --stop-after-initThe security test is the one people skip, and it is the one that catches real leaks. Testing as a specific user with with_user exercises your access rights and record rules exactly as production will.
Keeping it easy to upgrade
Upgrades come in two kinds: changes to your own module, and moving to the next Odoo version. Plan for both.
Changing your own module
When you rename a field or change data structure, bump the version in the manifest and add a migration script in a folder named after the new version:
# migrations/17.0.1.1.0/pre-migrate.py
def migrate(cr, version):
if not version:
return # fresh install, nothing to migrate
cr.execute("ALTER TABLE asset_loan RENAME COLUMN borrower_id TO partner_id")pre-migrate.py runs before the module's models are updated, and post-migrate.py runs after. Without the rename above, Odoo would create a new empty column and the old data would be left behind.
For records that admins are expected to edit, such as default configuration, wrap them in <data noupdate="1"> so a module update does not overwrite their changes.
Moving to the next Odoo version
A module written the way shown above is mostly mechanical to port. The usual work is:
- Update the version prefix in the manifest (for example
17.0to18.0). - Apply the view syntax changes for that release, such as
<tree>to<list>andtree,formtolist,formwhen going to Odoo 18. - Check every inherited view: confirm each
xpathanchor still exists in the new core view. - Check every overridden method: confirm the signature and return value in core have not changed.
- Run the full test suite on a copy of the production database upgraded to the new version.
The modules that are hard to port are the ones with copied core code, positional xpaths, overrides that skip super(), and no tests. Avoiding those four is most of the job.
If you have a backlog of custom modules to move, our Upgrade Autopilot app moves custom Odoo apps to the next version and upgrades and tests them automatically. Review its output like any other pull request.
A short checklist
- One model per file, files named after the model they define or extend.
_descriptionon every model,company_idwhere multi-company is possible.- Access rights for every model, record rules for every row-level restriction.
- Extend with
_inheritandxpath, never copy core. - Anchor xpaths on names, avoid
replace, always callsuper(). - Tests for constraints, state changes and security.
- Version bumps with migration scripts for any data structure change.
How Kalvyai can help
We build and maintain custom Odoo modules, integrations and version upgrades, following the practices in this post. If you need a new module, a review of existing custom code, or a plan to move to the next Odoo version, see our Odoo services or browse our ready-made apps at store.kalvyai.com. To talk about your project, contact us.
- Odoo
- Odoo Development
- Custom Modules
- Odoo Security
- Testing
- Odoo Upgrade
Kalvyai Engineering · Engineering team
The engineers who build, connect and fix business systems at Kalvyai: Odoo, ERPNext, Shopify and AI agents that work inside them with approvals, budgets and an audit trail.



Comments
No comments yet. Questions and corrections are welcome.
Rate this post or leave a comment