Django模型中的自定义函数

Custom function in Django's model

我有模型,我想添加我的自定义函数,当我创建对象时,这个函数会自动调用。

这是我的模型和测试函数。仅供测试

我想要在调用 test 函数后创建 Like 对象

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)

谁能帮帮我?

如果您想 运行 创建类似对象时的测试函数,为什么不直接将测试函数放在保存函数中?

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()

)