Django does not cascade on deletion

I understand more and more that I am still Django noob, I cannot understand what is happening with my data model and why it does not cascade. 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 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")) 

Thus, each thread has messages attached to it, and all threads containing related messages (i.e. replies) are associated with a thread identifier, which is a randomly generated string. Therefore, when I delete, I get the initial stream identifier (django auto-generated id), and then use it to capture the unique stream identifier and delete all records containing this stream identifier. However, when I delete a stream, it does not autocascade or delete related message objects.

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

+6
python sql django
source share
2 answers

In version Django 1.3, there is an on_delete parameter that defines the "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 try:

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

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

+4
source share

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

You can call delete in the corresponding message if that is what you want.

+1
source share

All Articles