如何将函数添加到不需要模型实例的模型中?

时间:2012-04-18 00:52:09

标签: python django class models

所以我一直在尝试在Django中添加一个模型函数,它接受参数然后将X个新记录插入到数据库中。

为什么不能MyModel.MyFunction()?我是否需要先制作一个实例?

如果是这样,有没有更好的方法来实现我想要的结果?

1 个答案:

答案 0 :(得分:3)

你当然可以这样做,你只需要把它变成classmethod

class MyModel(models.Model):
    @classmethod
    def my_function(cls):
        new_instance = cls(...)
        new_instance.save()
        # etc...