OneToOne and model deletion

12 views
Skip to first unread message

alex finn

unread,
Jul 9, 2008, 12:12:23 PM7/9/08
to Django users
Hi,

I'm new to django and was trying to play around OneToOne mapping (a
very powerful feature in my mind) and found one possible issue.

I created two models: Person and Profile, where Profile is mapped to
Person with OneToOne profile field in the Person class. So now when I
create a Person, I need to create a Profile instance in advance which
is fine. But what I noticed is that when I delete Person instance the
associated Profile instance is not deleted automatically which is what
I would expect as it is OneToOne mapping.

Ok, I can override Person's delete method which allows me to handle
this and delete the associated model instance.

But now when I need to delete all the Person instances in the
collection (i.e. Person.objects.all().delete()), Person's delete
method won't be involved and thus all the Profile instance will stay
alive. Is this something expected or is this a bug? Does anybody have
an experience of dealing with such issue?

Thanks,
Alex.

rui

unread,
Jul 9, 2008, 12:17:34 PM7/9/08
to django...@googlegroups.com
Try setting the primary_key option as True.

From http://www.djangoproject.com/documentation/models/one_to_one/:

class Restaurant(models.Model):
place = models.OneToOneField(Place, primary_key=True)

# Delete the restaurant; the waiter should also be removed
>>> r = Restaurant.objects.get(pk=1)
>>> r.delete()

Cheers.

--
Rui

alex finn

unread,
Jul 9, 2008, 2:53:32 PM7/9/08
to Django users
> Try setting the primary_key option as True.

Fair enough, but this will solve the issue (will it? Didn't try yet)
only in case I need just one OneToOne mapping per model. What if I
need more?
In the example above, what if I need Person to be mapped to Profile
and ProjectParticipant models as OneToOne?

All in all, I'm not saying this issue is critical, I'm just trying to
understand if this behaviour was introduced intentionally and I should
keep this in mind in developing in django or this is something that
should be fixed on a django level rather then on my application level.
I was trying to find any bugs on djangoproject.org but didn't succeed,
should I open a new one?

Alex.

Reply all
Reply to author
Forward
0 new messages