Can't update value of IntegerField of Django 1.8

Question:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    how_many_new_notifications = models.IntegerField(null=True,blank=True,default=0)
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])

In views.py function which is 100% called and whom is present

whom.profile.how_many_new_notifications += 1
whom.save()

Whatever, how_many_new_notifications is still equal zero and not incremented , despite everything else is correct

Also tried something like this:

  if  whom.profile.how_many_new_notifications  ==  None:
            whom.profile.how_many_new_notifications = 1
  else:
            varible_number_of_notifications = int(  whom.profile.how_many_new_notifications)
            whom.profile.how_many_new_notifications = varible_number_of_notifications  + 1

Get no errors in log, is there any reason why this code wouldn’t work, or should I search for issues in other places?

Asked By: user3475724

||

Answers:

User.profile is a property that gets a new copy of the profile each time it is used.

So when you do

user.profile.how_many_notifications += 1
user.profile.save()

Each line uses its own copy of the profile, the two Python objects are unrelated.

So you need to do

profile = user.profile
profile.how_many_notifications += 1
profile.save()

But using a profile property like that is a bit odd — you have a OneToOneField, and a related property is already automatically defined as the lower case name of your class. So

user.userprofile.how_many_new_notifications += 1
user.userprofile.save()

Should also work. If you want to change the name userprofile, use related_name:

user = models.OneToOneField(User, related_name='profile')

And then it works with user.profile.

Answered By: RemcoGerlich
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.