I am writing a module that inherits product. Specifically, this module adds two new models: product.template.scrapped and product.scrapped. These models are pretty much identical, with two fields each. The fields are product_id (or product_template_id) and scrap_reason; product_id is a Many2one field to either product.product or product.template, depending on which model is being used.
Inside product.product and product.template, I created a One2Many field called scrapped_id, related to either of the scrap models.
I am using a create override where if you scrap a template, it will automatically create entries in product.scrapped for each variant attached to the template. If you scrap the only variant of a product, it will create an entry in product.template.scrapped for the associated template.
Inside the create override, I determine the ID of the record when it will actually be created, as well as if the opposite record has already been scrapped. The goal is to have one entry per template, and one entry for each unique variant, which is handled by the create override (I could use _sql_constraints, but I don't see a specific need for that right now).
My issue is that when I do variant.write({'scrapped_id': latest_scrapped_id}), since it doesn't exist yet I get an IntegrityError like below:
psycopg2.IntegrityError: insert or update on table "product_template" violates foreign key constraint "product_template_scrapped_id_fkey"
DETAIL: Key (scrapped_id)=(1) is not present in table "product_template_scrapped".
How can I force this value to be written when it doesn't exist in the database yet, but will once the write returns?
Here is what my product.template.scrapped and product.scrapped models look like:
\https://gist.github.com/dtodd-wipeos/81ee8a25c020726891cbc93dc124db77
I added them as a gist as the code formatting tools available on these forums are not the best.
One idea that I did come up with, and is probably the simplest would be to not write scrapped_id to the product or template inside the create function, and to make scrapped_id a computed field that searches for self.id in the scrapped model