• Django ORM 进行查询操作和性能优化


    一, ORM 的基本操作

    测试数据

    from django.db import models
    
    
    class Publisher(models.Model):
      # 出版社
    name = models.CharField(max_length=32) addr = models.CharField(max_length=32) phone = models.IntegerField def __str__(self): return self.name

    class Author(models.Model):
      # 作者
    name = models.CharField(max_length=16) author_detail = models.OneToOneField("AuthorDetail") books = models.ManyToManyField(to="Book") def __str__(self): return self.name class Book(models.Model):
      # 书籍信息
    title = models.CharField(max_length=6) price = models.DecimalField(max_digits=5, decimal_places=2) publish_day = models.DateField(auto_now_add=True) publisher = models.ForeignKey(to="Publisher", to_field="id") def __str__(self): return self.title class AuthorDetail(models.Model):
      # 作者详情
    city = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.city
    增
     
    models.Tb1.objects.create(c1='xx', c2='oo')  增加一条数据,可以接受字典类型数据 **kwargs
     
    obj = models.Tb1(c1='xx', c2='oo')
    obj.save()
     
     查
     
    models.Tb1.objects.get(id=123)         # 获取单条数据,不存在则报错(不建议)
    models.Tb1.objects.all()               # 获取全部
    models.Tb1.objects.filter(name='seven') # 获取指定条件的数据
    models.Tb1.objects.exclude(name='seven') # 获取指定条件的数据
     
     删
     
    models.Tb1.objects.filter(name='seven').delete() # 删除指定条件的数据
     
     改
    models.Tb1.objects.filter(name='seven').update(gender='0')  # 将指定条件的数据更新,均支持 **kwargs
    obj = models.Tb1.objects.get(id=1)
    obj.c1 = '111'
    obj.save()    

    二, ForeignKey 的使用原因

     约束
     节省硬盘
     但是多表查询会降低速度,大型程序反而不使用外键,而是用单表(约束的时候,通过代码判断)

    extra
    
    extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
       Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,))
       Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
       Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"])
       Entry.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid'])

    F与Q查询

    from django.db.models import F
    models.Tb1.objects.update(num=F('num')+1)
    
        
    Book.objects.all().update(price=F("price")+30) 
    from django.db.models import Q
    con = Q()
     
    q1 = Q()
    q1.connector = 'OR'
    q1.children.append(('id', 1))
    q1.children.append(('id', 10))
    q1.children.append(('id', 9))
     
    q2 = Q()
    q2.connector = 'OR'
    q2.children.append(('c1', 1))
    q2.children.append(('c1', 10))
    q2.children.append(('c1', 9))
     
    con.add(q1, 'AND')
    con.add(q2, 'AND')
     
    models.Tb1.objects.filter(con)
     
    from django.db import connection
    cursor = connection.cursor()
    cursor.execute("""SELECT * from tb where name = %s""", ['Lennon'])
    row = cursor.fetchone()
    

    select_related(self, *fields)

    性能相关:表之间进行join连表操作,一次性获取关联的数据。
        model.tb.objects.all().select_related()
        model.tb.objects.all().select_related('外键字段')
        model.tb.objects.all().select_related('外键字段__外键字段')

    prefetch_related(self, *lookups)

    性能相关:多表连表操作时速度会慢,使用其执行多次SQL查询  在内存中做关联,而不会再做连表查询
               # 第一次 获取所有用户表
               # 第二次 获取用户类型表where id in (用户表中的查到的所有用户ID)
               models.UserInfo.objects.prefetch_related('外键字段')

    annotate(self, *args, **kwargs)(聚合函数)

     from django.db.models import Count, Avg, Max, Min, Sum
     
        v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id'))
        # SELECT u_id, COUNT(ui) AS `uid` FROM UserInfo GROUP BY u_id
     
        v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id')).filter(uid__gt=1)
        # SELECT u_id, COUNT(ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1
     
        v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id',distinct=True)).filter(uid__gt=1)
       # SELECT u_id, COUNT( DISTINCT ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1

    extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)

     Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,))
          Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
          Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"])
          Entry.objects.extra(select={'new_
  • 相关阅读:
    Shell printf 命令
    Shell echo命令
    Shell 基本运算符
    Shell 数组
    Shell 传递参数
    Shell 变量
    Spark基础知识汇总
    DataScientist————汇总篇
    Java的Unsafe类
    java 中文字符和unicode编码值相互转化
  • 原文地址:https://www.cnblogs.com/win-lin08/p/9377573.html
Copyright © 2020-2023  润新知