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