Django: save() vs update() to update the database?

前端 未结 6 1910
醉酒成梦
醉酒成梦 2020-12-12 18:55

I\'m writing a Django app, and I need a function to update a field in the database. Is there any reason to do one of these methods rather than the other?

de         


        
6条回答
  •  失恋的感觉
    2020-12-12 19:45

    Update will give you better performance with a queryset of more than one object, as it will make one database call per queryset.

    However save is useful, as it is easy to override the save method in your model and add extra logic there. In my own application for example, I update a dates when other fields are changed.

    Class myModel(models.Model): 
        name = models.CharField()
        date_created = models.DateField()
    
        def save(self):
            if not self.pk :
               ### we have a newly created object, as the db id is not set
               self.date_created = datetime.datetime.now()
            super(myModel , self).save()
    

提交回复
热议问题