I have Order and Shipment model. Shipment has a foreign key to Order.
class Order(...):
...
class Shipment()
order = m.ForeignKey('Order')
...
Now in one of my views I want do delete order object along with all related objects. So I invoke order.delete().
I have Django 1.0.4, PostgreSQL 8.4 and I use transaction middleware, so whole request is enclosed in single transaction.
The problem is that upon order.delete() I get:
...
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/__init__.py", line 28, in _commit
return self.connection.commit()
IntegrityError: update or delete on table "main_order" violates
foreign key constraint "main_shipment_order_id_fkey" on table "main_shipment"
DETAIL: Key (id)=(45) is still referenced from table "main_shipment".
I checked in connection.queries that proper queries are executed in proper order. First shipment is deleted, after that django executes delete on order row:
{'time': '0.000', 'sql': 'DELETE FROM "main_shipment" WHERE "id" IN (17)'},
{'time': '0.000', 'sql': 'DELETE FROM "main_order" WHERE "id" IN (45)'}
Foreign key have ON DELETE NO ACTION (default) and is initially deferred. I don't know why I get foreign key constraint violation.
I also tried to register pre_delete signal and manually delete shipment objects before delete on order is called, but it resulted in the same error.
I can change ON DELETE behaviour for this key in Postgres but it would be just a hack, I wonder if anyone has a better idea what's going on here.
There is also a small detail, my Order model inherits from Cart model, so it actually doesn't have id field but cart_ptr_id and after DELETE on order is executed there is also DELETE on cart, but it seems unrelated? to the shipment->order problem so I simplified it in the example.
Deleting a foreign key constraint removes the requirement to enforce referential integrity.
You can modify the foreign key side of a relationship in SQL Server by using SQL Server Management Studio or Transact-SQL. Modifying a table's foreign key changes which columns are related to columns in the primary key table.
In "Structure" tab, click on "see relational view" below the fields. Here you can remove the foreign keys by selecting an empty value in the dropdown.
DETAIL: Key (id)=(45) is still referenced from table "main_shipment".
There is still a record referencing to id 45. You did delete record 17 in main_shipment before, but there might be others as well. You have to delete all records in main_shipment referencing to id 45 in main_order. If not, the database protects you from doing harm to your data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With