AlphaDjango
AlphaDjango

Reputation: 33

Django do something when model instance created

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

Upvotes: 0

Views: 671

Answers (1)

Alexey Popov
Alexey Popov

Reputation: 756

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

Upvotes: 3

Related Questions