0

I am developing an app where I need some of the data to be protected even when some models are deleted. I've been reading on the on_delete options, and seems to be a lot of warnings against using on_delete=DO_NOTHING. In my case, I need the results to be maintained even when a yacht or event gets deleted. The basic structure is this;

# models.py
class Yacht(models.Model):
     yacht_name=models.CharField(max_length=100)
class Event(models.Model):
     event_name=models.CharField(max_length=100)
     yachts = models.ManyToManyField(Yacht, through="Result")
class Result(models.Model):
     yacht = models.ForeignKey(Yacht, on_delete=DO_NOTHING)
     event = models.ForeignKey(Event, on_delete=DO_NOTHING)
     ranking = models.IntegerField(max_lenght=4)

 

For record keeping, I need the results to remain even if a yacht or event is deleted. What is the best approach here? Some thoughts;

  1. Create additional Result field (_yacht = models.CharField()) and use a post_save signal to provide a string.
  2. Create a separate table to keep records of the events. Table gets created/updated at post_save

Thanks in advance,

J

JulienEast
  • 27
  • 7

2 Answers2

0

Please check out the official document at the link below https://docs.djangoproject.com/en/4.2/ref/models/fields/#django.db.models.ForeignKey.on_delete

Based on this here are some modifications to your code as per your requirements; try it. (If I have understood your requirement correctly)

class Result(models.Model):
     yacht = models.ForeignKey(Yacht, on_delete=models.SET_NULL, null=True)
     event = models.ForeignKey(Event, on_delete=models.SET_NULL, null=True)

Note: your fields need to be null=True; also note "null" is related to database & "blank" is related with your HTML forms

Mukibul Hasan
  • 592
  • 5
  • 10
  • The only issue with SET_NULL is that it will reference to nothing. I need to preserve a string representation of what was there before. So if a yacht was named Yacht1, once deleted I still want the result to display "Yacht1" at least as a string since the actual object no longer exists. – JulienEast Apr 10 '23 at 10:50
0

I suppose you consider a soft delete by implementing a deleted field in your model(s):

deleted = models.BooleanField(default=False)`

def soft_delete(self):
    self.deleted = True
    self.save()

More here: https://dev.to/bikramjeetsingh/soft-deletes-in-django-a9j