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

17 views
Skip to first unread message

Oliver Funk

unread,
Aug 20, 2014, 11:34:03 AM8/20/14
to django...@googlegroups.com

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?

Tom Evans

unread,
Aug 20, 2014, 12:43:23 PM8/20/14
to django...@googlegroups.com
On Wed, Aug 20, 2014 at 4:34 PM, Oliver Funk <oli....@gmail.com> wrote:
> I posted the following question on SO (link) and I haven't received any
> helpful answers. Can someone here please help me?

Sorry, same answers here - move the OneToOne to the other model or use
pre_delete signals to check how many related objects there will be
post delete.

You can simplify the whole logic by removing the need for two classes
- a Todo is a Reminder with null/empty start/stop time.

> 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?
>

I don't know; whenever I have a DateTimeField that is potentially not
specified, I will specify the field as "blank=True, null=True". In
that scenario, Django stores NULL as the date in the database,
represented as None in python.

Cheers

Tom
Reply all
Reply to author
Forward
0 new messages