python - How to cascade delete from a child to a parent -
i have 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, todo becomes reminder when start , optional end time supplied.
at moment, when delete reminder object, reminder field in todo object set null, want.
what need know:
how can setup these models if todo object deleted, corresponding reminder object deleted?
also, if wasn't one-to-one relationship, let's many-to-one (many todo's 1 reminder) relationship, how 1 setup models if todo object deleted, reminder object deleted, if there no more todo objects linked reminder?
also, regards to:
stop_time = models.datetimefield(blank=true)
if left blank in form, default value be, stored in database?
you defining relationship as
reminder = models.onetoonefield(reminder, blank=true, null=true, on_delete=models.set_null)
here specifying on_delete=models.set_null
. tells django set field null when referenced object deleted. if want delete object use models.cascade
. django uses default value.
more reference here
stop_time = models.datetimefield(blank=true)
when nothing specified field not set , blank, there no default value this.
as mentioned in comment, if want set reminder field in corresponding todo
object null
when reminder
object deleted, can put onetoone
relationship field in reminder
class instead of todo
class.
as onetoone relationship, per django orm identical when put in either of classes. access through attribute both objects.
for many-to-one have use pre-post delete signal. signals have own limitations
Comments
Post a Comment