Home > Enterprise >  Django: How to stop a value from incrementing when i refresh a page in Django?
Django: How to stop a value from incrementing when i refresh a page in Django?

Time:08-03

I have two some fields in my Profile model called:

class Profile(models.Model):
    ...
    main_all_earning = models.IntegerField(default=0)
    earning_point = models.IntegerField(default=0)
    referral_point = models.IntegerField(default=0)
    indirect_sign_up = models.IntegerField(default=0)

and i also have the logic in views.py

def profile(request):
   ...
user = request.user
    profile = request.user.profile
    my_count = Profile.objects.filter(recommended_by__profile__recommended_by=user).count()
    profile.indirect_sign_up = my_count * signup_point.ind_signup_point
    profile.main_all_earning = profile.main_all_earning   profile.indirect_sign_up
    profile.save()

Now whenever i call this profile view, the main_all_earning add whatever is in the indirect_sign_up and give the new value and so on... How do i stop this? what i want is for the main_all_earning to add whatever that is in the indirect_sign_up only once and till there is a new value in the indirect_sign_up and not whenever i refresh the page

CodePudding user response:

You could simply check if the indirect_sign_up value will change:

def profile(request):
   ...
    user = request.user
    profile = user.profile
    my_count = Profile.objects.filter(recommended_by__profile__recommended_by=user).count()

    temp_indirect_sign_up = my_count * signup_point.ind_signup_point
    if profile.indirect_sign_up != temp_indirect_sign_up:
        profile.indirect_sign_up = temp_indirect_sign_up
        profile.main_all_earning = profile.main_all_earning   profile.indirect_sign_up
        profile.save()

CodePudding user response:

IMHO, you should do this count update while updating the Profile model for a user. Whenever there is a change in the indirect_sign_up field run the count update code. Updating count only on profile visits may lead to incorrect counts for users. For me, the best placement can be at the point where the indirect_ref_signup update occurs.

Else, Signals can work best for you. We can work on a pre_save signal for this count update:

  • check if this is a save signal not create
  • check if current indirect_ref_signup has changed
# signals.py
from django.db.models.signals import post_save, pre_delete,pre_save
from django.dispatch import receiver
from .models import Profile


@receiver(pre_save, sender=Profile)
def update_indirect_signup_count(sender, instance, **kwargs):
    if instance.id is None:
        # this is on create event
        pass
    else:
        current=instance
        previous=Profile.objects.get(id=instance.id)
        if previous.indirect_sign_up!= current.indirect_sign_up:
            # update code here
            # save the instance
            instance.save()

  • Related