0

I'm looking to update a user's coin count in their profile whenever I create a promo code redemption object from a model.

Is there a method that runs when the object is created so I can update a field in the users profile from the promo code redemption model?

I tried init() but the arguments were no longer being filled in and saved in the model and I'm just looking to run extra code rather than adding custom fields.

I saw the signals file mentioned but wouldn't it be simpler to have it be done automatically through the model as a method?

class Promo_Code_Redemption(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    amount = models.DecimalField(max_digits=9,decimal_places=2)
    date = models.DateTimeField(default=timezone.now)
    code = models.ForeignKey(Promo_Code, on_delete=models.CASCADE)
    code_text = models.TextField()
    revenue_type = "Promo code"

    def __str__(self):
        return self.code.code

1 Answer 1

3

You can override Promo_Code_Redemption save() method:

# recommended naming convention for 
# class names in python is UpperCaseCamelCase
class Promo_Code_Redemption(models.Model):
    ...
    
    def save(self, *args, **kwargs):
        # you can check if object just created by comparing "pk" attr to None
        # you can also use _state attr see doc link below
        is_created = self.pk is None

        super(Promo_Code_Redemption, self).save(*args, **kwargs)

        if is_created:
            # do something here
            print('is created')



        

Model _state attr

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.