所有对model object的操作都会根据model的定义翻译成SQL。
Relationship 怎么定义:
ManyToOne (和OneToMany是一样的): ForeignKey , One side access Many: one.many_set (relatedManager)
OneToOne: OneToOneField
ManyToMany: ManyToManyField , 只在一边定义(many.many),在没有定义的另一边访问时:many.many_set (ManyRelatedManager)
OneToOne 用 inner join
ManyTonOne 用left join
OneToMany 用独立的select ... in ()
ManyToMany 用独立的select ... inner join on ... in()
--------------------------------------------------------------------------------------
合理利用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)
第三个方案是最快的应该