全部對model object的操做都會根據model的定義翻譯成SQL。sql
Relationship 怎麼定義:數據庫
ManyToOne (和OneToMany是同樣的): ForeignKey , One side access Many: one.many_set (relatedManager)django
OneToOne: OneToOneFieldapp
ManyToMany: ManyToManyField , 只在一邊定義(many.many),在沒有定義的另外一邊訪問時:many.many_set (ManyRelatedManager)ide
OneToOne 用 inner joinfetch
ManyTonOne 用left joinatom
OneToMany 用獨立的select ... in ()翻譯
ManyToMany 用獨立的select ... inner join on ... in()ip
--------------------------------------------------------------------------------------io
合理利用cache, 避免每次用到query_set時都要訪問數據庫
a = models.Customer.objects.all().prefetch_related('products')
// no query happen at all
b = list(a)
// both Customer and products have been retrieved and cached.
a = models.Customer.objects.all()
b = list(a)
// only Customer has been fetched.
for i in b:
print i.products // another query to database to fetch current products, not all products of every customer.
ManyToMany (OneToMany) : prefetch_related (須要另外一條select去數據)
OneToOne (ManyToOne): select_related( 同一條select 加join便可取出全部數據時使用)
---------------------------------------------------------------------------------------
如何打印出SQL?
from django.db import connection
print connection.queries
----------------------------------------------------------------------------------------
bulk insert 怎麼作效率最高?
三種方法:
1. bulk_create (仍是使用django model save, 一次Insert, 一個transaction)
2. transaction.atomic() (一個transaction,屢次save)
3. cursor (本身寫sql, 繞過django model)
第三個方案是最快的應該