Adilet Maratov Adilet Maratov - 1 year ago 103
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)
...<UserProfile: UserProfile object>
...(1, {'accounts.UserProfile': 1})
...<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
and it's like it never was deleted.

After little digging into the Django delete method, I realized that when I do
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:

...RelatedObjectDoesNotExist: User has no userprofile.

Does anyone have some ideas or code snippets?

Answer Source

You can reload the user from the database:

user = User.objects.get(

That will refresh all its attributes including the userprofile.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download