5

Well, I have many operations inside my function. there is a loop which has a self.create() function inside, and inside it there is still another loop containing another create function and so on... BUT they depends on each other with their ID.

Here is a sample of code (minified)

@api.multi
def create_report(self):
    id_report = None
    reports = [ResumeReport(resume) for resume in data] # a tab containing many reports to be created
    repo = self.env["module1"].search([("date", "=", str(date))])
    if repo:
        for r in repo:
            id_report = r
    else:
        id_report = self.env["module1"].create({
                'name': name
            })
    for rep in report:
        self.env["module2"].create({
                                'report_id': id_report.id,
                                'name': name
                            })

So what I want to do is to put this code under a transaction. It will be a pretty big SQL operation, so when an error occurs, I want it to be rollbacked and cancel all operations (Transaction!). Otherwise to commit it. But I don't know if there is a possibility to do that in Odoo 10 as I had not found any doc about transaciton.

Could you help me please?

SOLVED

@api.multi
def create_report(self):
self._cr.autocommit(False)
try:
    id_report = None
    reports = [ResumeReport(resume) for resume in data] # a tab containing many reports to be created
    repo = self.env["module1"].search([("date", "=", str(date))])
    if repo:
        for r in repo:
            id_report = r
    else:
        id_report = self.env["module1"].create({
                'name': name
            })
    for rep in report:
        self.env["module2"].create({
                                'report_id': id_report.id,
                                'name': name
                            })
self._cr.commit()
except:
self._cr.rollback()
  • AFAIK, Odoo runs everything in a transaction, and rollbacks if an exception is raised. – Unatiel Sep 12 '17 at 07:57
  • Yes that is true. I ve seen that Odoo cursor has automcommit attribute which is TRUE. So all I had to is to get the cursor and set it to FALSE with self._cr.autocommit(False) . then commit or rollback it manually. (I ve just found it) lol. Thank you anyway ! – Antsa Rakotomananjo Sep 12 '17 at 12:17
  • 1
    Ah, I thought you were wondering if the ORM could support transactions at all. If you want to run your own transactions, then you should really create your own cursor, and run your transaction in it. The [guidelines](https://www.odoo.com/documentation/10.0/reference/guidelines.html#never-commit-the-transaction) **strongy** advise to do it, and show an example. – Unatiel Sep 12 '17 at 15:24
  • Cool! Thank you Unatiel !! – Antsa Rakotomananjo Sep 13 '17 at 05:58

0 Answers0