Odoo / OpenERP Integrity Error on delete order_line - odoo

I use delegation to inherit fields from sale_order in a custom module:
class EXAMPLE(osv.osv):
_name = 'EXAMPLECLASS'
_inherits = {
'sale.order': 'sale_order_id'}
I'm using the standard view for sale_order. Everything works fine, I can add and update order_lines within the sale_order. However, when I try to delete an order_line from the sale_order I get the following error:
Integrity Error
The operation cannot be completed, probably due to the following:
- deletion: you may be trying to delete a record while other records still reference it
- creation/update: a mandatory field is not correctly set
[object with reference: order_id - order.id]
What am I missing? I think it has something to do with the fact that '_inherits' only inherits fields and not methods.
Any help on this matter would be greatly appreciated.

Related

Odoo 12: Many2one ondelete message?

Is it possible to change(edit) default ondelete message in Many2one field?
My field is:
parent_id = fields.Many2one("pgp.organizational.classifications", string="Parent classification", select=True, ondelete='restrict')
Default message is like this, but I won't to add my message:
"Odoo Server Error - Greška kod provjere
The operation cannot be completed, probably due to the following:
- deletion: you may be trying to delete a record while other records still reference it
- creation/update: a mandatory field is not correctly set
[objekt s referencom: pgp.organizational.classifications - pgp.organizational.classifications] "
You cannot change it in the Many2one field's declaration.
Code which generates this message is there: https://github.com/odoo/odoo/blob/12.0/odoo/service/model.py#L120-L154
Seems to be tricky to overload
Restricting and cascading deletes are the two most common options. RESTRICT prevents deletion of a referenced row. NO ACTION means that if any referencing rows still exist when the constraint is checked, an error is raised; this is the default behavior if you do not specify anything. (The essential difference between these two choices is that NO ACTION allows the check to be deferred until later in the transaction, whereas RESTRICT does not.) CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well. There are two other options: SET NULL and SET DEFAULT. These cause the referencing columns to be set to nulls or default values, respectively, when the referenced row is deleted. Note that these do not excuse you from observing any constraints. For example, if an action specifies SET DEFAULT but the default value would not satisfy the foreign key, the operation will fail.
I solved it by overloading unlink method.
Here is the code if it helps someone:
> #api.multi
> def unlink(self):
> for field in self:
> if field.parent_id:
> raise UserError(_('It is not possible to delete a record that is already used in transactions!'))
> return super(YourClass, self).unlink()

Removing children entries from parent causes error on SaveChanges

I am getting the following error:
The association between entity types 'Docket' and 'DocketLine' has been severed but the foreign key for this relationship cannot be set to null. If the dependent entity should be deleted, then setup the relationship to use cascade deletes.
The issue comes about because I have a Docket (header) than has multiple children (DocketLines), and I am doing an update where I am adding new Lines to the docket header, and I am just adding those new DocketLines to the Docket.DocketLines collection (which works fine). But when I attempt to remove a DocketLine from the same collection using Docket.DocketLines.Remove(deletedLine), then this generates the error message above. Any idea why?
I had to change my code to remove the Lines directly from the _context.DocketLines.Remove/RemoveRange(...) collection in the end, and this works, but it seems odd that I would add new items to a child collection to insert new DocketLines, but couldn't remove items from that same collection to remove DocketLines.
Inside the DbContext/OnModelCreating method, comment the OnDelete behaviour of the entity that is giving you that problem:
That will allow you to avoid that problem.

How to resolve this error in OpenErp?

I have been trying the following code in openerp and I had been getting this error
The operation cannot be completed, probably due to the following:
- deletion: you may be trying to delete a record while other records still reference it
- creation/update: a mandatory field is not correctly set
[object with reference: name - name]
In my py file, i had inherited one module
class hr_expense_expense(osv.osv):
_name = "hr.expense.expense"
_inherit = "hr.expense.expense"
_inherits = {'hr.employee':'first_approver'}
You don't give details, but I'm pretty sure the _inherits line should be removed. You probably made a confusion and actually want to add Many2one relation.

Adding a new entry that has no foreign keys results in a "The relationship could not be changed [..]" error

I am running into a weird problem. When I deploy my code, everything works. I can add orders to my system. However, after some orders has been made, I start to get the famous error:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
Now, I have read a lot about that error, but it doesn't help my case. I have a very simple database without any foreign keys:
My code looks like the following:
public NewOrder Create(NewOrder order)
{
var o = new WebshopOrder();
o.AdvertId = order.AdvertId;
o.DateCreated = DateTime.Now;
o.IsActivated = order.OrderState > OrderState.Created;
o.ProductId = order.Product.Id;
o.UserId = order.UserId.ToString();
Db.WebshopOrder.Add(o);
Db.SaveChanges();
return new NewOrder() { WebshopOrderId = o.Id};
}
Which in turn, then fails when I say Db.SaveChanges().
Any idea what on earth could be wrong here?
I see three possibilities at the moment:
ProductId is being sent to the DB as NULL
OrderId is being sent to the DB as NULL
Timestamp is being sent to the DB as NULL
I think it is complaining about one of those three columns that are the only ones that do NOT allow NULL. I think ProductId has the greatest chance of being the culprit, where your code is being called sometimes with a value there, and others times it is receiving a NULL product.
This may, or may not be the issue, but your code has:
order.Product.Id
Did you want to use this instead?
order.ProductId
That error message would be improved if it were split into two or more errors with each being more specific.
I can see from your question that you are looking into the Order table for relationships.
Instead you have to look into WebshopOrder table for any relations, because you are saving the WebshopOrder
Db.WebshopOrder.Add(o);
Db.SaveChanges();

Nhibernate foreign key constraint due to unexpected update of already inserted record

This is a strange one replicated in the following code:
using (ISession session = RepositoryTestHelper.SessionFactory.OpenSession())
{
//session.BeginTransaction();
UserRepo repo = new UserRepo(session);
CompanyRepo cRepo = new CompanyRepo(session);
var user = repo.FindByEmail("test.user#blah.com");
user.CompanyAssociations.Add(new CompanyUserAssoc()
{
User = user,
Company = cRepo.GetById(1)
});
repo.AddOrUpdate(user);
//session.Transaction.Commit();
}
And the relationship between user, company and CompanyUserAssoc is fairly straight forward:
For the company:
HasMany<CompanyUserAssoc>(x => x.UserAssociations).KeyColumn("User_id");
For the user:
HasMany<CompanyUserAssoc>(x => x.CompanyAssociations).KeyColumn("Company_id")
And for the association class itself:
References(x => x.Company).UniqueKey("CompanyId_UserId");
References(x => x.User).UniqueKey("CompanyId_UserId");
Now this is where I am baffled. Notice in my initial code that the begin and commit trans calls are commented out. This actually means the code will work! The CompanyUserAssoc is created and correctly references the user and the company with id of 1. Great!
But... sadly when I put this in a transaction i get this error:
{"The UPDATE statement conflicted with the FOREIGN KEY constraint \"FK3C47859753A62C6E\". The conflict occurred in database \"xxxx\", table \"dbo.Company\", column 'Id'.\r\nThe statement has been terminated."}
But why? Well that's my question. What i have see in the profiler is that it does this:
exec sp_executesql N'UPDATE [CompanyUserAssoc] SET Company_id = null WHERE Company_id = #p0',N'#p0 int',#p0=1
Wait... what? NULL? Why is it setting the company id to null? and why is it only doing this when in a transaction? What's "wrong" with my Nhibernate mapping?
Since both collections are mapped as non-inverse (the default) and the Company collection has no users, it will issue that update to clear the link table. Could you try setting the UserAssociations to inverse? Or, what I usually do when an explicit link table is involved, is set both HasManys to inverse and simply work with the link table directly.
This was a red herring in the end, a fish I have come to despise. I had not noticed in my haste and dependence on intellisense that the UserAssocations property of the Company was not an IList but an IList! yes I have stupidly chosen the Nhib map class instead of the domain class.. This weirdly didn't error in the way you would expect, and worked without a transaction, but why?
Well - Nhib was able to insert the assoc entry, but then believed it needed to update that same table with the id it had already inserted (because it somehow sees it as a different entity?). I would have expected a compilation error here in the map class itself as I was using the type, but no. And without a transaction the sql generated works.
I would investigate more as to why, but I've answered this just to highlight a rare and silly mistake which can lead to a lot of investigation if missed.