This question has been flagged
2 Replies
3475 Views

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.

Avatar
Discard
Author

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

Best Answer

In Odoo one-to-one relationships get a little bit messy. To avoid the situation, I generally use a many-to-one on one side (in this example I would put it on the scrapped) and a one-to-many on the other (the product side). As long as your constrains are working correctly, you can be fairly sure that a product will only have one scrapped_ids, even though it's a one-to-many and could have more.

This is essentially making a compute on the product as you mentioned in your comment, but it's all handled by Odoo rather than your own compute function. It also allows you to do a search over the products where scrapped_ids is set or not, whereas a non-stored compute doesn't allow this.

Avatar
Discard