Reputation: 189
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?
Upvotes: 6
Views: 13880
Reputation: 6763
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/
Upvotes: 5
Reputation: 123498
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 thread
s. See the documentation for more information and examples:
You could call delete
on the associated message if that's what you want.
Upvotes: 1