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

前端 未结 6 1915
醉酒成梦
醉酒成梦 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:34

    Using update directly is more efficient and could also prevent integrity problems.

    From the official documentation https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.update

    If you’re just updating a record and don’t need to do anything with the model object, the most efficient approach is to call update(), rather than loading the model object into memory. For example, instead of doing this:

    e = Entry.objects.get(id=10)
    e.comments_on = False
    e.save()
    

    …do this:

    Entry.objects.filter(id=10).update(comments_on=False)
    

    Using update() also prevents a race condition wherein something might change in your database in the short period of time between loading the object and calling save().

提交回复
热议问题