从 odoo 中的只读字段中保存值



我在表单字段上有 3 个字段,总和是只读的。单击"从只读字段保存数据不存储在数据库中"后。

例:

class myClass(models.Model):
number_1 = fields.Integer(store=True,default=0)
number_2 = fields.Integer(store=True,default=0)
sum = fields.Integer(store=True)
@api.onchange('number_1','number_2')
def compute_sum(self):
total = self.number_1 + self.number_2
self.sum = total

在这种情况下,我更喜欢计算字段。公式更改不会保存只读字段(例如,在更改事件上(。在 Odoo 11 中,引入了一个新选项force_save视图中的这种行为,但以前的版本没有此选项(除了社区模块,例如 OCA web_readonly_bypass(。

计算字段的解决方案:

class myClass(models.Model):
number_1 = fields.Integer()
number_2 = fields.Integer()
sum = fields.Integer(compute="compute_sum", store=True)
@api.depends('number_1','number_2')
@api.multi
def compute_sum(self):
for record in self:
total = record.number_1 + record.number_2
record.sum = total

无需更改视图定义。并且在正常Integer字段中也不需要store参数。默认值0已经是Integer的默认值,因此需要定义它。

您不必在视图中显式定义readonlysum因为默认情况下,没有反向导法的计算字段是只读的。

我希望下面的代码能帮助你

在我的情况下,总年份字段是只读的,并且基于"出生日期"总年份将更新

使用 onchange 方法,可以在字段中获取总年份,但在保存该记录时 总年份 字段设置为空白

溶液:-

创建总年份的新虚拟字段,并在原始字段上设置该虚拟字段值

例:-

蟒蛇文件

total_year = 字段。浮点((

total_year_copy = 字段。浮点((

从日期时间导入日期

换法

@api.onchange('dob'( 定义onchange_dob(个体经营(: 今天 = date.today(( self.total_year = self.total_year_copy = 今天.年 - dob.year - ((今天.月,今天.日( <(dob.month, dob.day((

创建方法

@api.型号

def create(self, vals(:

如果 vals 中的"total_year_copy":

vals.update({'total_year': vals.get('total_year_copy'(}(

return super(Project, self(.create(vals(

写入方法

@api.多

def write(self, vals(:

如果 vals 中的"total_year_copy":

vals.update({'total_year': vals.get('total_year_copy'(}(

return super(Project, self(.write(vals(

XML 文件

字段名称="total_year" 只读="1">

字段名称="total_year_copy" 不可见="1">

希望这可以帮助您保存只读记录

此致敬意

安吉特·甘地

from openerp import models, fields, api,exceptions
class your_model(models.Model):
_inherit = 'your.model'
field_1 =fields.Many2one('model.a', required="True", string="Field 1")
field_2 = fields.Integer(string = 'Field 2')
# onchange of field_1 we are populating value in field_2
@api.onchange('field_1')
def _onchange_field_1(self):
if field_1:
# your logic goes here to get value for field_2
self.field_2 = some_value
# As we know that when we get the value on onchange method, 
# the desired field convert into readonly mode and its value does not save into the database
# to save the value into the database we are going to override create and write method and in that method we explicitly save the value
@api.model
def create(self,vals):
if self.field_2:
vals['field_2']=self.field_1
res = super(your_model, self).create(vals)
return res
@api.multi
def write(self,vals):
if not self.field_2:
vals['field_2'] = self.field_1
res = super(your_model, self).write(vals)
return res

参考:在数据库中保存只读字段值

最新更新