我正在做一个Odoo 11项目,不幸的是,我们不能迁移到Odoo 12。
阅读Odoo 12 Development Cookbook - Third Edition这本书时,我发现了一种方法,可以在不使用GROUP BY编码SQL的情况下创建聚合方法,只需使用Odoo API上提供的read_group方法即可。
下面是我使用SQL获取它的方法:
SELECT SUM(ai.amount_total) as sum_total,
AVG(ai.amount_total) as avg_total
FROM account_invoice as ai
WHERE ai.partner_id = :partner_id AND ai.type = 'out_invoice'下面是我试图让它在我的模型类上工作的方式:
class MyModel(models.Model):
# fields definition
@api.multi
def get_aggregated_invoices(self):
self.ensure_one()
invoices_partner_domain = [
('partner_id', '=', self.partner_id.id),
('type', '=', 'out_invoice')
]
grouped_result = self.env['account.invoice'].read_group(
invoices_partner_domain,
[
'partner_id',
'sum_total:sum(amount_total)',
'avg_total:avg(amount_total)'
],
['partner_id']
)
if len(grouped_result) > 0:
print(str(grouped_result)) # << DEBUG breakpoint here
return {
'sum_total': grouped_result[0]['sum_total'],
'sum_total': grouped_result[0]['avg_total'],
}
else:
return None调试代码时,我得到了以下结果:

我是不是遗漏了什么或者Odoo 11没有和Odoo 12相同的功能?如果没有,有没有办法通过Odoo API来实现,或者我是否应该坚持使用我的GROUP BY SQL语句呢?
发布于 2021-09-12 21:55:47
v12版本在fields参数中引入了聚合函数的使用。
:参数列表字段:在对象上指定的列表视图中存在的字段列表。
每个元素要么是field (字段名称,使用默认聚合),要么是field:agg (使用聚合函数agg聚合字段),或者name:agg(field) (使用agg聚合字段并将其作为name返回)。可能的聚合函数是由PostgreSQL (https://www.postgresql.org/docs/current/static/functions-aggregate.html)和count_distinct提供的,具有预期的含义。
不同之处在于,在_read_group_raw函数中聚合字段的处理过程中,如果定义了聚合函数,则Odoo会尝试使用聚合函数,如果没有定义聚合函数,则会使用字段group_operator作为聚合函数。
Odoo 11不会检查我们是否定义了聚合函数并使用了group_operator。在您的示例中,aggregated_fields将是一个空列表。
amount_total字段的默认group_operator为sum。如果使用SQL调试级别,您将看到Odoo执行以下查询:
SELECT min("account_invoice".id) AS id, count("account_invoice".id) AS "partner_id_count" , sum("account_invoice"."amount_total") AS "amount_total" ,"account_invoice"."partner_id" as "partner_id"
FROM "account_invoice" LEFT JOIN "res_partner" as "account_invoice__partner_id" ON ("account_invoice"."partner_id" = "account_invoice__partner_id"."id")
WHERE (("account_invoice"."partner_id" = %s) AND ("account_invoice"."type" = %s))
GROUP BY "account_invoice"."partner_id","account_invoice__partner_id"."display_name"
ORDER BY "account_invoice__partner_id"."display_name"如下所示(使用sum作为聚合函数)调用read_group函数:
grouped_result = self.env['account.invoice'].read_group(
invoices_partner_domain,
[
'partner_id',
'amount_total',
],
['partner_id']
)https://stackoverflow.com/questions/69148517
复制相似问题