Ir al contenido
Menú
Se marcó esta pregunta
3 Respuestas
12276 Vistas

Odoo 11 Community Edition.

I am trying to read the rate of currency from object as obj.currency_id.rate

Its returning only the old rate. How do I fetch the latest rate? 

How do I fetch a rate by a certain date?

Thanks.

Avatar
Descartar
Mejor respuesta

rate_usd = self.env['res.currency'].search([('name', '=', 'USD')], limit=1).rate

Avatar
Descartar
Autor Mejor respuesta

I got the rate on a particular date as:

currency_id.with_context(date=purchase_order.date_order)

Referred: https://stackoverflow.com/a/44983955

However, if on a certain date, the rate is not defined, it will take the rate as 1. Is it possible to make it take the next nearest dates rate? How do we do that.

Thanks.    

Avatar
Descartar
Mejor respuesta

You analyse the file /addons/base/res/res_currency.py

The field rate is defined as:

    rate = fields.Float(compute='_compute_current_rate', string='Current Rate', digits=(12, 6),
                        help='The rate of the currency to the currency of rate 1.')

and computed by method (bellow), which depends on 'rate_ids.rate':

    @api.multi
    @api.depends('rate_ids.rate')
    def _compute_current_rate(self):
        date = self._context.get('date') or fields.Date.today()
        company_id = self._context.get('company_id') or self.env['res.users']._get_company().id
        # the subquery selects the last rate before 'date' for the given currency/company
        query = """SELECT c.id, (SELECT r.rate FROM res_currency_rate r
                                  WHERE r.currency_id = c.id AND r.name <= %s
                                    AND (r.company_id IS NULL OR r.company_id = %s)
                               ORDER BY r.company_id, r.name DESC
                                  LIMIT 1) AS rate
                   FROM res_currency c
                   WHERE c.id IN %s"""
        self._cr.execute(query, (date, company_id, tuple(self.ids)))
        currency_rates = dict(self._cr.fetchall())
        for currency in self:
            currency.rate = currency_rates.get(currency.id) or 1.0

Conclusion, if rate_ids are defined correctly, method should return the last rate.

You find in file, additionaly this code (used to calculate the date of currency) :

    @api.multi
    @api.depends('rate_ids.name')
    def _compute_date(self):
        for currency in self:
            currency.date = currency.rate_ids[:1].name

Conclusion: rate_ids.name may be used to search rate on a specified date (if exist)

Avatar
Descartar
Publicaciones relacionadas Respuestas Vistas Actividad
0
dic 22
1791
2
ago 20
3195
0
abr 25
654
3
jun 24
5448
0
oct 23
1478