Adilet Maratov Adilet Maratov - 3 months ago 22
Python Question

Why does not django delete one to one relationship?

I have the following simple relationship:

class User(models.Model):
fields here

class UserProfile(models.Model):
user = models.OneToOneField(User)


I did the following in the shell:

user = User.objects.create(...)
profile = UserProfile.objects.create(user=user)
user.userprofile
...<UserProfile: UserProfile object>
user.userprofile.delete()
...(1, {'accounts.UserProfile': 1})
user.userprofile
...<UserProfile: UserProfile object>


From the above, you can see that I create User and UserProfile instances. Than I try to delete UserProfile instance and it is deleted (at least seems like). Than I do
user.userprofile
and it's like it never was deleted.

After little digging into the Django delete method, I realized that when I do
user.userprofile.delete()
Django just deletes userprofile's pk and the rest fields are not touched. What I do not understand is what should I do in order to get the following result:

user.userprofile.delete()
user.userprofile
...RelatedObjectDoesNotExist: User has no userprofile.


Does anyone have some ideas or code snippets?

Answer

You can reload the user from the database:

user = User.objects.get(pk=user.pk)

That will refresh all its attributes including the userprofile.