Why can't I increment models.IntegerField?

I want to have a counter field in my user profile model to see how many requests each user has made.

However I cannot figure out how to increment the count.

I am trying to increment an integer field which is a associated with a model which looks like this:

class Profile(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        primary_key=True,
    )
    request_count = models.IntegerField(default=0)

Then in my views I want to increment the request_count every time the user makes a request like so:

     user = User.objects.get(email=pk)
     user_profile = Profile.objects.get(user=user)
     user_profile.request_count += 1
     user_profile.save()

For some reason every time I run this it sets the request_count to 1.

I assume this is because it is defaulting to 0 (the default I set) and then adding 1 to that.

But why doesn't the value increment?

Help greatly appreciated.

You could try with F expressions

def updateProfile(request, pk):
     user = User.objects.get(email=pk)
     user_profile = Profile.objects.get(user=user)
     user_profile.request_count = F("request_count") + 1
     user_profile.save()

     return redirect('index')

If you want to access the value after that, you should use refresh_from_db.

The only thing that kinda looks weird is this:

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

Unless you're using a custom user model, email isn't the primary key. The only required fields in the default user model are username and password. So maybe it's having trouble finding an user.

If it's not that, maybe you could try to update that field specifically:

user_profile.save(update_fields=['request_count'])

In the end it turned out that saving my ModelForm was, for some reason, resetting the count variable even though the count field wasn't part of the modelform. What fixed it was changing the ordering to set the instance first, then save the form, then save the profile with the count variable.

The final solutions looks like this:

Def updateProfile(request, pk):
    user = User.objects.get(email=pk)if form.is_valid():
        try:
            user_profile = Profile.objects.get(user=user)
            user_profile.ai_count +=1
        except:
            user_profile = None
        profile = form.save(commit=False)
        profile.user = user
        profile.save()
        user_profile.save()
        return redirect('index')

Not entirely sure why this works, but it does.

Back to Top