• 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)

    第三个方案是最快的应该

  • 相关阅读:
    ssh免密码登陆设置时Authentication refused: bad ownership or modes错误解决方法
    centos7下安装python3
    mongodb基本操作
    mongodb之增删改查
    openfire插件开发之IQHander
    centos7下安装MongoDB4.0
    XMPP节之message,presence,IQ介绍
    linux命令 比较两个文件
    关于内存泄露
    一些术语——依赖倒置•控制反转•依赖注入•面向接口编程
  • 原文地址:https://www.cnblogs.com/lynnge/p/5926048.html
Copyright © 2020-2023  润新知