Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete related object via OneToOneField

Is there some clever way how to perform delete in this situation?

class Bus(models.Model):  
    wheel = OneToOneField(Wheel)  

class Bike(models.Model):  
    wheel = OneToOneField(Wheel)  
    pedal = OneToOneField(Pedal)

class Car(models.Model):  
    wheel = OneToOneField(Wheel)  

class Wheel(models.Model):  
    somfields

car = Car()    
wheel = Wheel()  
wheel.save()
car.wheel = wheel
car.save()  
car.delete() # I want to delete also wheel (and also all stuff pointing via OneToOneField eg pedal)

Do I need to override delete methods of Car, Bike, Bus models or is there some better way? Other option is to create fields car, bike, bus on Wheel model, but it doesn't make much sense.

like image 628
ChRapO Avatar asked May 18 '13 03:05

ChRapO


1 Answers

Cascading delete is already provided by django, through on_delete attribute value CASCADE. It is also available for OneToOneField along with ForeignKey.

ForeignKey.on_delete

When an object referenced by a ForeignKey is deleted, Django by default emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey.

However, in your models you are putting OneToOneField in another model, hence you are not seeing the expected behavior.

Change your models to:

class Car(models.Model):  
    somefields

class Wheel(models.Model):  
    somfields
    car = OneToOneField(Car)  

That is put OneToOneField in Wheel model instead of Car. Now when you delete Car model corresponding Wheel will also be deleted.

Problem with overriding delete() method is that it will not be called if you do bulk delete operation as Car.objects.filter().delete()

like image 68
Rohan Avatar answered Sep 19 '22 20:09

Rohan