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.
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()
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