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)

    第三个方案是最快的应该

  • 相关阅读:
    tee命令
    linux优化之SElinux关闭
    (1)使用bash脚本实现批量添加用户
    Django admin管理工具的使用、定制及源码解析
    Mysql常见命令
    树梅派
    19道Python循环遍历,while,for语句测试题,网上看到的题目,自己不看答案全部做了一次,总共3个小时左右
    9*9的矩形,中间有个星号,按不同方向键,星星对应移动
    app在admin中显示成我们想要的中文名
    九九乘法表
  • 原文地址:https://www.cnblogs.com/lynnge/p/5926048.html
Copyright © 2011-2022 走看看