- Odoo 11 Development Cookbook(Second Edition)
- Holger Brunn Alexandre Fayolle
- 470字
- 2021-06-25 22:48:49
How it works...
Many-to-one fields add a column to the database table of the model, storing the database ID of the related record. At the database level, a foreign key constraint will also be created for it, ensuring that the stored IDs are a valid reference to a record in the related table. No database index is created for these relation fields, but this should often be considered; it can be done by adding the index=True attribute.
We can see that there are four more attributes we can use for many-to-one fields. The ondelete attribute determines what happens when the related record is deleted. For example, what happens to Books when their publisher record is deleted? The default is 'set null', setting an empty value on the field. It can also be 'restrict', which prevents the related record from being deleted, or 'cascade', which causes the linked record to also be deleted.
The last two (context and domain) are also valid for the other relational fields. They are mostly meaningful on the client side, and at the model level, act just as default values to be used in the client-side views:
- context adds variables to the client context when clicking through the field to the related record's view. We can, for example, use it to set default values for new records created through that view.
- domain is a search filter used to limit the list of related records available.
Both context and domain are explained in more detail in Chapter 10, Backend Views.
One-to-many fields are the reverse of many-to-one relations, and although they are added to models just like other fields, they have no actual representation in the database. Instead, they are programmatic shortcuts and enable views to represent these lists of related records.
Many-to-many relations also don't add columns in the tables for the models. This type of relation is represented in the database using an intermediate relation table, with two columns to store the two related IDs. Adding a new relation between a Book and an Author creates a new record in the relation table with the ID for the Book and the ID for the Author.
Odoo automatically handles the creation of this relation table. The relation table name is, by default, built using the name of the two related models, alphabetically sorted, plus a _rel suffix. However, we can override it using the relation attribute.
A case to keep in mind is when the two table names are large enough for the automatically generated database identifiers to exceed the PostgreSQL limit of 63 characters. As a rule of thumb, if the names of the two related tables exceed 23 characters, you should use the relation attribute to set a shorter name. In the next section, we will go into more detail on this.