W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
使用批量方法來減少SQL語句
當(dāng)創(chuàng)建對(duì)象時(shí),盡可能使用 ?bulk_create()
? 方法來減少 SQL 查詢數(shù)量。比如:
Entry.objects.bulk_create([
Entry(headline='This is a test'),
Entry(headline='This is only a test'),
])
要優(yōu)于:
Entry.objects.create(headline='This is a test')
Entry.objects.create(headline='This is only a test')
當(dāng)更新對(duì)象時(shí),盡可能使用 ?bulk_update()
? 方法來減少 SQL 查詢數(shù)。給定對(duì)象的列表或查詢集:
entries = Entry.objects.bulk_create([
Entry(headline='This is a test'),
Entry(headline='This is only a test'),
])
下面示例:
entries[0].headline = 'This is not a test'
entries[1].headline = 'This is no longer a test'
Entry.objects.bulk_update(entries, ['headline'])
要優(yōu)于:
entries[0].headline = 'This is not a test'
entries[0].save()
entries[1].headline = 'This is no longer a test'
entries[1].save()
當(dāng)插入對(duì)象到 ?ManyToManyFields
?時(shí),使用帶有多個(gè)對(duì)象的 ?add()
? 來減少 SQL 查詢的數(shù)量。舉例:
my_band.members.add(me, my_friend)
要優(yōu)于:
my_band.members.add(me)
my_band.members.add(my_friend)
其中 ?Bands
?和 ?Artists
?有多對(duì)多關(guān)系。
當(dāng)不同的對(duì)象對(duì)插入到 ?ManyToManyField
?或者自定義的 ?through
?表被定義時(shí),可以使用 ?bulk_create()
? 方法來減少 SQL 查詢的數(shù)量。比如:
PizzaToppingRelationship = Pizza.toppings.through
PizzaToppingRelationship.objects.bulk_create([
PizzaToppingRelationship(pizza=my_pizza, topping=pepperoni),
PizzaToppingRelationship(pizza=your_pizza, topping=pepperoni),
PizzaToppingRelationship(pizza=your_pizza, topping=mushroom),
], ignore_conflicts=True)
要優(yōu)于:
my_pizza.toppings.add(pepperoni)
your_pizza.toppings.add(pepperoni, mushroom)
當(dāng)從 ?ManyToManyFields
?刪除對(duì)象時(shí),可以使用帶有多個(gè)對(duì)象的 ?remove()
? 來減少 SQL 查詢的數(shù)量。比如:
my_band.members.remove(me, my_friend)
要優(yōu)于:
my_band.members.remove(me)
my_band.members.remove(my_friend)
其中 ?Bands
?和 ?Artists
?有多對(duì)多關(guān)系。
當(dāng)從 ?ManyToManyFields
?里刪除不同的對(duì)象對(duì)時(shí),可以在帶有多種 ?through
?模型實(shí)例的 ?Q
?表達(dá)式上使用 ?delete()
? 來減少 SQL 查詢的數(shù)量。比如:
from django.db.models import Q
PizzaToppingRelationship = Pizza.toppings.through
PizzaToppingRelationship.objects.filter(
Q(pizza=my_pizza, topping=pepperoni) |
Q(pizza=your_pizza, topping=pepperoni) |
Q(pizza=your_pizza, topping=mushroom)
).delete()
要優(yōu)于:
my_pizza.toppings.remove(pepperoni)
your_pizza.toppings.remove(pepperoni, mushroom)
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: