2

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?

Adilet Maratov
  • 1,312
  • 2
  • 14
  • 24

2 Answers2

4

You can reload the user from the database:

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

That will refresh all its attributes including the userprofile.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

You can use Model.refresh_from_db:

user.refresh_from_db

Relevant docs

Mostafa Nasef
  • 33
  • 1
  • 5