Access previous document in Jinja

In an Jinja script, I want to access the previous document. I.e. from a Sales invoice, I want to access the associated Sales order. From a Sales order, I want to access the associated Quotation. From a Quotation, I want to access the associated Opportunity. The latter I can do with quotation_doc.opportunity. For the former two, the corresponding code does not work: neither sales_order_doc.quotation nor sales_invoice_doc.sales_order do work.

In the source code of ERPNext, I have found doc.prevdoc_docname, but this does not work in Jinja either.

Any ideas?

The references of the previous documents are generally stored in the item child table. You can get the reference of the previous docs from there.

Since one sales order can be generated from multiple quotes, and an invoice from multiple orders, the value is stored in the child table as it is a many-to-one relationship by default.

Right, many thanks!