10

How to compute the value for default value in object fields in Odoo 8 models.py

We can't use the _default attribute anymore in Odoo 8.

field_name = fields.datatype(
    string=’value’, 
    default=compute_default_value
)

In the above field declaration, I want to call a method to assign default value for that field. For example:

name = fields.Char(
    string='Name', 
    default= _get_name()
)
ChesuCR
  • 9,352
  • 5
  • 51
  • 114
Jay Venkat
  • 397
  • 2
  • 5
  • 18

2 Answers2

23

You can use a lambda function like this:

name = fields.Char(
    string='Name',
    default=lambda self: self._get_default_name(),
)

@api.model
def _get_default_name(self):
    return "test"
ChesuCR
  • 9,352
  • 5
  • 51
  • 114
  • It work but it can be done in a simpler way. See my answer. – Daniel Reis Jul 23 '15 at 12:15
  • 4
    Yes, but if you want to follow the [OCA guidelines](https://github.com/OCA/maintainer-tools/blob/master/CONTRIBUTING.md#field) and follow de conventions you can check that the "Fields declarations" are always above the "Default methods". If you declare the function as you wrote in your post you can't do it like that – ChesuCR Jul 23 '15 at 12:34
  • They have changed the order as you can see. [Order 1](https://github.com/OCA/maintainer-tools/blob/repos_with_ids-website/CONTRIBUTING.md), [Order 2](https://github.com/OCA/maintainer-tools/blob/master/CONTRIBUTING.md#field). But I am still thinking that to write all the methods after the fields definitions is a better organization – ChesuCR May 13 '17 at 09:56
  • good solution ... if i want to change default value based on another field value – omar ahmed Jul 14 '20 at 09:24
  • @omarahmed you can use `@api.onchange('other_field')`, the `other_field` must be added to the form – ChesuCR Jul 15 '20 at 14:57
15

A simpler version for the @ChesuCR answer:

def _get_default_name(self):
    return "test"

name = fields.Char(
    string='Name',
    default=_get_default_name,
)
Daniel Reis
  • 12,944
  • 6
  • 43
  • 71