Search code examples
pythonodooodoo-10

How can i get attributes from a Many2One relationship on odoo?


I'm doing some school project and i want to get the attrs from a class with a Many2One relationship, more specific i want to get the preu_lloguer from my another class in the class Factura.

Here the class where i want to get the value from the another and place on "preu":

class Factura(models.Model):
    _name = 'carplus.factura'

    client_id = fields.Many2one("carplus.client", string="Client", required=True)
    vehicle_id = fields.Many2one("carplus.cotxe", string="Vehicle", required=True)
    renting_id = fields.Many2one("carplus.rentinglloguer", string="Contracte", required=True)
    preu = fields.Float(string="Preu")
    data_factura = fields.Date(string="Data de factura", required=True)

And here the class where is the attr that i need:

class Cotxe(models.Model):
    _name = 'carplus.cotxe'

    marca_id = fields.Many2one("carplus.cotxemarca", string="Marca", required=True)
    model = fields.Char(string="Model", required=True)
    color = fields.Char(string="Color")
    name = fields.Char(string="Matricula", required=True)
    data_compra = fields.Date(string="Data de compra", required=True)
    places = fields.Integer(string="Número de plaçes", required=True)
    tipus_id = fields.Many2one("carplus.cotxetipus", string="Tipus", required=True)
    combustible_id = fields.Many2one("carplus.cotxecombustible", string="Combustible", required=True)
    preu_lloguer = fields.Float(string="Preu lloguer", required=True)
    preu_renting = fields.Float(string="Preu renting", required=True)

PD: sorry about bad english


Solution

  • this really depends on how you want the information to be looked at. Is the related field supposed to be a field on the current model? if so use a related field.

    preu = fields.Float(related='vehicle_id.preu_lloguer')
    

    if you just need to reference the attribute in a method use the following

    vehicle_id.preu_lloguer
    

    If you need to determine which of the different prices to grab. You will need to use a computed field.

    preu = fields.Float(compute='_compute_price')
    
    def _compute_price(self):
        ...
        set code here
        ...
    

    This should get you through any situation.