全部对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)
第三个方案是最快的应该