Skip to main content
Version: Tryton 7.0 (LTS)

3. Models, fields, and relations

Tryton 7.0 · versioned practical course

Objectives

  • choose field types deliberately
  • model Many2One, One2Many, and Many2Many correctly
  • avoid duplicated business data

Mental model

Relations express ownership and lifecycle. A Many2One stores the foreign key; a One2Many is its reverse view; a Many2Many needs an explicit relation model.

Guided practice

  1. Make Author independent.
  2. Make each Book point to one Author.
  3. Expose books from Author through One2Many.
  4. Use a relation model only when both sides may have many records.
  5. Decide deletion behavior and requiredness from the business rule.

Minimal example

class Author(ModelSQL, ModelView):
"Author"
__name__ = 'library.author'
name = fields.Char("Name", required=True)
books = fields.One2Many('library.book', 'author', "Books")

class Book(ModelSQL, ModelView):
"Book"
__name__ = 'library.book'
title = fields.Char("Title", required=True)
author = fields.Many2One(
'library.author', "Author", required=True,
ondelete='RESTRICT')
price = fields.Numeric("Price", digits=(16, 2))
published_on = fields.Date("Published On")

How to read the example

Do not copy author_name into Book merely for display. Tryton can traverse relations, while duplicated values drift unless there is a documented historical reason.

Exercise

Add Genre and a Many2Many relation. Explain why the relation model needs two Many2One fields and a uniqueness constraint.

Run the exercise first with a minimal valid case, then add an invalid case and turn both into repeatable tests.

Verifiable result

Deleting an author referenced by a book is rejected, and a book can be reached from both sides of the relation.

Common mistakes

  • using Float for money
  • confusing One2Many with a stored list
  • using CASCADE without analyzing data loss
  • placing company-dependent data on a global master record

Ready-to-advance criteria

  • I can explain the concepts without looking at the code.
  • Valid and invalid cases have tests.
  • I tested with a non-administrative user.
  • I know how to upgrade and restore the training database.

Version and references

Series 7.0 requires at least Python 3.8 according to official metadata. This official branch still carries historical metadata in setup.py; preserve series compatibility while preparing custom packages for standard python -m build builds. Do not confuse this historical minimum with the Python version certified by your organization.

This edition pins examples and dependencies to series 7.0. Check the official 7.0 tutorial, server API, and source branch before moving a pattern to production.