Mahesh
Mahesh

Reputation: 1333

Foreign Key dependencies While deleting table

In my Postgresql, I have a main table TABLE_MAIN containing 10 columns in which 7 of the columns are foreign keys to the primary keys of the other 7 tables.

Now, in one of the tables (not TABLE_MAIN) let's call it child_table, whenever I click Refresh Button in the UI, I am emptying all the data in child_table using the following Django ORM query and then insert relevant data.

child_table.objects.all().delete()

I have lots of important data in TABLE_MAIN of around 1000 rows, and to my shock, whenever I click the Refresh button in the UI(which deleted all the data in child_table) I found that TABLE_MAIN data is completely gone.

What is happening here? Is it due to the foreign key dependencies??

and the other child_tables data is completely safe, but TABLE_MAIN data is lost.

Deleting one primary key in child_table for which it's a foreign key from TABLE_MAIN field will affect to lose all the data in TABLE_MAIN?

Upvotes: 1

Views: 1065

Answers (1)

Olzhas Arystanov
Olzhas Arystanov

Reputation: 986

Django's ForeignKey field provides a special option on_delete that let's you instruct Django what to do in case of related models deletion. You probably have this value set to CASCADE which deletes all objects containing ForeignKey whenever you delete some object from db. If you don't want this behavior, you should consider passing on of PROTECT, SET_NULL, SET_DEFAULT to on_delete option in your ForeignKey fields.

Upvotes: 2

Related Questions