Django - Function inside a model. How to call it from a view?

前端 未结 5 650
悲&欢浪女
悲&欢浪女 2021-02-05 12:43

I\'m designing a model in Django but I don\'t know if this is the best way. I have a model called \"History\" and inside this model I\'ve a specialized function that will handle

5条回答
  •  礼貌的吻别
    2021-02-05 13:12

    Does insert_history use self? Or does it create a new History object?

    If it creates a new object, I'd do it like this:

    class History(models.Model):
        @classmethod
        def insert_history(cls, field1, field2, field3):
            # Here be code
    

    To call it

    from app.models import History
    History.insert_history(field1, field2, field3)
    

    BTW, the conventional name for a method creating new objects is create. Also, have a look at https://docs.djangoproject.com/en/1.9/ref/models/instances/#creating-objects

提交回复
热议问题