'how can I create a computed fields that is depending on another model

I have two models reservation(inherit from sale.order) and places . I want to make a one2many field in the places model so when a reservation(sale.order) is confirmed, the new customer who reserved the place is added to this field here is my code

model reservation

from odoo import fields, models,api,_
from odoo.exceptions import Validation-error
class Customers2(models.Model):
    _inherit='sale.order'

client=fields.Many2one('res.partner',string='client')
secure_place=fields.Many2one(comodel_name='product.template',string='Secure place')
guests=fields.Integer(string='guests')
hotel_reser=fields.Many2one('product.template')
start_date=fields.Datetime(string='start date')
end_date=fields.Datetime(string='end date')
reserv_price=fields.Monetary(string='Price')
currency_id = fields.Many2one(comodel_name='res.currency',string='Currency')
reserv_status = fields.Selection(
    [('C', 'Confirmed'), ('D', 'Draft')],
    string='Reservation type')

model places

    from odoo import fields , models,api

class Place(models.Model):
    _inherit='product.template'


    hotel=fields.Selection([('H', 'Habit'),('Y','Yasmine'),('M','movenpick')],string='Hotel')
    type_of_room=fields.Selection([('S', 'spa'),('M','meeting room'),('N','Nightclub')],string='Room')
    reserv_persons=fields.One2many('sale.order','hotel_reser',string='clients reserved',compute='_compute_reservations')


Solution 1:[1]

To add the new customer who reserved the place in the reserv_persons field, the related model should be res.partner and its type many2many.

You want to use a computed field (the value is computed when needed), so you can search for sale orders in the sale state to show all customers who reserved the place

Example:

from odoo import api, fields, models, _, Command


class Place(models.Model):
    _inherit = 'product.template'

    reserv_persons = fields.Many2many('res.partner', string='clients reserved', compute='_compute_reservations')

    def _compute_reservations(self):
        sale_order = self.env['sale.order']
        for tmpl in self:
            tmpl.reserv_persons = [Command.link(so.client.id) for so in sale_order.search(
                [('secure_place', '=', tmpl.id), ('state', '=', 'sale')])]

The Command used above is a special command to manipulate the relation of One2many and Many2many

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kenly