Wednesday, August 20, 2014

How to delete a referenced object when the object, referencing the other object, is deleted?

I posted the following question on SO (link) and I haven't received any helpful answers. Can someone here please help me?

I am relatively new to Django and I'm just starting to get a feel for it, but I just can't work this out.

Many thanks!!!

I have the following model:

class Todo(models.Model):      user = models.OneToOneField(User)      note = models.CharField(max_length=255)      is_important = models.BooleanField(default=False)      is_complete = models.BooleanField(default=False)      reminder = models.OneToOneField(Reminder, blank=True, null=True, on_delete=models.SET_NULL)      class Reminder(models.Model):      start_time = models.DateTimeField()      stop_time = models.DateTimeField(blank=True)

Basically, a Todo becomes a Reminder when a start and optional end time are supplied.

At the moment, when I delete a Reminder object, the reminder field in the Todo object is set to Null, which what I want.

What I want to know:

How can I setup these models so that if a Todo object is deleted, the corresponding Reminder object will also be deleted?

Also, if it wasn't a one-to-one relationship, let's say it was a many-to-one (many Todo's to one Reminder) relationship, how could one setup the models so that if a Todo object was deleted, the Reminder object will also be deleted, but only if there were no more Todo objects linked to the Reminder?

Also, with regards to:

stop_time = models.DateTimeField(blank=True)

If it is left blank in the form, what will the default value be, stored in the database?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e4f1ccda-d643-4334-ba44-87a125a91025%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment