I have two models which are associated to each other through a ForeignKey how to delete the child model object without affecting parent model object

52 views
Skip to first unread message

Vignesh s

unread,
Nov 9, 2019, 7:56:16 AM11/9/19
to Django users
I have two models which are associated to each other through a ForeignKey how to delete the child model object without affecting parent model object

Jordan Micle

unread,
Nov 9, 2019, 8:05:35 AM11/9/19
to Django users
when you use foreingkey you will set these options
here, change like this
on_delete=models.SET_NULL 
user = models.ForeignKey(User, null=Trueon_delete=models.SET_NULL)

Nijo Joseph

unread,
Nov 9, 2019, 8:47:25 AM11/9/19
to django...@googlegroups.com
Since you are deleting the child model object none of these matters. But if you are deleting the parent model object on_delete matters.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/2ea6ad8b-022e-4db1-adf0-9642565eb608%40googlegroups.com.

Parth Joshi

unread,
Nov 10, 2019, 12:01:16 AM11/10/19
to django...@googlegroups.com
Agree with Jordan. When you talk about CASCADE Delete to SET_NULL, those will matter when the parent table is deleted.

For Example:


User
Field
Type
UserID
INT
Username
VARCHAR



Employee
Field
Type
Relationship
… some fields 


User
INT
Foreignkey(User, Userid)

In this case:

1. If you delete Employee with a related User, you don’t have to worry about cascading on User.
2. But if you delete a User, the User is already referred in multiple places in other tables. Deleting that user will create a dangling reference. Which will affect the integrity constraints. So here you set a policy to DELETE on cascade or SET_NULL on related fields. 

Hope this helps

Regards, 

Parth Joshi



Reply all
Reply to author
Forward
0 new messages