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

前端 未结 5 658
悲&欢浪女
悲&欢浪女 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:16

    To insert data to the History model I will always have to use the insert_history function.

    Yes, it will set the field3, a datetime, based on some logic that I will write inside insert_history

    The easiest way is to override the save method:

    class History(models.Model):
        field1 = models.ForeignKey(Request)
        field2 = models.BooleanField()
        field3 = models.DateTimeField()
    
        def __unicode__(self):
            return unicode(self.field1.id) # __unicode__ should return unicode,
                                           # not string.
    
        class Meta: #
            ordering = ['-field3']
    
        def save(self, *args, **kwargs):
            self.field3 = your calculated value
            super(History, self).save(*args, **kwargs)
    

    Now, whenever you save your method - field3's value will be whatever is the result of the calculation in your custom save method. You don't need to modify anything in your views for this to work.

提交回复
热议问题