Home > Enterprise >  Custom function in Django's model
Custom function in Django's model

Time:04-21

I have model and i want to add my custom function, and when i create object this function call automatically.

this is my model and test function. it's only for testing

i want when i create Like object after call test function

class LikeManager(models.Manager):

    def create(self, *args, **kwargs):
        decrease = kwargs.pop("decrease")
        new_like = self.model(**kwargs)
        new_like.save(decrease=decrease)
        return new_like
class Like(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("user"))
    question = models.ForeignKey(Question,on_delete=models.CASCADE,verbose_name=_("question"))

    objects = LikeManager()
    
    #this function (not printing)
    @property
    def test(self):
        print("Testing")
        return 1

    def save(self, decrease, *args, **kwargs):
        if not self.pk:
            if decrease:
                self.question.save()
            else:
                self.question.point  = 1
                self.question.save()

        return super(Like, self).save(*args, **kwargs)

who can help me?

CodePudding user response:

If you want to run the test function when a like object is created why don't you just put the test function inside of the save function?

class Like(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("user"))
    question = models.ForeignKey(Question,on_delete=models.CASCADE,verbose_name=_("question"))
    objects = LikeManager()

    def save(self, decrease, *args, **kwargs):
        def test(self):
            print("Testing")
            return 1
        if not self.pk:
            if decrease:
            self.question.save()
            else:
                self.question.point  = 1
                self.question.save()
        return super(Like, self).save(*args, **kwargs)

Otherwise, you need to call the test function every time after you create an object ( e.g.:

a = Like.objects.create(user=request.user,question=q)
a.test()

)

  • Related