官术网_书友最值得收藏!

  • Odoo Development Cookbook
  • Holger Brunn Alexandre Fayolle Daniel Reis
  • 291字
  • 2021-07-16 11:00:33

Adding a monetary field to a Model

Odoo has special support for monetary values related to a currency. Let's see how to use it in a Model.

Note

The Monetary field was introduced in Odoo 9.0 and is not available in previous versions. If you are using Odoo 8.0, the float field type is your best alternative.

Getting ready

We will reuse the my_module addon module from Chapter 3, Creating Odoo Modules.

How to do it…

The monetary field needs a complementary currency field to store the currency for the amounts.

The my_module already has a models/library_book.py defining a basic Model. We will edit this to add the needed fields:

  1. Add the field to store the currency that is to be used:
    class LibraryBook(models.Model):
        # ...
     currency_id = fields.Many2one(
     'res.currency', string='Currency')
    
  2. Add the monetary field to store our amount:
    class LibraryBook(models.Model):
        # ...
     retail_price = fields.Monetary(
     'Retail Price',
     # optional: currency_field='currency_id',
     )
    

Now, upgrade the addon module, and the new fields should be available in the Model. They won't be visible in views until they are added to them, but we can confirm their addition by inspecting the Model fields in Settings | Technical | Database Structure | Models.

How it works…

Monetary fields are similar to Float fields, but Odoo is able to represent them correctly in the user interface since it knows what their currency is through a second field for that purpose.

This currency field is expected to be named currency_id, but we can use whatever field name we like as long as it is indicated using the currency_field optional parameter. You might like to know that the decimal precision for the amount is taken from the currency definition (the decimal_precision field of the res.currency model).

主站蜘蛛池模板: 德江县| 诏安县| 沙河市| 临沂市| 陇南市| 崇礼县| 桓仁| 涞源县| 永年县| 澄城县| 卢氏县| 正蓝旗| 同心县| 北海市| 农安县| 楚雄市| 平顶山市| 灌南县| 许昌县| 昌江| 玉树县| 兖州市| 浑源县| 潼南县| 和林格尔县| 龙州县| 宣威市| 达日县| 德惠市| 南京市| 库尔勒市| 磴口县| 昌邑市| 西吉县| 盐源县| 玛沁县| 通渭县| 天等县| 敦化市| 萝北县| 龙井市|