如何更新不可更新的视图?

how to update a non updatable view?

我正在开发 odoo 版本 11。我创建了一个名为 test 的视图。我升级了模块。稍后我需要进行一些更改,包括更改一些值和删除一些值。每当我尝试升级模块时,我都会收到错误消息

psycopg2.OperationalError: cannot delete from view "test" DETAIL: Views containing GROUP BY are not automatically updatable. HINT: To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.

如何提供规则?我的代码如下

@api.model_cr
def init(self):
    cr = self.env.cr   
    tools.drop_view_if_exists(cr, 'o_test')
    cr.execute("""
    
                CREATE or replace view o_test as 
                (
                    SELECT 
                        mve.id as id,
                        acc.code as account_code,
                        SUM (mve.debit-mve.credit) AS balance,
                        mve.account_id as account_id
                    FROM account_move_line mve
                    LEFT JOIN account_account acc ON mve.account_id = acc.id 
                    GROUP BY mve.id,mve.account_id,acc.code
                )
            """)

我想把代码改成如下:

@api.model_cr
def init(self):
    cr = self.env.cr   
    tools.drop_view_if_exists(cr, 'o_test')
    cr.execute("""
    
                CREATE or replace view o_test as 
                (
                    SELECT 
                        mve.account_id as id,
                        acc.code as account_code,
                        SUM (mve.debit-mve.credit) AS balance,
                        mve.account_id as account_id
                    FROM account_move_line mve
                    LEFT JOIN account_account acc ON mve.account_id = acc.id 
                    GROUP BY mve.account_id,acc.code
                )
            """)

可以使用规则在 Postgres 中创建可编辑视图,GROUP BY 子句应该不是问题。您可以为更新查询编写如下规则。这里我只更新了一列

CREATE OR REPLACE RULE update_o_test AS
    ON UPDATE TO o_test
    DO INSTEAD
 UPDATE account_account SET code = new.code
  WHERE account_account.id = old.id;

同样,您可以为插入和删除操作创建规则。在 create view 语句结束后添加规则应该可行。 希望这有助于...