django使用bulk_update批量更新数据


一、第一步,导入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 = WestMedicineSkuQuerySet.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',]
        )

 








免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM