Reader small image

You're reading from  Odoo 15 Development Essentials - Fifth Edition

Product typeBook
Published inFeb 2022
Reading LevelBeginner
PublisherPackt
ISBN-139781800200067
Edition5th Edition
Languages
Tools
Right arrow
Author (1)
Daniel Reis
Daniel Reis
author image
Daniel Reis

Daniel Reis has a degree in applied mathematics and an MBA. He has had a long career in the IT industry, mostly as a consultant implementing business applications in a variety of sectors. He has been working with Odoo (OpenERP at the time) since 2010 and is an active contributor to the Odoo Community Association (OCA), where he also serves as a board member. He is the managing director of Open Source Integrators, a leading open source and Odoo consultancy firm.
Read more about Daniel Reis

Right arrow

Chapter 6: Models – Structuring the Application Data

In this chapter, we will learn more about the model layer and how to use models to design the data structures that support applications. We will explore the available model types, when each should be used, and how to define constraints that enforce data validations.

Models are composed of data fields that support several data types, and some field types support defining relationships between models. More advanced usage of fields involves having values automatically computed using specific business logic.

The following topics will be covered in this chapter:

  • Learning project – improving the Library app
  • Creating models
  • Creating fields
  • Relationships between models
  • Computed fields
  • Model constraints
  • Overview of the Odoo base models

Throughout these topics, you will learn how to create non-trivial data structures for your Odoo projects. By the end of this chapter, you should have...

Technical requirements

This chapter is based on the code we created in Chapter 3, Your First Odoo Application. This code can be found in the ch06/ directory of this book's GitHub repository at https://github.com/PacktPublishing/Odoo-15-Development-Essentials.

You should have it in your add-ons path. Make sure that you install the library_app module.

Learning project – improving the Library app

In Chapter 3, Your First Odoo Application, we created the library_app add-on module and implemented the simple library.book model to represent a book catalog. In this chapter, we will revisit that module to enrich the data that we can store for each book.

We will add a category hierarchy to use for book categorization with the following structure:

  • Name: The category title
  • Parent: The parent category that it belongs to
  • Subcategories: The categories that have this one as the parent
  • Featured book or author: A selected book or author that represents this category

A few more fields will be added to showcase the different data types available for Odoo fields. We will also use model constraints to implement a few validations on the Books model:

  • The title and publication date should be unique.
  • ISBNs entered should be valid.

We will start by revisiting Odoo models, now in more depth, to learn...

Creating models

Models are at the heart of the Odoo framework. They describe the application data structures and are the bridge between the application server and the database storage. Business logic can be implemented around models to provide application features, and user interfaces are created on top of them to provide the user experience.

In the following subsections, we will learn about the model's generic attributes, which are used to influence their behavior, and the several types we have available – regular models, transient models, and abstract models.

Model attributes

Model classes can use additional attributes to control some behaviors. These are the most commonly used attributes:

  • _name: This is the internal identifier for the Odoo model we are creating. This is mandatory when creating a new model.
  • _description: This is a user-friendly title that can be used to refer to a single Model record, such as Book. This is optional but recommended...

Creating fields

Having created a new model, the next step is to add fields to it. Odoo supports all the basic data types that are expected, such as text strings, integers, floating-point numbers, Booleans, dates and time, and image or binary data.

Let's explore the several types of fields available in Odoo.

Basic field types

We will go back to the book model to present the several available field types.

In the library_app/models/library_book.py file, edit the Book class, replacing the current field definitions with this one:

class Book(models.Model):
    _name = "library.book"
    _description = "Book"
    # String fields:
    name = fields.Char("Title")
    isbn = fields.Char("ISBN")
    book_type = fields.Selection(
        [("paper","Paperback"...

Relationships between models

Non-trivial business applications need to use relationships between the different entities involved. To do this, we need to use relational fields.

Looking at the Library app, the Book model has the following relationships:

  • Each book can have one publisher, and each publisher can have many books. From the book's point of view, this is a many-to-one relationship. It is implemented in the database as an integer field, holding the ID of the related publisher record, and a database foreign key in it, enforcing referential integrity.
  • The reverse of this, from the publisher's point of view, is a one-to-many relation, meaning that each publisher can have many books. While this is also a field type in Odoo, its database representation relies on the many-to-one relationship. We know the books related to a publisher running a query on books, filtered by the publisher ID.
  • Each book can have many authors, and each author can have many books...

Computed fields

Fields can have their values automatically calculated by a function, instead of simply reading a database stored value. A computed field is declared just like a regular field but has the additional compute argument to define the function that's used for the computation.

Computed fields involve writing some business logic. So, to take full advantage of this feature, we should be comfortable with the topics that will be explained in Chapter 8, Business Logic – Supporting Business Processes. Computed fields will still be explained here, but we will keep the business logic as simple as possible.

As an example, we will add a computed field to the Books model, displaying the publisher's country. This will allow the country to be displayed in the form view.

The code that's needed to find the value is simple: if book represents a book record, we can use object dot notation to get the publisher's country using book.publisher_id.country_id...

Model constraints

Often, applications need to ensure data integrity and enforce validations to ensure that the data is complete and correct.

The PostgreSQL database manager supports many useful validations, such as avoiding duplicates or checking that values meet certain simple conditions. Odoo models can use the PostgreSQL constraints capabilities for this.

Some checks require more sophisticated logic and are better implemented as Python code. For these cases, we can use specific model methods that implement that Python constraint logic.

Let's learn more about these two possibilities.

SQL model constraints

SQL constraints are added to the database table definition and are enforced directly by PostgreSQL. They are declared using the _sql_constraints class attribute.

It is a list of tuples, and each tuple has a format of (name, sql, message):

  • name is the constraint identifier name.
  • sql is the PostgreSQL syntax for the constraint.
  • message is the...

Overview of the Odoo base models

In the previous chapters, we had the chance to create new models, such as the Book model, but we also made use of the already existing models, such as the Partner model, provided by the Odoo base module. In this section, we will provide a short introduction to these built-in models.

The Odoo core framework includes the base add-on module. It provides the essential features needed for Odoo apps to work. It can be found in the Odoo repository, in the./odoo/addons/base subdirectory.

The standard add-on modules, which provide the official apps and features made available with Odoo, depend on and build on top of the base module. The standard add-ons can be found in the Odoo repository, in the ./addons subdirectory.

The base module provides two kinds of models:

  • Information repository, ir.*, models
  • Resources, res.*, models

The information repository models are used to store basic data needed for the Odoo framework, such as Menus...

Summary

In this chapter, we learned about the different model types, such as transient and abstract models, and why these are useful for user interface wizards and mixins, respectively. Other relevant model features include Python and SQL constraints, which can be used to prevent data entry errors.

We also learned about the available field types, as well as all the attributes they support, to be able to represent the business data in the most accurate way possible. We also learned about relationships fields, and how to use them to create relationships between the different entities that are used by our applications.

After that, we saw that models are usually based on the models.Model class, but that we can also use models.Abstract for reusable mixin models and models.Transient for wizards or advanced user interaction dialogs. We saw the general model attributes that are available, such as _order for default sort order and _rec_name for the default field to use for record representation...

Further reading

The official documentation for models can be found at https://www.odoo.com/documentation/15.0/developer/reference/backend/orm.html.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Odoo 15 Development Essentials - Fifth Edition
Published in: Feb 2022Publisher: PacktISBN-13: 9781800200067
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Daniel Reis

Daniel Reis has a degree in applied mathematics and an MBA. He has had a long career in the IT industry, mostly as a consultant implementing business applications in a variety of sectors. He has been working with Odoo (OpenERP at the time) since 2010 and is an active contributor to the Odoo Community Association (OCA), where he also serves as a board member. He is the managing director of Open Source Integrators, a leading open source and Odoo consultancy firm.
Read more about Daniel Reis