Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django not cascading on delete

Tags:

python

sql

django

I'm realizing more and more that I'm still a Django noob, I can't seem to figure out what's happening with my data model and why it's not cascading deletes. Here is my model.

class message(models.Model):
     msg_text = models.CharField(max_length = 9900)
     date_time = models.DateTimeField()
     is_read = models.BooleanField(default=False)


 class thread(models.Model):
     message = models.ForeignKey(message)
     subject = models.CharField(max_length=160)
     from_user = models.ForeignKey(User, related_name = 'from_user')
     to_user = models.ForeignKey(User, related_name = 'to_user')
     thread_id = models.CharField(max_length = 36)

def __unicode__(self):
    return self.subject

And then here is my delete function

def delete_message(request, thread_id):
     t = thread.objects.get(id=thread_id)
     thread.objects.filter(thread_id = t.thread_id).delete()

     return HttpResponseRedirect(reverse("inbox.views.index"))

So every thread has messages attached to it, and all the threads that contain related messages (ie replies) are all related with a thread id which is a randomly generated string. So when I delete I get the initial thread id (django auto-generated id) and then use it to grab the unique thread id and delete all entries that contain that thread ID. However when I delete the thread it is not auto-cascading and deleting the related message objects.

The weird thing is that it worked before, but then stopped working, I'm not too sure why. Any ideas?

like image 239
john m. Avatar asked Oct 02 '10 20:10

john m.


2 Answers

In Django version 1.3 there is a on_delete parameter which determinates "ondelete" action, for example:

def get_sentinel_user():
    return User.objects.get_or_create(username='deleted')[0]

class MyModel(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user))

So maybe try:

class thread(models.Model):
     message = models.ForeignKey(message, on_delete=models.CASCADE)
     ...

source http://docs.djangoproject.com/en/1.3/ref/models/fields/

like image 88
damienix Avatar answered Sep 30 '22 17:09

damienix


That's not how cascading delete works. Since thread has a foreign key to message, if you delete a message, the cascading effect is to delete all associated threads. See the documentation for more information and examples:

  • Deleting objects

You could call delete on the associated message if that's what you want.

like image 37
ars Avatar answered Sep 30 '22 17:09

ars