Home > Software design >  Why can't I increment models.IntegerField?
Why can't I increment models.IntegerField?

Time:12-20

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:

def updateProfile(request, email):
     user = User.objects.get(email=email)
     form = forms.ProfileForm(request.POST)
     if request.method == 'POST':
        if form.is_valid():
            profile = form.save(commit=False)
            profile.user = user
            form.save()
            try: 
                user_profile = Profile.objects.get(user=user)
                user_profile.request_count  = 1
                user_profile.save()
            except:
                user_profile = None
            return redirect('index')

<a href="{% url 'update-profile' session.userinfo.email %}">
Update my profile
</a>

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.

CodePudding user response:

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.

CodePudding user response:

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'])
  • Related