优化代码以获得更好的性能和质量

Optimizing code for better performance and quality

我有这个计算方法,计算6个字段和总数。 有用。 问题是如何在性能和代码质量方面优化它。 只是想获得一些关于如何编写更好代码的建议。

def _ocnhange_date(self):
    date = datetime.datetime.now().strftime ("%Y-%m-%d %H:%M:%S")
    self.date = date
    self.drawer_potential = self.drawer_id.product_categ_price * self.drawer_qty
    self.flexible_potential = self.flexible_id.product_categ_price * self.flexible_qty
    self.runner_potential = self.runner_id.product_categ_price * self.runner_qty
    self.group_1_potential = self.group_1_id.product_categ_price * self.group_1_qty
    self.group_2_potential = self.group_2_id.product_categ_price * self.group_2_qty
    self.group_3_potential = self.group_3_id.product_categ_price * self.group_3_qty
    total = [self.drawer_potential,self.flexible_potential,self.runner_potential,self.group_1_potential,
             self.group_2_potential,self.group_3_potential]
    self.total_potentail = sum(total)

我只看到两件事你可以在这里改进:

  1. 使用 Odoo 的 Datetime class 得到 "now" 因为它已经考虑了 Odoo 的日期时间格式。最后这更易于维护,因为如果 Odoo 决定在整个系统范围内更改整个格式,您也必须更改您的方法。

  2. 尽量避免如此多的赋值,而是使用允许合并更新某些值的方法。对于 onchange 方法,这将是 update() 而对于其他值更改,它显然是 write().

def _onchange_date(self):
    self.update({
        'date': fields.Datetime.now(),
        'drawer_potential': self.drawer_id.product_categ_price * self.drawer_qty,
        'flexible_potential': self.flexible_id.product_categ_price * self.flexible_qty,
        # and so on
    })

首先要注意的是:您应该主要担心批处理操作的性能。你的情况是一个 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