Odoo 11 Development Essentials(Third Edition)
上QQ阅读APP看书,第一时间看更新

Creating a Custom Model

We now have a Library top menu with a menu item for Book Authors. It's time to add a Books menu item to hold the records for books.

Let's visit again, in Settings, the Technical | Database Structure | Models menu, and click on Create. Fill in the Model form with these values:

  • Model Description: Book
  • Model: x_library_book

We should save it before we can properly add new fields to it. So click on Save and then Edit it again. You can see that a few fields were automatically added. The ORM includes them in all Models, and they can be useful for audit purposes.

The x_name (or name) field is a title representing the record in lists or when it is referenced in other records. For us, it makes sense to use it for the book title. You may edit it and change the Field Label to a more meaningful Title.

We also add a field for the book authors. A book can have many authors, and any author can have many books. So this is a many-to-many relationship.

On the Fields list, click on Add an item to create a new field with these values:

  • Field Name: x_author_ids
  • Field Label: Authors
  • Field Type: many2many
  • Object Relation: res.partner
  • Domain: [('x_is_book_author', '=', True)]

The many-to-many field has a few specific definitions: the Relation Table, Column1, and Columns2 fields. These are automatically filled out for you and the defaults are good for most cases, so we don't need to worry about them now. These will be discussed in more detail in Chapter 4Models – Structuring the Application Data.

The Domain attribute is optional, but we used it so that only book authors are selectable from the list. Otherwise, all Partners would be available for selection.

We now need to make this Model available in the user interface. If we create a menu item for a new model, it can be used right away, since Odoo will automatically generate default views for it.

In Settings, navigate to Technical | User Interface | Menu Items and create a new record with the following values:

  • Menu: Books
  • Parent Menu: Library
  • Action: Select ir.actions.act_window, and in the selection list on the right, click on Create and Edit to open a form for the creation of the related Window Action:
    • Action name: Books (will be the title used for the presented views)
    • Object: x_library_book (the technical name of the target Model)

Save the Action and Menu Item, and once we reload the web client the Library top menu app will show the Books option alongside the Book Authors option.

Try it and you will see the basic, but functional, automatically generated views. We will want to create our own views, so that's what we will be working on in the next section.