Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 39 ยท Models and ORM

Defining Models and Fields

Define Odoo models: Model, TransientModel and AbstractModel, class attributes, scalar field types, field options, selections and magic fields.

The model is the heart of Odoo development. A model is a Python class that describes one kind of business object: what data it stores (its fields) and what it can do (its methods). From that single description Odoo creates a table, a data access layer, access to the web client and the external API. In this lesson you learn how to define models and the scalar field types; the next lessons cover relations, recordsets, searching and computed fields.

Odoo model code is shown read-only because it needs the Odoo server. Each lesson in this chapter adds Python stand-ins that reproduce the mechanism (here: a field system with defaults and validation). They are labelled and are not the real ORM.

Three kinds of models

All models inherit from a class in odoo.models:

  • models.Model: persistent. Has a table, records survive restarts. Used for almost everything.
  • models.TransientModel: temporary records for wizards (dialogs). The table exists but a scheduled job deletes old rows automatically.
  • models.AbstractModel: no table at all. Used as a mixin that other models inherit to share fields and methods (mail.thread is an abstract model).

Class attributes

Python
from odoo import fields, models


class LibraryBook(models.Model):
    _name = "library.book"
    _description = "Library Book"
    _order = "name"
    _rec_name = "name"

    name = fields.Char(required=True, index=True)
    isbn = fields.Char(string="ISBN", copy=False, size=13)
    pages = fields.Integer(default=1, help="Number of pages")
    price = fields.Float(digits=(8, 2))
    published = fields.Date()
    description = fields.Html()
    cover = fields.Binary()
    state = fields.Selection(
        [("draft", "Draft"), ("available", "Available"), ("lost", "Lost")],
        default="draft",
        required=True,
    )
    active = fields.Boolean(default=True)

    _sql_constraints = [
        ("isbn_unique", "unique(isbn)", "The ISBN must be unique."),
    ]

The underscore-prefixed attributes configure the model:

Attribute Purpose
_name Technical name; required for a new model
_description Human label (required to avoid a warning)
_order Default sorting, SQL-like: "name asc, id desc"
_rec_name Field used as the record's display name (default: name)
_table Override the table name (rare)
_sql_constraints Database-level constraints (unique, check). Recent series offer models.Constraint for the same job
_inherit Extend or copy another model (see the inheritance lesson)

Scalar field types

Field Stored as Notes
Char varchar size, translate=True for translated text
Text text Multi-line, no formatting
Html text Rich text; sanitised by default
Integer integer
Float numeric digits=(total, decimals)
Monetary numeric Needs a currency_field
Boolean boolean
Date, Datetime date, timestamp Stored in UTC; the client shows the user's time zone
Selection varchar List of (value, label) pairs
Binary file on disk attachment=True by default: stored in the filestore
Image like Binary Resizes automatically with max_width and max_height

Field options you will use daily

  • string: the label. If omitted, Odoo builds one from the attribute name (pages becomes "Pages").
  • required=True: NOT NULL in the database and enforced in forms.
  • default: a value or a function (lambda self: fields.Date.today()); a callable is evaluated for every new record.
  • readonly, copy=False (do not copy when duplicating a record), index=True, help, groups="base.group_system" (only these groups see the field), tracking=True (log changes in the chatter, needs mail.thread), translate=True for translatable strings.

Magic fields

Every model gets these without you declaring them:

  • id, the primary key.
  • create_date, create_uid, write_date, write_uid: audit information.
  • display_name, computed from _rec_name, shown in many-to-one drop-downs and breadcrumbs.

The special field active hides archived records from default searches, and sequence (an Integer by convention) together with the handle widget gives a drag-and-drop order in lists.

Selection fields

A Selection stores the technical value and shows the label:

Python
state = fields.Selection(
    [("draft", "Draft"), ("available", "Available")],
    string="Status",
    default="draft",
)

Use short, lowercase technical values; labels can be translated. To let other modules add options use selection_add in an inherited model:

Python
state = fields.Selection(selection_add=[("reserved", "Reserved")], ondelete={"reserved": "set default"})

A runnable stand-in: fields as descriptors

Odoo fields are Python descriptors: objects defined on the class that control how attributes are read and written on instances. This stand-in builds a very small version with required, default and type checking, so you can see why book.pages = "ten" can be rejected.

Python Stand-in: a tiny field system

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A second stand-in: a Selection with labels

The selection stores a short value but displays a label. The stand-in below keeps both and rejects values that are not in the list, like the ORM does on write.

Python Stand-in: Selection values and labels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which model class would you use for a wizard dialog whose data does not need to be kept?

    Transient models store temporary records that Odoo cleans up automatically.
  2. 2. What is an AbstractModel used for?

    Abstract models have no table; other models inherit them to reuse fields and methods, for example mail.thread.
  3. 3. What does copy=False on a field do?

    It is useful for unique values such as references and ISBNs.
  4. 4. Which are magic fields created for every model?

    The audit fields and id exist automatically. active, sequence and company_id are conventions you must declare.

Summary

  • Models are Python classes: Model (persistent), TransientModel (wizards), AbstractModel (mixins).
  • Class attributes such as _name, _description, _order and _sql_constraints configure the model.
  • Scalar fields: Char, Text, Html, Integer, Float, Monetary, Boolean, Date, Datetime, Selection, Binary, Image.
  • Options like required, default, copy, index, groups and tracking shape behaviour.
  • Fields are descriptors; Odoo adds magic fields such as id and create_date.

Next: Relational Fields