Home > Back-end >  How to create a class in django which will be deleted when the element in another class is deleted
How to create a class in django which will be deleted when the element in another class is deleted

Time:05-26

I am new to python and django please help me with this doubt .How to create a class in django which will be deleted when the element in other class is deleted ?

CodePudding user response:

you can use on_delete on your ForeignKey filed

for more explanation, look here

CodePudding user response:

You can do like this:

class Company:
     name = models.CharField(blank=False, max_length=150)
    
class Car:
     company = models.ForeignKey(Company, on_delete=models.CASCADE)

Whenever company is deleted. All the cars with that company will also get deleted. If you do on_delete=models.PROTECT it will prevent deletion of records because it's protected.

  • Related