Skip to Content
Menu
This question has been flagged
3 Replies
10688 Views

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
Discard
Best Answer

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

Avatar
Discard
Author Best Answer

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
Discard
Best Answer

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
Discard
Related Posts Replies Views Activity
0
Dec 22
928
2
Aug 20
1970
3
Jun 24
3347
0
Oct 23
532
1
Jun 23
2288