Python 如何使用 Odoo 中的方法设置默认值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31583328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:15:44  来源:igfitidea点击:

How to set default values with methods in Odoo?

pythonpython-2.7odooodoo-8default-value

提问by Jay Venkat

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

如何计算 Odoo 8 models.py中对象字段中默认值的值

We can't use the _defaultattribute anymore in Odoo 8.

我们不能_default再在 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()
)

采纳答案by ChesuCR

You can use a lambda function like this:

您可以使用这样的 lambda 函数:

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

@api.model
def _get_default_name(self):
    return "test"

回答by Daniel Reis

A simpler version for the @ChesuCR answer:

@ChesuCR 答案的更简单版本:

def _get_default_name(self):
    return "test"

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