zoukankan      html  css  js  c++  java
  • Django Models

    所有对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)

    第三个方案是最快的应该

  • 相关阅读:
    MacPE+WinPE-黑苹果之路
    项目已被os x使用 不能打开-黑苹果之路
    X230上安装Yosemite/Win7-黑苹果之路
    SVN-服务器搭建、apache2整合、eclipse使用
    Android开发-Hello World+phonegap(Cordova)
    IOS开发-phonegap上的数据库
    lenovo X230热键功能
    XBox360-双光盘游戏自制GOD
    Kindle3与亚马逊
    iOS开发tips-UIScrollView的Autlayout布局
  • 原文地址:https://www.cnblogs.com/lynnge/p/5926048.html
Copyright © 2011-2022 走看看