Odoo 优化代码以获得更好的性能和质量
我有这个计算方法,计算6个字段和总数。 它起作用了。 问题是我如何优化it性能和代码质量。 只是想得到一些关于如何编写更好代码的建议 定义日期(自): date=datetime.datetime.now().strftime(“%Y-%m-%d%H:%m:%S”) self.date=日期 self.drawer\u potential=self.drawer\u id.产品种类价格*self.drawer\u数量 self.flexible\u potential=self.flexible\u id.产品种类价格*self.flexible\u数量 self.runner\u潜在=self.runner\u id.product\u categu\u price*self.runner\u数量 self.group\u 1\u潜在=self.group\u 1\u id.product\u categu\u价格*self.group\u 1\u数量 self.group\u 2\u potential=self.group\u 2\u id.产品种类价格*self.group\u 2\u数量 self.group\u 3\u潜力=self.group\u 3\u id.产品\u类别\u价格*self.group\u 3\u数量 总计=[self.drawer\u潜力,self.flexible\u潜力,self.runner\u潜力,self.group\u 1\u潜力, self.group_2_潜力,self.group_3_潜力] self.total_potential=总和(总计)Odoo 优化代码以获得更好的性能和质量,odoo,odoo-9,Odoo,Odoo 9,我有这个计算方法,计算6个字段和总数。 它起作用了。 问题是我如何优化it性能和代码质量。 只是想得到一些关于如何编写更好代码的建议 定义日期(自): date=datetime.datetime.now().strftime(“%Y-%m-%d%H:%m:%S”) self.date=日期 self.drawer\u potential=self.drawer\u id.产品种类价格*self.drawer\u数量 self.flexible\u potential=self.flexible
我只看到两件事可以改进:
Datetime
类获取“now”,因为它已经考虑了Odoo的Datetime格式。最后,这更易于维护,因为如果Odoo决定在系统范围内更改整个格式,您也必须更改您的方法update()
,对于其他值更改,这显然是write()
def一旦更改日期(self):
自我更新({
“日期”:字段.Datetime.now(),
“抽屉潜力”:self.drawer\u id.product\u categu\u price*self.drawer\u数量,
“灵活潜力”:self.flexible\u id.product\u categ\u price*self.flexible\u quantity,
#等等
})
第一件事:您应该主要关注批处理操作的性能。您的案例是onchange方法,这意味着:
- 它将由用户交互手动触发
- 它一次只影响一条记录
- 它不会执行数据库写入
def _ocnhange_date(self):
# Use this alternative method, easier to maintain
self.date = fields.Datetime.now()
# Less code here, although almost equal
# performance (possibly less)
total = 0
for field in ("drawer", "flexible", "runner",
"group_1", "group_2", "group_3"):
potential = self["%s_id"].product_categ_price * self["%s_qty"]
total += potential
self["%s_potential"] = potential
# We use a generator instead of a list
self.total_potential = total
您使用的是哪个版本的odoo?我使用的是odoo 9。虽然您所说的可维护性是正确的,但在较低的级别,您的代码将执行完全相同的性能。使用write时有区别,但使用update(onchange确实需要)时是一样的。是的,我知道,update不像write那样工作。但现在他必须考虑一下。