Search code examples
pythonodooodoo-12

Odoo python models - how to access related models


I am trying to understand Odoo's models - I know Django quite well but am having trouble understanding Odoo, mainly because the documentation is generally so awful.

Suppose I have some models like this:

class Publisher(models.model):
    name = fields.Char('Name',help='Publisher name')
    ...

class Book(model.model):
    publisher = fields.Many2one('whatever.publisher',string='Publisher')

Now suppose I have a Book object "mybook". How do I get the Publisher object? Is it just mybook.publisher?

Also in Django I could define a reverse relationship (using "related_name") so that publisher.books.all() would give me all the reverse relationships, ie all the books for the publisher. What is the equivalent in Odoo? Or in Odoo is it the case that I must explicitly declare a One2many relationship from Publisher to Book in addition to the Many2one from Book to Publisher?

In Odoo it also looks like you can define a One2many relationship:

class Publisher(models.model):
    published_books = fields.One2many('whatever.book','author',string='Published books')

So if I have a publisher object 'publisher' then how do I get a list of the publisher's published books? Is it just publisher.published_books?

Finally we have fields.Many2many

class Store(models.model):
    book_ids = fields.Many2many('whatever.book',string='Books')

In this case, a Store sells many books and a Book can be in many stores.

So how do I get the books in a store? How do I get all the stores for a given book?

Also, if I want book.stores as well as store.books, does this mean I have to declare a fields.Many2many relationship in both Book and Store models?

I'm pretty shocked this is so hard to find in the Odoo documentation.


Solution

  • Yes, you have to add Many2many fields on both model:

    class Store(models.model):
        book_ids = fields.Many2many(comodel_name='whatever.book',string='Books', column1='book_id', column2='store_id')
    
    class Book(models.model):
        store_ids = fields.Many2many(comodel_name='whatever.store',string='Stores', column2='book_id', column1='store_id')
    

    For a particular store record, you can get all the books using:

    store.book_ids
    

    For a particular book record, you can get all the stores using:

    book.store_ids