一、第一步,导入bulk_update包
from bulk_update.helper import bulk_update
二、写一个类
class CommonQuerySet(models.QuerySet):

def bulk_update(self, objs, update_fields=None,
exclude_fields=None, batch_size=None):
self._for_write = True
using = self.db

return bulk_update(
objs, update_fields=update_fields,
exclude_fields=exclude_fields, using=using,
batch_size=batch_size)

  

三、第三步,在需要使用批量更新的model类中,添加一行代码
class Track(models.Model):
    album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
    order = models.IntegerField()
    title = models.CharField(max_length=100)
    duration = models.IntegerField()
     objects =CommonQuerySet.as_manager() 
  

  class Meta:
    unique_together = ('album', 'order') ordering = ['order']

  

方法二:

第一步导入包
from django_bulk_update.helper import bulk_update
第二步使用
        prescription_item_objs = []
        for prescription_item_list in prescription_item_data:
            for i in prescription_item_list:
                prescription_dic[i.get('id')] = i.get('weight')
        for i in prescription_item_qs:
            i.weight = prescription_dic.get(i.id)
            prescription_item_objs.append(i)
        print(prescription_item_objs)
        bulk_update(
            prescription_item_objs, update_fields=['weight',]
        )

 







posted on 2021-09-13 11:17  輪滑少年  阅读(6129)  评论(0编辑  收藏  举报