Lewis
Lewis

Reputation: 2798

Django: How to delete child row and remove relationship from Foreign key

What I want

I have two Models. I want the following outcomes:

What I've tried

When trying to delete RecordModel. I receive error:

MySQLdb._exceptions.IntegrityError: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (`cdt_dashboard`.`emissions_dashboard_bookingmodel`, CONSTRAINT `emissions_dashboard__record_id_f8312a32_fk_emissions` FOREIGN KEY (`record_id`) REFERENCES `emissions_dashboard_recordmodel` (`i)')

Models

class RecordModel(models.Model):

    created = models.DateTimeField(blank=True, null=True)
    started = models.DateTimeField(blank=True, null=True)
    finished = models.DateTimeField(blank=True, null=True)

class BookingModel(models.Model):
    booker = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    record = models.OneToOneField(RecordModel, blank=True, null=True, on_delete=models.DO_NOTHING)


Upvotes: 1

Views: 1019

Answers (1)

KutayAslan
KutayAslan

Reputation: 494

Try changing

record = models.OneToOneField(RecordModel, blank=True, null=True, on_delete=models.DO_NOTHING)

into this

record = models.OneToOneField(RecordModel, blank=True, null=True, on_delete=models.SET_NULL)

Upvotes: 2

Related Questions