Django ORM 中的批量操作
生活随笔
收集整理的這篇文章主要介紹了
Django ORM 中的批量操作
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
數(shù)據(jù)模型定義
from django.db import modelsclass Product(models.Model):name = models.CharField(max_length=200)price = models.DecimalField(max_digits=10, decimal_places=2)批量插入數(shù)據(jù)
批量插入數(shù)據(jù)的時(shí)候,首先要?jiǎng)?chuàng)建一個(gè)對(duì)象的列表,然后調(diào)用bulk_create方法,一次將列表中的數(shù)據(jù)插入到數(shù)據(jù)庫中。
product_list_to_insert = list() for x in range(10):product_list_to_insert.append(Product(name='product name ' + str(x), price=x)) Product.objects.bulk_create(product_list_to_insert)批量更新數(shù)據(jù)
批量更新數(shù)據(jù)時(shí),先進(jìn)行數(shù)據(jù)過濾,然后再調(diào)用update方法進(jìn)行一次性地更新。下面的語句將生成類似update....frrom....的SQL語句。
Product.objects.filter(name__contains='name').update(name='new name')批量刪除數(shù)據(jù)
批量更新數(shù)據(jù)時(shí),先是進(jìn)行數(shù)據(jù)過濾,然后再調(diào)用delete方法進(jìn)行一次性刪除。下面的語句講生成類似delete from ... where ... 的SQL語句。
Product.objects.filter(name__contains='name query').delete()?
?
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/Black-rainbow/p/9567442.html
總結(jié)
以上是生活随笔為你收集整理的Django ORM 中的批量操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python中的id()函数_怪异现象
- 下一篇: 我发起了一个 用 物理服务器 和 .Ne